im-browser.js 940 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define('leancloud-realtime', ['exports'], factory) :
  4. (global = global || self, factory(global.AV = global.AV || {}));
  5. }(this, (function (exports) { 'use strict';
  6. var define = undefined;
  7. var require = require || function(id) {throw new Error('Unexpected required ' + id)};
  8. var process = (typeof window !== 'undefined' && window.process) || {};
  9. process.env = process.env || {};
  10. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  11. function unwrapExports (x) {
  12. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  13. }
  14. function createCommonjsModule(fn, basedir, module) {
  15. return module = {
  16. path: basedir,
  17. exports: {},
  18. require: function (path, base) {
  19. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  20. }
  21. }, fn(module, module.exports), module.exports;
  22. }
  23. function getCjsExportFromNamespace (n) {
  24. return n && n['default'] || n;
  25. }
  26. function commonjsRequire () {
  27. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  28. }
  29. var _typeof_1 = createCommonjsModule(function (module) {
  30. function _typeof(obj) {
  31. "@babel/helpers - typeof";
  32. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  33. module.exports = _typeof = function _typeof(obj) {
  34. return typeof obj;
  35. };
  36. } else {
  37. module.exports = _typeof = function _typeof(obj) {
  38. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  39. };
  40. }
  41. return _typeof(obj);
  42. }
  43. module.exports = _typeof;
  44. });
  45. var componentEmitter = createCommonjsModule(function (module) {
  46. /**
  47. * Expose `Emitter`.
  48. */
  49. {
  50. module.exports = Emitter;
  51. }
  52. /**
  53. * Initialize a new `Emitter`.
  54. *
  55. * @api public
  56. */
  57. function Emitter(obj) {
  58. if (obj) return mixin(obj);
  59. }
  60. /**
  61. * Mixin the emitter properties.
  62. *
  63. * @param {Object} obj
  64. * @return {Object}
  65. * @api private
  66. */
  67. function mixin(obj) {
  68. for (var key in Emitter.prototype) {
  69. obj[key] = Emitter.prototype[key];
  70. }
  71. return obj;
  72. }
  73. /**
  74. * Listen on the given `event` with `fn`.
  75. *
  76. * @param {String} event
  77. * @param {Function} fn
  78. * @return {Emitter}
  79. * @api public
  80. */
  81. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  82. this._callbacks = this._callbacks || {};
  83. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  84. return this;
  85. };
  86. /**
  87. * Adds an `event` listener that will be invoked a single
  88. * time then automatically removed.
  89. *
  90. * @param {String} event
  91. * @param {Function} fn
  92. * @return {Emitter}
  93. * @api public
  94. */
  95. Emitter.prototype.once = function (event, fn) {
  96. function on() {
  97. this.off(event, on);
  98. fn.apply(this, arguments);
  99. }
  100. on.fn = fn;
  101. this.on(event, on);
  102. return this;
  103. };
  104. /**
  105. * Remove the given callback for `event` or all
  106. * registered callbacks.
  107. *
  108. * @param {String} event
  109. * @param {Function} fn
  110. * @return {Emitter}
  111. * @api public
  112. */
  113. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  114. this._callbacks = this._callbacks || {}; // all
  115. if (0 == arguments.length) {
  116. this._callbacks = {};
  117. return this;
  118. } // specific event
  119. var callbacks = this._callbacks['$' + event];
  120. if (!callbacks) return this; // remove all handlers
  121. if (1 == arguments.length) {
  122. delete this._callbacks['$' + event];
  123. return this;
  124. } // remove specific handler
  125. var cb;
  126. for (var i = 0; i < callbacks.length; i++) {
  127. cb = callbacks[i];
  128. if (cb === fn || cb.fn === fn) {
  129. callbacks.splice(i, 1);
  130. break;
  131. }
  132. } // Remove event specific arrays for event types that no
  133. // one is subscribed for to avoid memory leak.
  134. if (callbacks.length === 0) {
  135. delete this._callbacks['$' + event];
  136. }
  137. return this;
  138. };
  139. /**
  140. * Emit `event` with the given args.
  141. *
  142. * @param {String} event
  143. * @param {Mixed} ...
  144. * @return {Emitter}
  145. */
  146. Emitter.prototype.emit = function (event) {
  147. this._callbacks = this._callbacks || {};
  148. var args = new Array(arguments.length - 1),
  149. callbacks = this._callbacks['$' + event];
  150. for (var i = 1; i < arguments.length; i++) {
  151. args[i - 1] = arguments[i];
  152. }
  153. if (callbacks) {
  154. callbacks = callbacks.slice(0);
  155. for (var i = 0, len = callbacks.length; i < len; ++i) {
  156. callbacks[i].apply(this, args);
  157. }
  158. }
  159. return this;
  160. };
  161. /**
  162. * Return array of callbacks for `event`.
  163. *
  164. * @param {String} event
  165. * @return {Array}
  166. * @api public
  167. */
  168. Emitter.prototype.listeners = function (event) {
  169. this._callbacks = this._callbacks || {};
  170. return this._callbacks['$' + event] || [];
  171. };
  172. /**
  173. * Check if this emitter has `event` handlers.
  174. *
  175. * @param {String} event
  176. * @return {Boolean}
  177. * @api public
  178. */
  179. Emitter.prototype.hasListeners = function (event) {
  180. return !!this.listeners(event).length;
  181. };
  182. });
  183. var fastSafeStringify = stringify;
  184. stringify.default = stringify;
  185. stringify.stable = deterministicStringify;
  186. stringify.stableStringify = deterministicStringify;
  187. var arr = [];
  188. var replacerStack = [];
  189. // Regular stringify
  190. function stringify (obj, replacer, spacer) {
  191. decirc(obj, '', [], undefined);
  192. var res;
  193. if (replacerStack.length === 0) {
  194. res = JSON.stringify(obj, replacer, spacer);
  195. } else {
  196. res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
  197. }
  198. while (arr.length !== 0) {
  199. var part = arr.pop();
  200. if (part.length === 4) {
  201. Object.defineProperty(part[0], part[1], part[3]);
  202. } else {
  203. part[0][part[1]] = part[2];
  204. }
  205. }
  206. return res
  207. }
  208. function decirc (val, k, stack, parent) {
  209. var i;
  210. if (typeof val === 'object' && val !== null) {
  211. for (i = 0; i < stack.length; i++) {
  212. if (stack[i] === val) {
  213. var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
  214. if (propertyDescriptor.get !== undefined) {
  215. if (propertyDescriptor.configurable) {
  216. Object.defineProperty(parent, k, { value: '[Circular]' });
  217. arr.push([parent, k, val, propertyDescriptor]);
  218. } else {
  219. replacerStack.push([val, k]);
  220. }
  221. } else {
  222. parent[k] = '[Circular]';
  223. arr.push([parent, k, val]);
  224. }
  225. return
  226. }
  227. }
  228. stack.push(val);
  229. // Optimize for Arrays. Big arrays could kill the performance otherwise!
  230. if (Array.isArray(val)) {
  231. for (i = 0; i < val.length; i++) {
  232. decirc(val[i], i, stack, val);
  233. }
  234. } else {
  235. var keys = Object.keys(val);
  236. for (i = 0; i < keys.length; i++) {
  237. var key = keys[i];
  238. decirc(val[key], key, stack, val);
  239. }
  240. }
  241. stack.pop();
  242. }
  243. }
  244. // Stable-stringify
  245. function compareFunction (a, b) {
  246. if (a < b) {
  247. return -1
  248. }
  249. if (a > b) {
  250. return 1
  251. }
  252. return 0
  253. }
  254. function deterministicStringify (obj, replacer, spacer) {
  255. var tmp = deterministicDecirc(obj, '', [], undefined) || obj;
  256. var res;
  257. if (replacerStack.length === 0) {
  258. res = JSON.stringify(tmp, replacer, spacer);
  259. } else {
  260. res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
  261. }
  262. while (arr.length !== 0) {
  263. var part = arr.pop();
  264. if (part.length === 4) {
  265. Object.defineProperty(part[0], part[1], part[3]);
  266. } else {
  267. part[0][part[1]] = part[2];
  268. }
  269. }
  270. return res
  271. }
  272. function deterministicDecirc (val, k, stack, parent) {
  273. var i;
  274. if (typeof val === 'object' && val !== null) {
  275. for (i = 0; i < stack.length; i++) {
  276. if (stack[i] === val) {
  277. var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
  278. if (propertyDescriptor.get !== undefined) {
  279. if (propertyDescriptor.configurable) {
  280. Object.defineProperty(parent, k, { value: '[Circular]' });
  281. arr.push([parent, k, val, propertyDescriptor]);
  282. } else {
  283. replacerStack.push([val, k]);
  284. }
  285. } else {
  286. parent[k] = '[Circular]';
  287. arr.push([parent, k, val]);
  288. }
  289. return
  290. }
  291. }
  292. if (typeof val.toJSON === 'function') {
  293. return
  294. }
  295. stack.push(val);
  296. // Optimize for Arrays. Big arrays could kill the performance otherwise!
  297. if (Array.isArray(val)) {
  298. for (i = 0; i < val.length; i++) {
  299. deterministicDecirc(val[i], i, stack, val);
  300. }
  301. } else {
  302. // Create a temporary object in the required way
  303. var tmp = {};
  304. var keys = Object.keys(val).sort(compareFunction);
  305. for (i = 0; i < keys.length; i++) {
  306. var key = keys[i];
  307. deterministicDecirc(val[key], key, stack, val);
  308. tmp[key] = val[key];
  309. }
  310. if (parent !== undefined) {
  311. arr.push([parent, k, val]);
  312. parent[k] = tmp;
  313. } else {
  314. return tmp
  315. }
  316. }
  317. stack.pop();
  318. }
  319. }
  320. // wraps replacer function to handle values we couldn't replace
  321. // and mark them as [Circular]
  322. function replaceGetterValues (replacer) {
  323. replacer = replacer !== undefined ? replacer : function (k, v) { return v };
  324. return function (key, val) {
  325. if (replacerStack.length > 0) {
  326. for (var i = 0; i < replacerStack.length; i++) {
  327. var part = replacerStack[i];
  328. if (part[1] === key && part[0] === val) {
  329. val = '[Circular]';
  330. replacerStack.splice(i, 1);
  331. break
  332. }
  333. }
  334. }
  335. return replacer.call(this, key, val)
  336. }
  337. }
  338. function _typeof(obj) {
  339. if (typeof Symbol === "function" && _typeof_1(Symbol.iterator) === "symbol") {
  340. _typeof = function _typeof(obj) {
  341. return _typeof_1(obj);
  342. };
  343. } else {
  344. _typeof = function _typeof(obj) {
  345. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof_1(obj);
  346. };
  347. }
  348. return _typeof(obj);
  349. }
  350. /**
  351. * Check if `obj` is an object.
  352. *
  353. * @param {Object} obj
  354. * @return {Boolean}
  355. * @api private
  356. */
  357. function isObject(obj) {
  358. return obj !== null && _typeof(obj) === 'object';
  359. }
  360. var isObject_1 = isObject;
  361. function _typeof$1(obj) {
  362. if (typeof Symbol === "function" && _typeof_1(Symbol.iterator) === "symbol") {
  363. _typeof$1 = function _typeof(obj) {
  364. return _typeof_1(obj);
  365. };
  366. } else {
  367. _typeof$1 = function _typeof(obj) {
  368. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof_1(obj);
  369. };
  370. }
  371. return _typeof$1(obj);
  372. }
  373. /**
  374. * Module of mixed-in functions shared between node and client code
  375. */
  376. /**
  377. * Expose `RequestBase`.
  378. */
  379. var requestBase = RequestBase;
  380. /**
  381. * Initialize a new `RequestBase`.
  382. *
  383. * @api public
  384. */
  385. function RequestBase(obj) {
  386. if (obj) return mixin(obj);
  387. }
  388. /**
  389. * Mixin the prototype properties.
  390. *
  391. * @param {Object} obj
  392. * @return {Object}
  393. * @api private
  394. */
  395. function mixin(obj) {
  396. for (var key in RequestBase.prototype) {
  397. if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
  398. }
  399. return obj;
  400. }
  401. /**
  402. * Clear previous timeout.
  403. *
  404. * @return {Request} for chaining
  405. * @api public
  406. */
  407. RequestBase.prototype.clearTimeout = function () {
  408. clearTimeout(this._timer);
  409. clearTimeout(this._responseTimeoutTimer);
  410. clearTimeout(this._uploadTimeoutTimer);
  411. delete this._timer;
  412. delete this._responseTimeoutTimer;
  413. delete this._uploadTimeoutTimer;
  414. return this;
  415. };
  416. /**
  417. * Override default response body parser
  418. *
  419. * This function will be called to convert incoming data into request.body
  420. *
  421. * @param {Function}
  422. * @api public
  423. */
  424. RequestBase.prototype.parse = function (fn) {
  425. this._parser = fn;
  426. return this;
  427. };
  428. /**
  429. * Set format of binary response body.
  430. * In browser valid formats are 'blob' and 'arraybuffer',
  431. * which return Blob and ArrayBuffer, respectively.
  432. *
  433. * In Node all values result in Buffer.
  434. *
  435. * Examples:
  436. *
  437. * req.get('/')
  438. * .responseType('blob')
  439. * .end(callback);
  440. *
  441. * @param {String} val
  442. * @return {Request} for chaining
  443. * @api public
  444. */
  445. RequestBase.prototype.responseType = function (val) {
  446. this._responseType = val;
  447. return this;
  448. };
  449. /**
  450. * Override default request body serializer
  451. *
  452. * This function will be called to convert data set via .send or .attach into payload to send
  453. *
  454. * @param {Function}
  455. * @api public
  456. */
  457. RequestBase.prototype.serialize = function (fn) {
  458. this._serializer = fn;
  459. return this;
  460. };
  461. /**
  462. * Set timeouts.
  463. *
  464. * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
  465. * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
  466. * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
  467. *
  468. * Value of 0 or false means no timeout.
  469. *
  470. * @param {Number|Object} ms or {response, deadline}
  471. * @return {Request} for chaining
  472. * @api public
  473. */
  474. RequestBase.prototype.timeout = function (options) {
  475. if (!options || _typeof$1(options) !== 'object') {
  476. this._timeout = options;
  477. this._responseTimeout = 0;
  478. this._uploadTimeout = 0;
  479. return this;
  480. }
  481. for (var option in options) {
  482. if (Object.prototype.hasOwnProperty.call(options, option)) {
  483. switch (option) {
  484. case 'deadline':
  485. this._timeout = options.deadline;
  486. break;
  487. case 'response':
  488. this._responseTimeout = options.response;
  489. break;
  490. case 'upload':
  491. this._uploadTimeout = options.upload;
  492. break;
  493. default:
  494. console.warn('Unknown timeout option', option);
  495. }
  496. }
  497. }
  498. return this;
  499. };
  500. /**
  501. * Set number of retry attempts on error.
  502. *
  503. * Failed requests will be retried 'count' times if timeout or err.code >= 500.
  504. *
  505. * @param {Number} count
  506. * @param {Function} [fn]
  507. * @return {Request} for chaining
  508. * @api public
  509. */
  510. RequestBase.prototype.retry = function (count, fn) {
  511. // Default to 1 if no count passed or true
  512. if (arguments.length === 0 || count === true) count = 1;
  513. if (count <= 0) count = 0;
  514. this._maxRetries = count;
  515. this._retries = 0;
  516. this._retryCallback = fn;
  517. return this;
  518. };
  519. var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
  520. /**
  521. * Determine if a request should be retried.
  522. * (Borrowed from segmentio/superagent-retry)
  523. *
  524. * @param {Error} err an error
  525. * @param {Response} [res] response
  526. * @returns {Boolean} if segment should be retried
  527. */
  528. RequestBase.prototype._shouldRetry = function (err, res) {
  529. if (!this._maxRetries || this._retries++ >= this._maxRetries) {
  530. return false;
  531. }
  532. if (this._retryCallback) {
  533. try {
  534. var override = this._retryCallback(err, res);
  535. if (override === true) return true;
  536. if (override === false) return false; // undefined falls back to defaults
  537. } catch (err_) {
  538. console.error(err_);
  539. }
  540. }
  541. if (res && res.status && res.status >= 500 && res.status !== 501) return true;
  542. if (err) {
  543. if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout
  544. if (err.timeout && err.code === 'ECONNABORTED') return true;
  545. if (err.crossDomain) return true;
  546. }
  547. return false;
  548. };
  549. /**
  550. * Retry request
  551. *
  552. * @return {Request} for chaining
  553. * @api private
  554. */
  555. RequestBase.prototype._retry = function () {
  556. this.clearTimeout(); // node
  557. if (this.req) {
  558. this.req = null;
  559. this.req = this.request();
  560. }
  561. this._aborted = false;
  562. this.timedout = false;
  563. this.timedoutError = null;
  564. return this._end();
  565. };
  566. /**
  567. * Promise support
  568. *
  569. * @param {Function} resolve
  570. * @param {Function} [reject]
  571. * @return {Request}
  572. */
  573. RequestBase.prototype.then = function (resolve, reject) {
  574. var _this = this;
  575. if (!this._fullfilledPromise) {
  576. var self = this;
  577. if (this._endCalled) {
  578. console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
  579. }
  580. this._fullfilledPromise = new Promise(function (resolve, reject) {
  581. self.on('abort', function () {
  582. if (_this.timedout && _this.timedoutError) {
  583. reject(_this.timedoutError);
  584. return;
  585. }
  586. var err = new Error('Aborted');
  587. err.code = 'ABORTED';
  588. err.status = _this.status;
  589. err.method = _this.method;
  590. err.url = _this.url;
  591. reject(err);
  592. });
  593. self.end(function (err, res) {
  594. if (err) reject(err);else resolve(res);
  595. });
  596. });
  597. }
  598. return this._fullfilledPromise.then(resolve, reject);
  599. };
  600. RequestBase.prototype["catch"] = function (cb) {
  601. return this.then(undefined, cb);
  602. };
  603. /**
  604. * Allow for extension
  605. */
  606. RequestBase.prototype.use = function (fn) {
  607. fn(this);
  608. return this;
  609. };
  610. RequestBase.prototype.ok = function (cb) {
  611. if (typeof cb !== 'function') throw new Error('Callback required');
  612. this._okCallback = cb;
  613. return this;
  614. };
  615. RequestBase.prototype._isResponseOK = function (res) {
  616. if (!res) {
  617. return false;
  618. }
  619. if (this._okCallback) {
  620. return this._okCallback(res);
  621. }
  622. return res.status >= 200 && res.status < 300;
  623. };
  624. /**
  625. * Get request header `field`.
  626. * Case-insensitive.
  627. *
  628. * @param {String} field
  629. * @return {String}
  630. * @api public
  631. */
  632. RequestBase.prototype.get = function (field) {
  633. return this._header[field.toLowerCase()];
  634. };
  635. /**
  636. * Get case-insensitive header `field` value.
  637. * This is a deprecated internal API. Use `.get(field)` instead.
  638. *
  639. * (getHeader is no longer used internally by the superagent code base)
  640. *
  641. * @param {String} field
  642. * @return {String}
  643. * @api private
  644. * @deprecated
  645. */
  646. RequestBase.prototype.getHeader = RequestBase.prototype.get;
  647. /**
  648. * Set header `field` to `val`, or multiple fields with one object.
  649. * Case-insensitive.
  650. *
  651. * Examples:
  652. *
  653. * req.get('/')
  654. * .set('Accept', 'application/json')
  655. * .set('X-API-Key', 'foobar')
  656. * .end(callback);
  657. *
  658. * req.get('/')
  659. * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
  660. * .end(callback);
  661. *
  662. * @param {String|Object} field
  663. * @param {String} val
  664. * @return {Request} for chaining
  665. * @api public
  666. */
  667. RequestBase.prototype.set = function (field, val) {
  668. if (isObject_1(field)) {
  669. for (var key in field) {
  670. if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
  671. }
  672. return this;
  673. }
  674. this._header[field.toLowerCase()] = val;
  675. this.header[field] = val;
  676. return this;
  677. };
  678. /**
  679. * Remove header `field`.
  680. * Case-insensitive.
  681. *
  682. * Example:
  683. *
  684. * req.get('/')
  685. * .unset('User-Agent')
  686. * .end(callback);
  687. *
  688. * @param {String} field field name
  689. */
  690. RequestBase.prototype.unset = function (field) {
  691. delete this._header[field.toLowerCase()];
  692. delete this.header[field];
  693. return this;
  694. };
  695. /**
  696. * Write the field `name` and `val`, or multiple fields with one object
  697. * for "multipart/form-data" request bodies.
  698. *
  699. * ``` js
  700. * request.post('/upload')
  701. * .field('foo', 'bar')
  702. * .end(callback);
  703. *
  704. * request.post('/upload')
  705. * .field({ foo: 'bar', baz: 'qux' })
  706. * .end(callback);
  707. * ```
  708. *
  709. * @param {String|Object} name name of field
  710. * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
  711. * @return {Request} for chaining
  712. * @api public
  713. */
  714. RequestBase.prototype.field = function (name, val) {
  715. // name should be either a string or an object.
  716. if (name === null || undefined === name) {
  717. throw new Error('.field(name, val) name can not be empty');
  718. }
  719. if (this._data) {
  720. throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
  721. }
  722. if (isObject_1(name)) {
  723. for (var key in name) {
  724. if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
  725. }
  726. return this;
  727. }
  728. if (Array.isArray(val)) {
  729. for (var i in val) {
  730. if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
  731. }
  732. return this;
  733. } // val should be defined now
  734. if (val === null || undefined === val) {
  735. throw new Error('.field(name, val) val can not be empty');
  736. }
  737. if (typeof val === 'boolean') {
  738. val = String(val);
  739. }
  740. this._getFormData().append(name, val);
  741. return this;
  742. };
  743. /**
  744. * Abort the request, and clear potential timeout.
  745. *
  746. * @return {Request} request
  747. * @api public
  748. */
  749. RequestBase.prototype.abort = function () {
  750. if (this._aborted) {
  751. return this;
  752. }
  753. this._aborted = true;
  754. if (this.xhr) this.xhr.abort(); // browser
  755. if (this.req) this.req.abort(); // node
  756. this.clearTimeout();
  757. this.emit('abort');
  758. return this;
  759. };
  760. RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
  761. switch (options.type) {
  762. case 'basic':
  763. this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
  764. break;
  765. case 'auto':
  766. this.username = user;
  767. this.password = pass;
  768. break;
  769. case 'bearer':
  770. // usage would be .auth(accessToken, { type: 'bearer' })
  771. this.set('Authorization', "Bearer ".concat(user));
  772. break;
  773. }
  774. return this;
  775. };
  776. /**
  777. * Enable transmission of cookies with x-domain requests.
  778. *
  779. * Note that for this to work the origin must not be
  780. * using "Access-Control-Allow-Origin" with a wildcard,
  781. * and also must set "Access-Control-Allow-Credentials"
  782. * to "true".
  783. *
  784. * @api public
  785. */
  786. RequestBase.prototype.withCredentials = function (on) {
  787. // This is browser-only functionality. Node side is no-op.
  788. if (on === undefined) on = true;
  789. this._withCredentials = on;
  790. return this;
  791. };
  792. /**
  793. * Set the max redirects to `n`. Does nothing in browser XHR implementation.
  794. *
  795. * @param {Number} n
  796. * @return {Request} for chaining
  797. * @api public
  798. */
  799. RequestBase.prototype.redirects = function (n) {
  800. this._maxRedirects = n;
  801. return this;
  802. };
  803. /**
  804. * Maximum size of buffered response body, in bytes. Counts uncompressed size.
  805. * Default 200MB.
  806. *
  807. * @param {Number} n number of bytes
  808. * @return {Request} for chaining
  809. */
  810. RequestBase.prototype.maxResponseSize = function (n) {
  811. if (typeof n !== 'number') {
  812. throw new TypeError('Invalid argument');
  813. }
  814. this._maxResponseSize = n;
  815. return this;
  816. };
  817. /**
  818. * Convert to a plain javascript object (not JSON string) of scalar properties.
  819. * Note as this method is designed to return a useful non-this value,
  820. * it cannot be chained.
  821. *
  822. * @return {Object} describing method, url, and data of this request
  823. * @api public
  824. */
  825. RequestBase.prototype.toJSON = function () {
  826. return {
  827. method: this.method,
  828. url: this.url,
  829. data: this._data,
  830. headers: this._header
  831. };
  832. };
  833. /**
  834. * Send `data` as the request body, defaulting the `.type()` to "json" when
  835. * an object is given.
  836. *
  837. * Examples:
  838. *
  839. * // manual json
  840. * request.post('/user')
  841. * .type('json')
  842. * .send('{"name":"tj"}')
  843. * .end(callback)
  844. *
  845. * // auto json
  846. * request.post('/user')
  847. * .send({ name: 'tj' })
  848. * .end(callback)
  849. *
  850. * // manual x-www-form-urlencoded
  851. * request.post('/user')
  852. * .type('form')
  853. * .send('name=tj')
  854. * .end(callback)
  855. *
  856. * // auto x-www-form-urlencoded
  857. * request.post('/user')
  858. * .type('form')
  859. * .send({ name: 'tj' })
  860. * .end(callback)
  861. *
  862. * // defaults to x-www-form-urlencoded
  863. * request.post('/user')
  864. * .send('name=tobi')
  865. * .send('species=ferret')
  866. * .end(callback)
  867. *
  868. * @param {String|Object} data
  869. * @return {Request} for chaining
  870. * @api public
  871. */
  872. // eslint-disable-next-line complexity
  873. RequestBase.prototype.send = function (data) {
  874. var isObj = isObject_1(data);
  875. var type = this._header['content-type'];
  876. if (this._formData) {
  877. throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
  878. }
  879. if (isObj && !this._data) {
  880. if (Array.isArray(data)) {
  881. this._data = [];
  882. } else if (!this._isHost(data)) {
  883. this._data = {};
  884. }
  885. } else if (data && this._data && this._isHost(this._data)) {
  886. throw new Error("Can't merge these send calls");
  887. } // merge
  888. if (isObj && isObject_1(this._data)) {
  889. for (var key in data) {
  890. if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
  891. }
  892. } else if (typeof data === 'string') {
  893. // default to x-www-form-urlencoded
  894. if (!type) this.type('form');
  895. type = this._header['content-type'];
  896. if (type === 'application/x-www-form-urlencoded') {
  897. this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
  898. } else {
  899. this._data = (this._data || '') + data;
  900. }
  901. } else {
  902. this._data = data;
  903. }
  904. if (!isObj || this._isHost(data)) {
  905. return this;
  906. } // default to json
  907. if (!type) this.type('json');
  908. return this;
  909. };
  910. /**
  911. * Sort `querystring` by the sort function
  912. *
  913. *
  914. * Examples:
  915. *
  916. * // default order
  917. * request.get('/user')
  918. * .query('name=Nick')
  919. * .query('search=Manny')
  920. * .sortQuery()
  921. * .end(callback)
  922. *
  923. * // customized sort function
  924. * request.get('/user')
  925. * .query('name=Nick')
  926. * .query('search=Manny')
  927. * .sortQuery(function(a, b){
  928. * return a.length - b.length;
  929. * })
  930. * .end(callback)
  931. *
  932. *
  933. * @param {Function} sort
  934. * @return {Request} for chaining
  935. * @api public
  936. */
  937. RequestBase.prototype.sortQuery = function (sort) {
  938. // _sort default to true but otherwise can be a function or boolean
  939. this._sort = typeof sort === 'undefined' ? true : sort;
  940. return this;
  941. };
  942. /**
  943. * Compose querystring to append to req.url
  944. *
  945. * @api private
  946. */
  947. RequestBase.prototype._finalizeQueryString = function () {
  948. var query = this._query.join('&');
  949. if (query) {
  950. this.url += (this.url.includes('?') ? '&' : '?') + query;
  951. }
  952. this._query.length = 0; // Makes the call idempotent
  953. if (this._sort) {
  954. var index = this.url.indexOf('?');
  955. if (index >= 0) {
  956. var queryArr = this.url.slice(index + 1).split('&');
  957. if (typeof this._sort === 'function') {
  958. queryArr.sort(this._sort);
  959. } else {
  960. queryArr.sort();
  961. }
  962. this.url = this.url.slice(0, index) + '?' + queryArr.join('&');
  963. }
  964. }
  965. }; // For backwards compat only
  966. RequestBase.prototype._appendQueryString = function () {
  967. console.warn('Unsupported');
  968. };
  969. /**
  970. * Invoke callback with timeout error.
  971. *
  972. * @api private
  973. */
  974. RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
  975. if (this._aborted) {
  976. return;
  977. }
  978. var err = new Error("".concat(reason + timeout, "ms exceeded"));
  979. err.timeout = timeout;
  980. err.code = 'ECONNABORTED';
  981. err.errno = errno;
  982. this.timedout = true;
  983. this.timedoutError = err;
  984. this.abort();
  985. this.callback(err);
  986. };
  987. RequestBase.prototype._setTimeouts = function () {
  988. var self = this; // deadline
  989. if (this._timeout && !this._timer) {
  990. this._timer = setTimeout(function () {
  991. self._timeoutError('Timeout of ', self._timeout, 'ETIME');
  992. }, this._timeout);
  993. } // response timeout
  994. if (this._responseTimeout && !this._responseTimeoutTimer) {
  995. this._responseTimeoutTimer = setTimeout(function () {
  996. self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
  997. }, this._responseTimeout);
  998. }
  999. };
  1000. /**
  1001. * Return the mime type for the given `str`.
  1002. *
  1003. * @param {String} str
  1004. * @return {String}
  1005. * @api private
  1006. */
  1007. var type = function type(str) {
  1008. return str.split(/ *; */).shift();
  1009. };
  1010. /**
  1011. * Return header field parameters.
  1012. *
  1013. * @param {String} str
  1014. * @return {Object}
  1015. * @api private
  1016. */
  1017. var params = function params(str) {
  1018. return str.split(/ *; */).reduce(function (obj, str) {
  1019. var parts = str.split(/ *= */);
  1020. var key = parts.shift();
  1021. var val = parts.shift();
  1022. if (key && val) obj[key] = val;
  1023. return obj;
  1024. }, {});
  1025. };
  1026. /**
  1027. * Parse Link header fields.
  1028. *
  1029. * @param {String} str
  1030. * @return {Object}
  1031. * @api private
  1032. */
  1033. var parseLinks = function parseLinks(str) {
  1034. return str.split(/ *, */).reduce(function (obj, str) {
  1035. var parts = str.split(/ *; */);
  1036. var url = parts[0].slice(1, -1);
  1037. var rel = parts[1].split(/ *= */)[1].slice(1, -1);
  1038. obj[rel] = url;
  1039. return obj;
  1040. }, {});
  1041. };
  1042. /**
  1043. * Strip content related fields from `header`.
  1044. *
  1045. * @param {Object} header
  1046. * @return {Object} header
  1047. * @api private
  1048. */
  1049. var cleanHeader = function cleanHeader(header, changesOrigin) {
  1050. delete header['content-type'];
  1051. delete header['content-length'];
  1052. delete header['transfer-encoding'];
  1053. delete header.host; // secuirty
  1054. if (changesOrigin) {
  1055. delete header.authorization;
  1056. delete header.cookie;
  1057. }
  1058. return header;
  1059. };
  1060. var utils = {
  1061. type: type,
  1062. params: params,
  1063. parseLinks: parseLinks,
  1064. cleanHeader: cleanHeader
  1065. };
  1066. /**
  1067. * Module dependencies.
  1068. */
  1069. /**
  1070. * Expose `ResponseBase`.
  1071. */
  1072. var responseBase = ResponseBase;
  1073. /**
  1074. * Initialize a new `ResponseBase`.
  1075. *
  1076. * @api public
  1077. */
  1078. function ResponseBase(obj) {
  1079. if (obj) return mixin$1(obj);
  1080. }
  1081. /**
  1082. * Mixin the prototype properties.
  1083. *
  1084. * @param {Object} obj
  1085. * @return {Object}
  1086. * @api private
  1087. */
  1088. function mixin$1(obj) {
  1089. for (var key in ResponseBase.prototype) {
  1090. if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
  1091. }
  1092. return obj;
  1093. }
  1094. /**
  1095. * Get case-insensitive `field` value.
  1096. *
  1097. * @param {String} field
  1098. * @return {String}
  1099. * @api public
  1100. */
  1101. ResponseBase.prototype.get = function (field) {
  1102. return this.header[field.toLowerCase()];
  1103. };
  1104. /**
  1105. * Set header related properties:
  1106. *
  1107. * - `.type` the content type without params
  1108. *
  1109. * A response of "Content-Type: text/plain; charset=utf-8"
  1110. * will provide you with a `.type` of "text/plain".
  1111. *
  1112. * @param {Object} header
  1113. * @api private
  1114. */
  1115. ResponseBase.prototype._setHeaderProperties = function (header) {
  1116. // TODO: moar!
  1117. // TODO: make this a util
  1118. // content-type
  1119. var ct = header['content-type'] || '';
  1120. this.type = utils.type(ct); // params
  1121. var params = utils.params(ct);
  1122. for (var key in params) {
  1123. if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
  1124. }
  1125. this.links = {}; // links
  1126. try {
  1127. if (header.link) {
  1128. this.links = utils.parseLinks(header.link);
  1129. }
  1130. } catch (_unused) {// ignore
  1131. }
  1132. };
  1133. /**
  1134. * Set flags such as `.ok` based on `status`.
  1135. *
  1136. * For example a 2xx response will give you a `.ok` of __true__
  1137. * whereas 5xx will be __false__ and `.error` will be __true__. The
  1138. * `.clientError` and `.serverError` are also available to be more
  1139. * specific, and `.statusType` is the class of error ranging from 1..5
  1140. * sometimes useful for mapping respond colors etc.
  1141. *
  1142. * "sugar" properties are also defined for common cases. Currently providing:
  1143. *
  1144. * - .noContent
  1145. * - .badRequest
  1146. * - .unauthorized
  1147. * - .notAcceptable
  1148. * - .notFound
  1149. *
  1150. * @param {Number} status
  1151. * @api private
  1152. */
  1153. ResponseBase.prototype._setStatusProperties = function (status) {
  1154. var type = status / 100 | 0; // status / class
  1155. this.statusCode = status;
  1156. this.status = this.statusCode;
  1157. this.statusType = type; // basics
  1158. this.info = type === 1;
  1159. this.ok = type === 2;
  1160. this.redirect = type === 3;
  1161. this.clientError = type === 4;
  1162. this.serverError = type === 5;
  1163. this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
  1164. this.created = status === 201;
  1165. this.accepted = status === 202;
  1166. this.noContent = status === 204;
  1167. this.badRequest = status === 400;
  1168. this.unauthorized = status === 401;
  1169. this.notAcceptable = status === 406;
  1170. this.forbidden = status === 403;
  1171. this.notFound = status === 404;
  1172. this.unprocessableEntity = status === 422;
  1173. };
  1174. function _toConsumableArray(arr) {
  1175. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  1176. }
  1177. function _nonIterableSpread() {
  1178. throw new TypeError("Invalid attempt to spread non-iterable instance");
  1179. }
  1180. function _iterableToArray(iter) {
  1181. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  1182. }
  1183. function _arrayWithoutHoles(arr) {
  1184. if (Array.isArray(arr)) {
  1185. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  1186. arr2[i] = arr[i];
  1187. }
  1188. return arr2;
  1189. }
  1190. }
  1191. function Agent() {
  1192. this._defaults = [];
  1193. }
  1194. ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) {
  1195. // Default setting for all requests from this agent
  1196. Agent.prototype[fn] = function () {
  1197. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  1198. args[_key] = arguments[_key];
  1199. }
  1200. this._defaults.push({
  1201. fn: fn,
  1202. args: args
  1203. });
  1204. return this;
  1205. };
  1206. });
  1207. Agent.prototype._setDefaults = function (req) {
  1208. this._defaults.forEach(function (def) {
  1209. req[def.fn].apply(req, _toConsumableArray(def.args));
  1210. });
  1211. };
  1212. var agentBase = Agent;
  1213. var client = createCommonjsModule(function (module, exports) {
  1214. function _typeof(obj) {
  1215. if (typeof Symbol === "function" && _typeof_1(Symbol.iterator) === "symbol") {
  1216. _typeof = function _typeof(obj) {
  1217. return _typeof_1(obj);
  1218. };
  1219. } else {
  1220. _typeof = function _typeof(obj) {
  1221. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof_1(obj);
  1222. };
  1223. }
  1224. return _typeof(obj);
  1225. }
  1226. /**
  1227. * Root reference for iframes.
  1228. */
  1229. var root;
  1230. if (typeof window !== 'undefined') {
  1231. // Browser window
  1232. root = window;
  1233. } else if (typeof self === 'undefined') {
  1234. // Other environments
  1235. console.warn('Using browser-only version of superagent in non-browser environment');
  1236. root = void 0;
  1237. } else {
  1238. // Web Worker
  1239. root = self;
  1240. }
  1241. /**
  1242. * Noop.
  1243. */
  1244. function noop() {}
  1245. /**
  1246. * Expose `request`.
  1247. */
  1248. module.exports = function (method, url) {
  1249. // callback
  1250. if (typeof url === 'function') {
  1251. return new exports.Request('GET', method).end(url);
  1252. } // url first
  1253. if (arguments.length === 1) {
  1254. return new exports.Request('GET', method);
  1255. }
  1256. return new exports.Request(method, url);
  1257. };
  1258. exports = module.exports;
  1259. var request = exports;
  1260. exports.Request = Request;
  1261. /**
  1262. * Determine XHR.
  1263. */
  1264. request.getXHR = function () {
  1265. if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
  1266. return new XMLHttpRequest();
  1267. }
  1268. try {
  1269. return new ActiveXObject('Microsoft.XMLHTTP');
  1270. } catch (_unused) {}
  1271. try {
  1272. return new ActiveXObject('Msxml2.XMLHTTP.6.0');
  1273. } catch (_unused2) {}
  1274. try {
  1275. return new ActiveXObject('Msxml2.XMLHTTP.3.0');
  1276. } catch (_unused3) {}
  1277. try {
  1278. return new ActiveXObject('Msxml2.XMLHTTP');
  1279. } catch (_unused4) {}
  1280. throw new Error('Browser-only version of superagent could not find XHR');
  1281. };
  1282. /**
  1283. * Removes leading and trailing whitespace, added to support IE.
  1284. *
  1285. * @param {String} s
  1286. * @return {String}
  1287. * @api private
  1288. */
  1289. var trim = ''.trim ? function (s) {
  1290. return s.trim();
  1291. } : function (s) {
  1292. return s.replace(/(^\s*|\s*$)/g, '');
  1293. };
  1294. /**
  1295. * Serialize the given `obj`.
  1296. *
  1297. * @param {Object} obj
  1298. * @return {String}
  1299. * @api private
  1300. */
  1301. function serialize(obj) {
  1302. if (!isObject_1(obj)) return obj;
  1303. var pairs = [];
  1304. for (var key in obj) {
  1305. if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
  1306. }
  1307. return pairs.join('&');
  1308. }
  1309. /**
  1310. * Helps 'serialize' with serializing arrays.
  1311. * Mutates the pairs array.
  1312. *
  1313. * @param {Array} pairs
  1314. * @param {String} key
  1315. * @param {Mixed} val
  1316. */
  1317. function pushEncodedKeyValuePair(pairs, key, val) {
  1318. if (val === undefined) return;
  1319. if (val === null) {
  1320. pairs.push(encodeURI(key));
  1321. return;
  1322. }
  1323. if (Array.isArray(val)) {
  1324. val.forEach(function (v) {
  1325. pushEncodedKeyValuePair(pairs, key, v);
  1326. });
  1327. } else if (isObject_1(val)) {
  1328. for (var subkey in val) {
  1329. if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
  1330. }
  1331. } else {
  1332. pairs.push(encodeURI(key) + '=' + encodeURIComponent(val));
  1333. }
  1334. }
  1335. /**
  1336. * Expose serialization method.
  1337. */
  1338. request.serializeObject = serialize;
  1339. /**
  1340. * Parse the given x-www-form-urlencoded `str`.
  1341. *
  1342. * @param {String} str
  1343. * @return {Object}
  1344. * @api private
  1345. */
  1346. function parseString(str) {
  1347. var obj = {};
  1348. var pairs = str.split('&');
  1349. var pair;
  1350. var pos;
  1351. for (var i = 0, len = pairs.length; i < len; ++i) {
  1352. pair = pairs[i];
  1353. pos = pair.indexOf('=');
  1354. if (pos === -1) {
  1355. obj[decodeURIComponent(pair)] = '';
  1356. } else {
  1357. obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
  1358. }
  1359. }
  1360. return obj;
  1361. }
  1362. /**
  1363. * Expose parser.
  1364. */
  1365. request.parseString = parseString;
  1366. /**
  1367. * Default MIME type map.
  1368. *
  1369. * superagent.types.xml = 'application/xml';
  1370. *
  1371. */
  1372. request.types = {
  1373. html: 'text/html',
  1374. json: 'application/json',
  1375. xml: 'text/xml',
  1376. urlencoded: 'application/x-www-form-urlencoded',
  1377. form: 'application/x-www-form-urlencoded',
  1378. 'form-data': 'application/x-www-form-urlencoded'
  1379. };
  1380. /**
  1381. * Default serialization map.
  1382. *
  1383. * superagent.serialize['application/xml'] = function(obj){
  1384. * return 'generated xml here';
  1385. * };
  1386. *
  1387. */
  1388. request.serialize = {
  1389. 'application/x-www-form-urlencoded': serialize,
  1390. 'application/json': fastSafeStringify
  1391. };
  1392. /**
  1393. * Default parsers.
  1394. *
  1395. * superagent.parse['application/xml'] = function(str){
  1396. * return { object parsed from str };
  1397. * };
  1398. *
  1399. */
  1400. request.parse = {
  1401. 'application/x-www-form-urlencoded': parseString,
  1402. 'application/json': JSON.parse
  1403. };
  1404. /**
  1405. * Parse the given header `str` into
  1406. * an object containing the mapped fields.
  1407. *
  1408. * @param {String} str
  1409. * @return {Object}
  1410. * @api private
  1411. */
  1412. function parseHeader(str) {
  1413. var lines = str.split(/\r?\n/);
  1414. var fields = {};
  1415. var index;
  1416. var line;
  1417. var field;
  1418. var val;
  1419. for (var i = 0, len = lines.length; i < len; ++i) {
  1420. line = lines[i];
  1421. index = line.indexOf(':');
  1422. if (index === -1) {
  1423. // could be empty line, just skip it
  1424. continue;
  1425. }
  1426. field = line.slice(0, index).toLowerCase();
  1427. val = trim(line.slice(index + 1));
  1428. fields[field] = val;
  1429. }
  1430. return fields;
  1431. }
  1432. /**
  1433. * Check if `mime` is json or has +json structured syntax suffix.
  1434. *
  1435. * @param {String} mime
  1436. * @return {Boolean}
  1437. * @api private
  1438. */
  1439. function isJSON(mime) {
  1440. // should match /json or +json
  1441. // but not /json-seq
  1442. return /[/+]json($|[^-\w])/.test(mime);
  1443. }
  1444. /**
  1445. * Initialize a new `Response` with the given `xhr`.
  1446. *
  1447. * - set flags (.ok, .error, etc)
  1448. * - parse header
  1449. *
  1450. * Examples:
  1451. *
  1452. * Aliasing `superagent` as `request` is nice:
  1453. *
  1454. * request = superagent;
  1455. *
  1456. * We can use the promise-like API, or pass callbacks:
  1457. *
  1458. * request.get('/').end(function(res){});
  1459. * request.get('/', function(res){});
  1460. *
  1461. * Sending data can be chained:
  1462. *
  1463. * request
  1464. * .post('/user')
  1465. * .send({ name: 'tj' })
  1466. * .end(function(res){});
  1467. *
  1468. * Or passed to `.send()`:
  1469. *
  1470. * request
  1471. * .post('/user')
  1472. * .send({ name: 'tj' }, function(res){});
  1473. *
  1474. * Or passed to `.post()`:
  1475. *
  1476. * request
  1477. * .post('/user', { name: 'tj' })
  1478. * .end(function(res){});
  1479. *
  1480. * Or further reduced to a single call for simple cases:
  1481. *
  1482. * request
  1483. * .post('/user', { name: 'tj' }, function(res){});
  1484. *
  1485. * @param {XMLHTTPRequest} xhr
  1486. * @param {Object} options
  1487. * @api private
  1488. */
  1489. function Response(req) {
  1490. this.req = req;
  1491. this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
  1492. this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
  1493. this.statusText = this.req.xhr.statusText;
  1494. var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  1495. if (status === 1223) {
  1496. status = 204;
  1497. }
  1498. this._setStatusProperties(status);
  1499. this.headers = parseHeader(this.xhr.getAllResponseHeaders());
  1500. this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
  1501. // getResponseHeader still works. so we get content-type even if getting
  1502. // other headers fails.
  1503. this.header['content-type'] = this.xhr.getResponseHeader('content-type');
  1504. this._setHeaderProperties(this.header);
  1505. if (this.text === null && req._responseType) {
  1506. this.body = this.xhr.response;
  1507. } else {
  1508. this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
  1509. }
  1510. } // eslint-disable-next-line new-cap
  1511. responseBase(Response.prototype);
  1512. /**
  1513. * Parse the given body `str`.
  1514. *
  1515. * Used for auto-parsing of bodies. Parsers
  1516. * are defined on the `superagent.parse` object.
  1517. *
  1518. * @param {String} str
  1519. * @return {Mixed}
  1520. * @api private
  1521. */
  1522. Response.prototype._parseBody = function (str) {
  1523. var parse = request.parse[this.type];
  1524. if (this.req._parser) {
  1525. return this.req._parser(this, str);
  1526. }
  1527. if (!parse && isJSON(this.type)) {
  1528. parse = request.parse['application/json'];
  1529. }
  1530. return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
  1531. };
  1532. /**
  1533. * Return an `Error` representative of this response.
  1534. *
  1535. * @return {Error}
  1536. * @api public
  1537. */
  1538. Response.prototype.toError = function () {
  1539. var req = this.req;
  1540. var method = req.method;
  1541. var url = req.url;
  1542. var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
  1543. var err = new Error(msg);
  1544. err.status = this.status;
  1545. err.method = method;
  1546. err.url = url;
  1547. return err;
  1548. };
  1549. /**
  1550. * Expose `Response`.
  1551. */
  1552. request.Response = Response;
  1553. /**
  1554. * Initialize a new `Request` with the given `method` and `url`.
  1555. *
  1556. * @param {String} method
  1557. * @param {String} url
  1558. * @api public
  1559. */
  1560. function Request(method, url) {
  1561. var self = this;
  1562. this._query = this._query || [];
  1563. this.method = method;
  1564. this.url = url;
  1565. this.header = {}; // preserves header name case
  1566. this._header = {}; // coerces header names to lowercase
  1567. this.on('end', function () {
  1568. var err = null;
  1569. var res = null;
  1570. try {
  1571. res = new Response(self);
  1572. } catch (err_) {
  1573. err = new Error('Parser is unable to parse the response');
  1574. err.parse = true;
  1575. err.original = err_; // issue #675: return the raw response if the response parsing fails
  1576. if (self.xhr) {
  1577. // ie9 doesn't have 'response' property
  1578. err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails
  1579. err.status = self.xhr.status ? self.xhr.status : null;
  1580. err.statusCode = err.status; // backwards-compat only
  1581. } else {
  1582. err.rawResponse = null;
  1583. err.status = null;
  1584. }
  1585. return self.callback(err);
  1586. }
  1587. self.emit('response', res);
  1588. var new_err;
  1589. try {
  1590. if (!self._isResponseOK(res)) {
  1591. new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response');
  1592. }
  1593. } catch (err_) {
  1594. new_err = err_; // ok() callback can throw
  1595. } // #1000 don't catch errors from the callback to avoid double calling it
  1596. if (new_err) {
  1597. new_err.original = err;
  1598. new_err.response = res;
  1599. new_err.status = res.status;
  1600. self.callback(new_err, res);
  1601. } else {
  1602. self.callback(null, res);
  1603. }
  1604. });
  1605. }
  1606. /**
  1607. * Mixin `Emitter` and `RequestBase`.
  1608. */
  1609. // eslint-disable-next-line new-cap
  1610. componentEmitter(Request.prototype); // eslint-disable-next-line new-cap
  1611. requestBase(Request.prototype);
  1612. /**
  1613. * Set Content-Type to `type`, mapping values from `request.types`.
  1614. *
  1615. * Examples:
  1616. *
  1617. * superagent.types.xml = 'application/xml';
  1618. *
  1619. * request.post('/')
  1620. * .type('xml')
  1621. * .send(xmlstring)
  1622. * .end(callback);
  1623. *
  1624. * request.post('/')
  1625. * .type('application/xml')
  1626. * .send(xmlstring)
  1627. * .end(callback);
  1628. *
  1629. * @param {String} type
  1630. * @return {Request} for chaining
  1631. * @api public
  1632. */
  1633. Request.prototype.type = function (type) {
  1634. this.set('Content-Type', request.types[type] || type);
  1635. return this;
  1636. };
  1637. /**
  1638. * Set Accept to `type`, mapping values from `request.types`.
  1639. *
  1640. * Examples:
  1641. *
  1642. * superagent.types.json = 'application/json';
  1643. *
  1644. * request.get('/agent')
  1645. * .accept('json')
  1646. * .end(callback);
  1647. *
  1648. * request.get('/agent')
  1649. * .accept('application/json')
  1650. * .end(callback);
  1651. *
  1652. * @param {String} accept
  1653. * @return {Request} for chaining
  1654. * @api public
  1655. */
  1656. Request.prototype.accept = function (type) {
  1657. this.set('Accept', request.types[type] || type);
  1658. return this;
  1659. };
  1660. /**
  1661. * Set Authorization field value with `user` and `pass`.
  1662. *
  1663. * @param {String} user
  1664. * @param {String} [pass] optional in case of using 'bearer' as type
  1665. * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
  1666. * @return {Request} for chaining
  1667. * @api public
  1668. */
  1669. Request.prototype.auth = function (user, pass, options) {
  1670. if (arguments.length === 1) pass = '';
  1671. if (_typeof(pass) === 'object' && pass !== null) {
  1672. // pass is optional and can be replaced with options
  1673. options = pass;
  1674. pass = '';
  1675. }
  1676. if (!options) {
  1677. options = {
  1678. type: typeof btoa === 'function' ? 'basic' : 'auto'
  1679. };
  1680. }
  1681. var encoder = function encoder(string) {
  1682. if (typeof btoa === 'function') {
  1683. return btoa(string);
  1684. }
  1685. throw new Error('Cannot use basic auth, btoa is not a function');
  1686. };
  1687. return this._auth(user, pass, options, encoder);
  1688. };
  1689. /**
  1690. * Add query-string `val`.
  1691. *
  1692. * Examples:
  1693. *
  1694. * request.get('/shoes')
  1695. * .query('size=10')
  1696. * .query({ color: 'blue' })
  1697. *
  1698. * @param {Object|String} val
  1699. * @return {Request} for chaining
  1700. * @api public
  1701. */
  1702. Request.prototype.query = function (val) {
  1703. if (typeof val !== 'string') val = serialize(val);
  1704. if (val) this._query.push(val);
  1705. return this;
  1706. };
  1707. /**
  1708. * Queue the given `file` as an attachment to the specified `field`,
  1709. * with optional `options` (or filename).
  1710. *
  1711. * ``` js
  1712. * request.post('/upload')
  1713. * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
  1714. * .end(callback);
  1715. * ```
  1716. *
  1717. * @param {String} field
  1718. * @param {Blob|File} file
  1719. * @param {String|Object} options
  1720. * @return {Request} for chaining
  1721. * @api public
  1722. */
  1723. Request.prototype.attach = function (field, file, options) {
  1724. if (file) {
  1725. if (this._data) {
  1726. throw new Error("superagent can't mix .send() and .attach()");
  1727. }
  1728. this._getFormData().append(field, file, options || file.name);
  1729. }
  1730. return this;
  1731. };
  1732. Request.prototype._getFormData = function () {
  1733. if (!this._formData) {
  1734. this._formData = new root.FormData();
  1735. }
  1736. return this._formData;
  1737. };
  1738. /**
  1739. * Invoke the callback with `err` and `res`
  1740. * and handle arity check.
  1741. *
  1742. * @param {Error} err
  1743. * @param {Response} res
  1744. * @api private
  1745. */
  1746. Request.prototype.callback = function (err, res) {
  1747. if (this._shouldRetry(err, res)) {
  1748. return this._retry();
  1749. }
  1750. var fn = this._callback;
  1751. this.clearTimeout();
  1752. if (err) {
  1753. if (this._maxRetries) err.retries = this._retries - 1;
  1754. this.emit('error', err);
  1755. }
  1756. fn(err, res);
  1757. };
  1758. /**
  1759. * Invoke callback with x-domain error.
  1760. *
  1761. * @api private
  1762. */
  1763. Request.prototype.crossDomainError = function () {
  1764. var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
  1765. err.crossDomain = true;
  1766. err.status = this.status;
  1767. err.method = this.method;
  1768. err.url = this.url;
  1769. this.callback(err);
  1770. }; // This only warns, because the request is still likely to work
  1771. Request.prototype.agent = function () {
  1772. console.warn('This is not supported in browser version of superagent');
  1773. return this;
  1774. };
  1775. Request.prototype.ca = Request.prototype.agent;
  1776. Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected
  1777. Request.prototype.write = function () {
  1778. throw new Error('Streaming is not supported in browser version of superagent');
  1779. };
  1780. Request.prototype.pipe = Request.prototype.write;
  1781. /**
  1782. * Check if `obj` is a host object,
  1783. * we don't want to serialize these :)
  1784. *
  1785. * @param {Object} obj host object
  1786. * @return {Boolean} is a host object
  1787. * @api private
  1788. */
  1789. Request.prototype._isHost = function (obj) {
  1790. // Native objects stringify to [object File], [object Blob], [object FormData], etc.
  1791. return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
  1792. };
  1793. /**
  1794. * Initiate request, invoking callback `fn(res)`
  1795. * with an instanceof `Response`.
  1796. *
  1797. * @param {Function} fn
  1798. * @return {Request} for chaining
  1799. * @api public
  1800. */
  1801. Request.prototype.end = function (fn) {
  1802. if (this._endCalled) {
  1803. console.warn('Warning: .end() was called twice. This is not supported in superagent');
  1804. }
  1805. this._endCalled = true; // store callback
  1806. this._callback = fn || noop; // querystring
  1807. this._finalizeQueryString();
  1808. this._end();
  1809. };
  1810. Request.prototype._setUploadTimeout = function () {
  1811. var self = this; // upload timeout it's wokrs only if deadline timeout is off
  1812. if (this._uploadTimeout && !this._uploadTimeoutTimer) {
  1813. this._uploadTimeoutTimer = setTimeout(function () {
  1814. self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
  1815. }, this._uploadTimeout);
  1816. }
  1817. }; // eslint-disable-next-line complexity
  1818. Request.prototype._end = function () {
  1819. if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
  1820. var self = this;
  1821. this.xhr = request.getXHR();
  1822. var xhr = this.xhr;
  1823. var data = this._formData || this._data;
  1824. this._setTimeouts(); // state change
  1825. xhr.onreadystatechange = function () {
  1826. var readyState = xhr.readyState;
  1827. if (readyState >= 2 && self._responseTimeoutTimer) {
  1828. clearTimeout(self._responseTimeoutTimer);
  1829. }
  1830. if (readyState !== 4) {
  1831. return;
  1832. } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
  1833. // result in the error "Could not complete the operation due to error c00c023f"
  1834. var status;
  1835. try {
  1836. status = xhr.status;
  1837. } catch (_unused5) {
  1838. status = 0;
  1839. }
  1840. if (!status) {
  1841. if (self.timedout || self._aborted) return;
  1842. return self.crossDomainError();
  1843. }
  1844. self.emit('end');
  1845. }; // progress
  1846. var handleProgress = function handleProgress(direction, e) {
  1847. if (e.total > 0) {
  1848. e.percent = e.loaded / e.total * 100;
  1849. if (e.percent === 100) {
  1850. clearTimeout(self._uploadTimeoutTimer);
  1851. }
  1852. }
  1853. e.direction = direction;
  1854. self.emit('progress', e);
  1855. };
  1856. if (this.hasListeners('progress')) {
  1857. try {
  1858. xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
  1859. if (xhr.upload) {
  1860. xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
  1861. }
  1862. } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
  1863. // Reported here:
  1864. // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
  1865. }
  1866. }
  1867. if (xhr.upload) {
  1868. this._setUploadTimeout();
  1869. } // initiate request
  1870. try {
  1871. if (this.username && this.password) {
  1872. xhr.open(this.method, this.url, true, this.username, this.password);
  1873. } else {
  1874. xhr.open(this.method, this.url, true);
  1875. }
  1876. } catch (err) {
  1877. // see #1149
  1878. return this.callback(err);
  1879. } // CORS
  1880. if (this._withCredentials) xhr.withCredentials = true; // body
  1881. if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
  1882. // serialize stuff
  1883. var contentType = this._header['content-type'];
  1884. var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
  1885. if (!_serialize && isJSON(contentType)) {
  1886. _serialize = request.serialize['application/json'];
  1887. }
  1888. if (_serialize) data = _serialize(data);
  1889. } // set header fields
  1890. for (var field in this.header) {
  1891. if (this.header[field] === null) continue;
  1892. if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
  1893. }
  1894. if (this._responseType) {
  1895. xhr.responseType = this._responseType;
  1896. } // send stuff
  1897. this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
  1898. // We need null here if data is undefined
  1899. xhr.send(typeof data === 'undefined' ? null : data);
  1900. };
  1901. request.agent = function () {
  1902. return new agentBase();
  1903. };
  1904. ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
  1905. agentBase.prototype[method.toLowerCase()] = function (url, fn) {
  1906. var req = new request.Request(method, url);
  1907. this._setDefaults(req);
  1908. if (fn) {
  1909. req.end(fn);
  1910. }
  1911. return req;
  1912. };
  1913. });
  1914. agentBase.prototype.del = agentBase.prototype["delete"];
  1915. /**
  1916. * GET `url` with optional callback `fn(res)`.
  1917. *
  1918. * @param {String} url
  1919. * @param {Mixed|Function} [data] or fn
  1920. * @param {Function} [fn]
  1921. * @return {Request}
  1922. * @api public
  1923. */
  1924. request.get = function (url, data, fn) {
  1925. var req = request('GET', url);
  1926. if (typeof data === 'function') {
  1927. fn = data;
  1928. data = null;
  1929. }
  1930. if (data) req.query(data);
  1931. if (fn) req.end(fn);
  1932. return req;
  1933. };
  1934. /**
  1935. * HEAD `url` with optional callback `fn(res)`.
  1936. *
  1937. * @param {String} url
  1938. * @param {Mixed|Function} [data] or fn
  1939. * @param {Function} [fn]
  1940. * @return {Request}
  1941. * @api public
  1942. */
  1943. request.head = function (url, data, fn) {
  1944. var req = request('HEAD', url);
  1945. if (typeof data === 'function') {
  1946. fn = data;
  1947. data = null;
  1948. }
  1949. if (data) req.query(data);
  1950. if (fn) req.end(fn);
  1951. return req;
  1952. };
  1953. /**
  1954. * OPTIONS query to `url` with optional callback `fn(res)`.
  1955. *
  1956. * @param {String} url
  1957. * @param {Mixed|Function} [data] or fn
  1958. * @param {Function} [fn]
  1959. * @return {Request}
  1960. * @api public
  1961. */
  1962. request.options = function (url, data, fn) {
  1963. var req = request('OPTIONS', url);
  1964. if (typeof data === 'function') {
  1965. fn = data;
  1966. data = null;
  1967. }
  1968. if (data) req.send(data);
  1969. if (fn) req.end(fn);
  1970. return req;
  1971. };
  1972. /**
  1973. * DELETE `url` with optional `data` and callback `fn(res)`.
  1974. *
  1975. * @param {String} url
  1976. * @param {Mixed} [data]
  1977. * @param {Function} [fn]
  1978. * @return {Request}
  1979. * @api public
  1980. */
  1981. function del(url, data, fn) {
  1982. var req = request('DELETE', url);
  1983. if (typeof data === 'function') {
  1984. fn = data;
  1985. data = null;
  1986. }
  1987. if (data) req.send(data);
  1988. if (fn) req.end(fn);
  1989. return req;
  1990. }
  1991. request.del = del;
  1992. request["delete"] = del;
  1993. /**
  1994. * PATCH `url` with optional `data` and callback `fn(res)`.
  1995. *
  1996. * @param {String} url
  1997. * @param {Mixed} [data]
  1998. * @param {Function} [fn]
  1999. * @return {Request}
  2000. * @api public
  2001. */
  2002. request.patch = function (url, data, fn) {
  2003. var req = request('PATCH', url);
  2004. if (typeof data === 'function') {
  2005. fn = data;
  2006. data = null;
  2007. }
  2008. if (data) req.send(data);
  2009. if (fn) req.end(fn);
  2010. return req;
  2011. };
  2012. /**
  2013. * POST `url` with optional `data` and callback `fn(res)`.
  2014. *
  2015. * @param {String} url
  2016. * @param {Mixed} [data]
  2017. * @param {Function} [fn]
  2018. * @return {Request}
  2019. * @api public
  2020. */
  2021. request.post = function (url, data, fn) {
  2022. var req = request('POST', url);
  2023. if (typeof data === 'function') {
  2024. fn = data;
  2025. data = null;
  2026. }
  2027. if (data) req.send(data);
  2028. if (fn) req.end(fn);
  2029. return req;
  2030. };
  2031. /**
  2032. * PUT `url` with optional `data` and callback `fn(res)`.
  2033. *
  2034. * @param {String} url
  2035. * @param {Mixed|Function} [data] or fn
  2036. * @param {Function} [fn]
  2037. * @return {Request}
  2038. * @api public
  2039. */
  2040. request.put = function (url, data, fn) {
  2041. var req = request('PUT', url);
  2042. if (typeof data === 'function') {
  2043. fn = data;
  2044. data = null;
  2045. }
  2046. if (data) req.send(data);
  2047. if (fn) req.end(fn);
  2048. return req;
  2049. };
  2050. });
  2051. var client_1 = client.Request;
  2052. var lib = createCommonjsModule(function (module, exports) {
  2053. Object.defineProperty(exports, "__esModule", { value: true });
  2054. exports.request = function (url, options) {
  2055. if (options === void 0) { options = {}; }
  2056. var _a = options.method, method = _a === void 0 ? "GET" : _a, data = options.data, headers = options.headers, onprogress = options.onprogress;
  2057. var req = client(method, url);
  2058. if (headers) {
  2059. req.set(headers);
  2060. }
  2061. if (onprogress) {
  2062. req.on("progress", onprogress);
  2063. }
  2064. return req
  2065. .send(data)
  2066. .catch(function (error) {
  2067. if (error.response) {
  2068. return error.response;
  2069. }
  2070. throw error;
  2071. })
  2072. .then(function (_a) {
  2073. var status = _a.status, ok = _a.ok, header = _a.header, body = _a.body;
  2074. return ({
  2075. status: status,
  2076. ok: ok,
  2077. headers: header,
  2078. data: body
  2079. });
  2080. });
  2081. };
  2082. exports.upload = function (url, file, options) {
  2083. if (options === void 0) { options = {}; }
  2084. var data = options.data, headers = options.headers, onprogress = options.onprogress;
  2085. var req = client("POST", url).attach(file.field, file.data, file.name);
  2086. if (data) {
  2087. req.field(data);
  2088. }
  2089. if (headers) {
  2090. req.set(headers);
  2091. }
  2092. if (onprogress) {
  2093. req.on("progress", onprogress);
  2094. }
  2095. return req
  2096. .catch(function (error) {
  2097. if (error.response) {
  2098. return error.response;
  2099. }
  2100. throw error;
  2101. })
  2102. .then(function (_a) {
  2103. var status = _a.status, ok = _a.ok, header = _a.header, body = _a.body;
  2104. return ({
  2105. status: status,
  2106. ok: ok,
  2107. headers: header,
  2108. data: body
  2109. });
  2110. });
  2111. };
  2112. });
  2113. unwrapExports(lib);
  2114. var lib_1 = lib.request;
  2115. var lib_2 = lib.upload;
  2116. var lib$1 = createCommonjsModule(function (module, exports) {
  2117. Object.defineProperty(exports, "__esModule", {
  2118. value: true
  2119. });
  2120. exports.request = lib.request;
  2121. exports.upload = lib.upload;
  2122. exports.storage = window.localStorage;
  2123. exports.WebSocket = window.WebSocket;
  2124. exports.platformInfo = {
  2125. name: "Browser"
  2126. };
  2127. });
  2128. unwrapExports(lib$1);
  2129. var lib_1$1 = lib$1.request;
  2130. var lib_2$1 = lib$1.upload;
  2131. var lib_3 = lib$1.storage;
  2132. var lib_4 = lib$1.WebSocket;
  2133. var lib_5 = lib$1.platformInfo;
  2134. function _defineProperty(obj, key, value) {
  2135. if (key in obj) {
  2136. Object.defineProperty(obj, key, {
  2137. value: value,
  2138. enumerable: true,
  2139. configurable: true,
  2140. writable: true
  2141. });
  2142. } else {
  2143. obj[key] = value;
  2144. }
  2145. return obj;
  2146. }
  2147. var defineProperty = _defineProperty;
  2148. var long_1 = createCommonjsModule(function (module) {
  2149. /*
  2150. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  2151. Copyright 2009 The Closure Library Authors. All Rights Reserved.
  2152. Licensed under the Apache License, Version 2.0 (the "License");
  2153. you may not use this file except in compliance with the License.
  2154. You may obtain a copy of the License at
  2155. http://www.apache.org/licenses/LICENSE-2.0
  2156. Unless required by applicable law or agreed to in writing, software
  2157. distributed under the License is distributed on an "AS-IS" BASIS,
  2158. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2159. See the License for the specific language governing permissions and
  2160. limitations under the License.
  2161. */
  2162. /**
  2163. * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
  2164. * Released under the Apache License, Version 2.0
  2165. * see: https://github.com/dcodeIO/long.js for details
  2166. */
  2167. (function(global, factory) {
  2168. /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
  2169. module["exports"] = factory();
  2170. /* Global */ else
  2171. (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
  2172. })(commonjsGlobal, function() {
  2173. /**
  2174. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  2175. * See the from* functions below for more convenient ways of constructing Longs.
  2176. * @exports Long
  2177. * @class A Long class for representing a 64 bit two's-complement integer value.
  2178. * @param {number} low The low (signed) 32 bits of the long
  2179. * @param {number} high The high (signed) 32 bits of the long
  2180. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  2181. * @constructor
  2182. */
  2183. function Long(low, high, unsigned) {
  2184. /**
  2185. * The low 32 bits as a signed value.
  2186. * @type {number}
  2187. */
  2188. this.low = low | 0;
  2189. /**
  2190. * The high 32 bits as a signed value.
  2191. * @type {number}
  2192. */
  2193. this.high = high | 0;
  2194. /**
  2195. * Whether unsigned or not.
  2196. * @type {boolean}
  2197. */
  2198. this.unsigned = !!unsigned;
  2199. }
  2200. // The internal representation of a long is the two given signed, 32-bit values.
  2201. // We use 32-bit pieces because these are the size of integers on which
  2202. // Javascript performs bit-operations. For operations like addition and
  2203. // multiplication, we split each number into 16 bit pieces, which can easily be
  2204. // multiplied within Javascript's floating-point representation without overflow
  2205. // or change in sign.
  2206. //
  2207. // In the algorithms below, we frequently reduce the negative case to the
  2208. // positive case by negating the input(s) and then post-processing the result.
  2209. // Note that we must ALWAYS check specially whether those values are MIN_VALUE
  2210. // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  2211. // a positive number, it overflows back into a negative). Not handling this
  2212. // case would often result in infinite recursion.
  2213. //
  2214. // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
  2215. // methods on which they depend.
  2216. /**
  2217. * An indicator used to reliably determine if an object is a Long or not.
  2218. * @type {boolean}
  2219. * @const
  2220. * @private
  2221. */
  2222. Long.prototype.__isLong__;
  2223. Object.defineProperty(Long.prototype, "__isLong__", {
  2224. value: true,
  2225. enumerable: false,
  2226. configurable: false
  2227. });
  2228. /**
  2229. * @function
  2230. * @param {*} obj Object
  2231. * @returns {boolean}
  2232. * @inner
  2233. */
  2234. function isLong(obj) {
  2235. return (obj && obj["__isLong__"]) === true;
  2236. }
  2237. /**
  2238. * Tests if the specified object is a Long.
  2239. * @function
  2240. * @param {*} obj Object
  2241. * @returns {boolean}
  2242. */
  2243. Long.isLong = isLong;
  2244. /**
  2245. * A cache of the Long representations of small integer values.
  2246. * @type {!Object}
  2247. * @inner
  2248. */
  2249. var INT_CACHE = {};
  2250. /**
  2251. * A cache of the Long representations of small unsigned integer values.
  2252. * @type {!Object}
  2253. * @inner
  2254. */
  2255. var UINT_CACHE = {};
  2256. /**
  2257. * @param {number} value
  2258. * @param {boolean=} unsigned
  2259. * @returns {!Long}
  2260. * @inner
  2261. */
  2262. function fromInt(value, unsigned) {
  2263. var obj, cachedObj, cache;
  2264. if (unsigned) {
  2265. value >>>= 0;
  2266. if (cache = (0 <= value && value < 256)) {
  2267. cachedObj = UINT_CACHE[value];
  2268. if (cachedObj)
  2269. return cachedObj;
  2270. }
  2271. obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  2272. if (cache)
  2273. UINT_CACHE[value] = obj;
  2274. return obj;
  2275. } else {
  2276. value |= 0;
  2277. if (cache = (-128 <= value && value < 128)) {
  2278. cachedObj = INT_CACHE[value];
  2279. if (cachedObj)
  2280. return cachedObj;
  2281. }
  2282. obj = fromBits(value, value < 0 ? -1 : 0, false);
  2283. if (cache)
  2284. INT_CACHE[value] = obj;
  2285. return obj;
  2286. }
  2287. }
  2288. /**
  2289. * Returns a Long representing the given 32 bit integer value.
  2290. * @function
  2291. * @param {number} value The 32 bit integer in question
  2292. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  2293. * @returns {!Long} The corresponding Long value
  2294. */
  2295. Long.fromInt = fromInt;
  2296. /**
  2297. * @param {number} value
  2298. * @param {boolean=} unsigned
  2299. * @returns {!Long}
  2300. * @inner
  2301. */
  2302. function fromNumber(value, unsigned) {
  2303. if (isNaN(value) || !isFinite(value))
  2304. return unsigned ? UZERO : ZERO;
  2305. if (unsigned) {
  2306. if (value < 0)
  2307. return UZERO;
  2308. if (value >= TWO_PWR_64_DBL)
  2309. return MAX_UNSIGNED_VALUE;
  2310. } else {
  2311. if (value <= -TWO_PWR_63_DBL)
  2312. return MIN_VALUE;
  2313. if (value + 1 >= TWO_PWR_63_DBL)
  2314. return MAX_VALUE;
  2315. }
  2316. if (value < 0)
  2317. return fromNumber(-value, unsigned).neg();
  2318. return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  2319. }
  2320. /**
  2321. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2322. * @function
  2323. * @param {number} value The number in question
  2324. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  2325. * @returns {!Long} The corresponding Long value
  2326. */
  2327. Long.fromNumber = fromNumber;
  2328. /**
  2329. * @param {number} lowBits
  2330. * @param {number} highBits
  2331. * @param {boolean=} unsigned
  2332. * @returns {!Long}
  2333. * @inner
  2334. */
  2335. function fromBits(lowBits, highBits, unsigned) {
  2336. return new Long(lowBits, highBits, unsigned);
  2337. }
  2338. /**
  2339. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
  2340. * assumed to use 32 bits.
  2341. * @function
  2342. * @param {number} lowBits The low 32 bits
  2343. * @param {number} highBits The high 32 bits
  2344. * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
  2345. * @returns {!Long} The corresponding Long value
  2346. */
  2347. Long.fromBits = fromBits;
  2348. /**
  2349. * @function
  2350. * @param {number} base
  2351. * @param {number} exponent
  2352. * @returns {number}
  2353. * @inner
  2354. */
  2355. var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
  2356. /**
  2357. * @param {string} str
  2358. * @param {(boolean|number)=} unsigned
  2359. * @param {number=} radix
  2360. * @returns {!Long}
  2361. * @inner
  2362. */
  2363. function fromString(str, unsigned, radix) {
  2364. if (str.length === 0)
  2365. throw Error('empty string');
  2366. if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
  2367. return ZERO;
  2368. if (typeof unsigned === 'number') {
  2369. // For goog.math.long compatibility
  2370. radix = unsigned,
  2371. unsigned = false;
  2372. } else {
  2373. unsigned = !! unsigned;
  2374. }
  2375. radix = radix || 10;
  2376. if (radix < 2 || 36 < radix)
  2377. throw RangeError('radix');
  2378. var p;
  2379. if ((p = str.indexOf('-')) > 0)
  2380. throw Error('interior hyphen');
  2381. else if (p === 0) {
  2382. return fromString(str.substring(1), unsigned, radix).neg();
  2383. }
  2384. // Do several (8) digits each time through the loop, so as to
  2385. // minimize the calls to the very expensive emulated div.
  2386. var radixToPower = fromNumber(pow_dbl(radix, 8));
  2387. var result = ZERO;
  2388. for (var i = 0; i < str.length; i += 8) {
  2389. var size = Math.min(8, str.length - i),
  2390. value = parseInt(str.substring(i, i + size), radix);
  2391. if (size < 8) {
  2392. var power = fromNumber(pow_dbl(radix, size));
  2393. result = result.mul(power).add(fromNumber(value));
  2394. } else {
  2395. result = result.mul(radixToPower);
  2396. result = result.add(fromNumber(value));
  2397. }
  2398. }
  2399. result.unsigned = unsigned;
  2400. return result;
  2401. }
  2402. /**
  2403. * Returns a Long representation of the given string, written using the specified radix.
  2404. * @function
  2405. * @param {string} str The textual representation of the Long
  2406. * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
  2407. * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
  2408. * @returns {!Long} The corresponding Long value
  2409. */
  2410. Long.fromString = fromString;
  2411. /**
  2412. * @function
  2413. * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
  2414. * @returns {!Long}
  2415. * @inner
  2416. */
  2417. function fromValue(val) {
  2418. if (val /* is compatible */ instanceof Long)
  2419. return val;
  2420. if (typeof val === 'number')
  2421. return fromNumber(val);
  2422. if (typeof val === 'string')
  2423. return fromString(val);
  2424. // Throws for non-objects, converts non-instanceof Long:
  2425. return fromBits(val.low, val.high, val.unsigned);
  2426. }
  2427. /**
  2428. * Converts the specified value to a Long.
  2429. * @function
  2430. * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
  2431. * @returns {!Long}
  2432. */
  2433. Long.fromValue = fromValue;
  2434. // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
  2435. // no runtime penalty for these.
  2436. /**
  2437. * @type {number}
  2438. * @const
  2439. * @inner
  2440. */
  2441. var TWO_PWR_16_DBL = 1 << 16;
  2442. /**
  2443. * @type {number}
  2444. * @const
  2445. * @inner
  2446. */
  2447. var TWO_PWR_24_DBL = 1 << 24;
  2448. /**
  2449. * @type {number}
  2450. * @const
  2451. * @inner
  2452. */
  2453. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  2454. /**
  2455. * @type {number}
  2456. * @const
  2457. * @inner
  2458. */
  2459. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  2460. /**
  2461. * @type {number}
  2462. * @const
  2463. * @inner
  2464. */
  2465. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  2466. /**
  2467. * @type {!Long}
  2468. * @const
  2469. * @inner
  2470. */
  2471. var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
  2472. /**
  2473. * @type {!Long}
  2474. * @inner
  2475. */
  2476. var ZERO = fromInt(0);
  2477. /**
  2478. * Signed zero.
  2479. * @type {!Long}
  2480. */
  2481. Long.ZERO = ZERO;
  2482. /**
  2483. * @type {!Long}
  2484. * @inner
  2485. */
  2486. var UZERO = fromInt(0, true);
  2487. /**
  2488. * Unsigned zero.
  2489. * @type {!Long}
  2490. */
  2491. Long.UZERO = UZERO;
  2492. /**
  2493. * @type {!Long}
  2494. * @inner
  2495. */
  2496. var ONE = fromInt(1);
  2497. /**
  2498. * Signed one.
  2499. * @type {!Long}
  2500. */
  2501. Long.ONE = ONE;
  2502. /**
  2503. * @type {!Long}
  2504. * @inner
  2505. */
  2506. var UONE = fromInt(1, true);
  2507. /**
  2508. * Unsigned one.
  2509. * @type {!Long}
  2510. */
  2511. Long.UONE = UONE;
  2512. /**
  2513. * @type {!Long}
  2514. * @inner
  2515. */
  2516. var NEG_ONE = fromInt(-1);
  2517. /**
  2518. * Signed negative one.
  2519. * @type {!Long}
  2520. */
  2521. Long.NEG_ONE = NEG_ONE;
  2522. /**
  2523. * @type {!Long}
  2524. * @inner
  2525. */
  2526. var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
  2527. /**
  2528. * Maximum signed value.
  2529. * @type {!Long}
  2530. */
  2531. Long.MAX_VALUE = MAX_VALUE;
  2532. /**
  2533. * @type {!Long}
  2534. * @inner
  2535. */
  2536. var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
  2537. /**
  2538. * Maximum unsigned value.
  2539. * @type {!Long}
  2540. */
  2541. Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
  2542. /**
  2543. * @type {!Long}
  2544. * @inner
  2545. */
  2546. var MIN_VALUE = fromBits(0, 0x80000000|0, false);
  2547. /**
  2548. * Minimum signed value.
  2549. * @type {!Long}
  2550. */
  2551. Long.MIN_VALUE = MIN_VALUE;
  2552. /**
  2553. * @alias Long.prototype
  2554. * @inner
  2555. */
  2556. var LongPrototype = Long.prototype;
  2557. /**
  2558. * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
  2559. * @returns {number}
  2560. */
  2561. LongPrototype.toInt = function toInt() {
  2562. return this.unsigned ? this.low >>> 0 : this.low;
  2563. };
  2564. /**
  2565. * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
  2566. * @returns {number}
  2567. */
  2568. LongPrototype.toNumber = function toNumber() {
  2569. if (this.unsigned)
  2570. return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
  2571. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  2572. };
  2573. /**
  2574. * Converts the Long to a string written in the specified radix.
  2575. * @param {number=} radix Radix (2-36), defaults to 10
  2576. * @returns {string}
  2577. * @override
  2578. * @throws {RangeError} If `radix` is out of range
  2579. */
  2580. LongPrototype.toString = function toString(radix) {
  2581. radix = radix || 10;
  2582. if (radix < 2 || 36 < radix)
  2583. throw RangeError('radix');
  2584. if (this.isZero())
  2585. return '0';
  2586. if (this.isNegative()) { // Unsigned Longs are never negative
  2587. if (this.eq(MIN_VALUE)) {
  2588. // We need to change the Long value before it can be negated, so we remove
  2589. // the bottom-most digit in this base and then recurse to do the rest.
  2590. var radixLong = fromNumber(radix),
  2591. div = this.div(radixLong),
  2592. rem1 = div.mul(radixLong).sub(this);
  2593. return div.toString(radix) + rem1.toInt().toString(radix);
  2594. } else
  2595. return '-' + this.neg().toString(radix);
  2596. }
  2597. // Do several (6) digits each time through the loop, so as to
  2598. // minimize the calls to the very expensive emulated div.
  2599. var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
  2600. rem = this;
  2601. var result = '';
  2602. while (true) {
  2603. var remDiv = rem.div(radixToPower),
  2604. intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
  2605. digits = intval.toString(radix);
  2606. rem = remDiv;
  2607. if (rem.isZero())
  2608. return digits + result;
  2609. else {
  2610. while (digits.length < 6)
  2611. digits = '0' + digits;
  2612. result = '' + digits + result;
  2613. }
  2614. }
  2615. };
  2616. /**
  2617. * Gets the high 32 bits as a signed integer.
  2618. * @returns {number} Signed high bits
  2619. */
  2620. LongPrototype.getHighBits = function getHighBits() {
  2621. return this.high;
  2622. };
  2623. /**
  2624. * Gets the high 32 bits as an unsigned integer.
  2625. * @returns {number} Unsigned high bits
  2626. */
  2627. LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
  2628. return this.high >>> 0;
  2629. };
  2630. /**
  2631. * Gets the low 32 bits as a signed integer.
  2632. * @returns {number} Signed low bits
  2633. */
  2634. LongPrototype.getLowBits = function getLowBits() {
  2635. return this.low;
  2636. };
  2637. /**
  2638. * Gets the low 32 bits as an unsigned integer.
  2639. * @returns {number} Unsigned low bits
  2640. */
  2641. LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
  2642. return this.low >>> 0;
  2643. };
  2644. /**
  2645. * Gets the number of bits needed to represent the absolute value of this Long.
  2646. * @returns {number}
  2647. */
  2648. LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
  2649. if (this.isNegative()) // Unsigned Longs are never negative
  2650. return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  2651. var val = this.high != 0 ? this.high : this.low;
  2652. for (var bit = 31; bit > 0; bit--)
  2653. if ((val & (1 << bit)) != 0)
  2654. break;
  2655. return this.high != 0 ? bit + 33 : bit + 1;
  2656. };
  2657. /**
  2658. * Tests if this Long's value equals zero.
  2659. * @returns {boolean}
  2660. */
  2661. LongPrototype.isZero = function isZero() {
  2662. return this.high === 0 && this.low === 0;
  2663. };
  2664. /**
  2665. * Tests if this Long's value is negative.
  2666. * @returns {boolean}
  2667. */
  2668. LongPrototype.isNegative = function isNegative() {
  2669. return !this.unsigned && this.high < 0;
  2670. };
  2671. /**
  2672. * Tests if this Long's value is positive.
  2673. * @returns {boolean}
  2674. */
  2675. LongPrototype.isPositive = function isPositive() {
  2676. return this.unsigned || this.high >= 0;
  2677. };
  2678. /**
  2679. * Tests if this Long's value is odd.
  2680. * @returns {boolean}
  2681. */
  2682. LongPrototype.isOdd = function isOdd() {
  2683. return (this.low & 1) === 1;
  2684. };
  2685. /**
  2686. * Tests if this Long's value is even.
  2687. * @returns {boolean}
  2688. */
  2689. LongPrototype.isEven = function isEven() {
  2690. return (this.low & 1) === 0;
  2691. };
  2692. /**
  2693. * Tests if this Long's value equals the specified's.
  2694. * @param {!Long|number|string} other Other value
  2695. * @returns {boolean}
  2696. */
  2697. LongPrototype.equals = function equals(other) {
  2698. if (!isLong(other))
  2699. other = fromValue(other);
  2700. if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
  2701. return false;
  2702. return this.high === other.high && this.low === other.low;
  2703. };
  2704. /**
  2705. * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
  2706. * @function
  2707. * @param {!Long|number|string} other Other value
  2708. * @returns {boolean}
  2709. */
  2710. LongPrototype.eq = LongPrototype.equals;
  2711. /**
  2712. * Tests if this Long's value differs from the specified's.
  2713. * @param {!Long|number|string} other Other value
  2714. * @returns {boolean}
  2715. */
  2716. LongPrototype.notEquals = function notEquals(other) {
  2717. return !this.eq(/* validates */ other);
  2718. };
  2719. /**
  2720. * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
  2721. * @function
  2722. * @param {!Long|number|string} other Other value
  2723. * @returns {boolean}
  2724. */
  2725. LongPrototype.neq = LongPrototype.notEquals;
  2726. /**
  2727. * Tests if this Long's value is less than the specified's.
  2728. * @param {!Long|number|string} other Other value
  2729. * @returns {boolean}
  2730. */
  2731. LongPrototype.lessThan = function lessThan(other) {
  2732. return this.comp(/* validates */ other) < 0;
  2733. };
  2734. /**
  2735. * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
  2736. * @function
  2737. * @param {!Long|number|string} other Other value
  2738. * @returns {boolean}
  2739. */
  2740. LongPrototype.lt = LongPrototype.lessThan;
  2741. /**
  2742. * Tests if this Long's value is less than or equal the specified's.
  2743. * @param {!Long|number|string} other Other value
  2744. * @returns {boolean}
  2745. */
  2746. LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
  2747. return this.comp(/* validates */ other) <= 0;
  2748. };
  2749. /**
  2750. * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
  2751. * @function
  2752. * @param {!Long|number|string} other Other value
  2753. * @returns {boolean}
  2754. */
  2755. LongPrototype.lte = LongPrototype.lessThanOrEqual;
  2756. /**
  2757. * Tests if this Long's value is greater than the specified's.
  2758. * @param {!Long|number|string} other Other value
  2759. * @returns {boolean}
  2760. */
  2761. LongPrototype.greaterThan = function greaterThan(other) {
  2762. return this.comp(/* validates */ other) > 0;
  2763. };
  2764. /**
  2765. * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
  2766. * @function
  2767. * @param {!Long|number|string} other Other value
  2768. * @returns {boolean}
  2769. */
  2770. LongPrototype.gt = LongPrototype.greaterThan;
  2771. /**
  2772. * Tests if this Long's value is greater than or equal the specified's.
  2773. * @param {!Long|number|string} other Other value
  2774. * @returns {boolean}
  2775. */
  2776. LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
  2777. return this.comp(/* validates */ other) >= 0;
  2778. };
  2779. /**
  2780. * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
  2781. * @function
  2782. * @param {!Long|number|string} other Other value
  2783. * @returns {boolean}
  2784. */
  2785. LongPrototype.gte = LongPrototype.greaterThanOrEqual;
  2786. /**
  2787. * Compares this Long's value with the specified's.
  2788. * @param {!Long|number|string} other Other value
  2789. * @returns {number} 0 if they are the same, 1 if the this is greater and -1
  2790. * if the given one is greater
  2791. */
  2792. LongPrototype.compare = function compare(other) {
  2793. if (!isLong(other))
  2794. other = fromValue(other);
  2795. if (this.eq(other))
  2796. return 0;
  2797. var thisNeg = this.isNegative(),
  2798. otherNeg = other.isNegative();
  2799. if (thisNeg && !otherNeg)
  2800. return -1;
  2801. if (!thisNeg && otherNeg)
  2802. return 1;
  2803. // At this point the sign bits are the same
  2804. if (!this.unsigned)
  2805. return this.sub(other).isNegative() ? -1 : 1;
  2806. // Both are positive if at least one is unsigned
  2807. return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
  2808. };
  2809. /**
  2810. * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
  2811. * @function
  2812. * @param {!Long|number|string} other Other value
  2813. * @returns {number} 0 if they are the same, 1 if the this is greater and -1
  2814. * if the given one is greater
  2815. */
  2816. LongPrototype.comp = LongPrototype.compare;
  2817. /**
  2818. * Negates this Long's value.
  2819. * @returns {!Long} Negated Long
  2820. */
  2821. LongPrototype.negate = function negate() {
  2822. if (!this.unsigned && this.eq(MIN_VALUE))
  2823. return MIN_VALUE;
  2824. return this.not().add(ONE);
  2825. };
  2826. /**
  2827. * Negates this Long's value. This is an alias of {@link Long#negate}.
  2828. * @function
  2829. * @returns {!Long} Negated Long
  2830. */
  2831. LongPrototype.neg = LongPrototype.negate;
  2832. /**
  2833. * Returns the sum of this and the specified Long.
  2834. * @param {!Long|number|string} addend Addend
  2835. * @returns {!Long} Sum
  2836. */
  2837. LongPrototype.add = function add(addend) {
  2838. if (!isLong(addend))
  2839. addend = fromValue(addend);
  2840. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  2841. var a48 = this.high >>> 16;
  2842. var a32 = this.high & 0xFFFF;
  2843. var a16 = this.low >>> 16;
  2844. var a00 = this.low & 0xFFFF;
  2845. var b48 = addend.high >>> 16;
  2846. var b32 = addend.high & 0xFFFF;
  2847. var b16 = addend.low >>> 16;
  2848. var b00 = addend.low & 0xFFFF;
  2849. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2850. c00 += a00 + b00;
  2851. c16 += c00 >>> 16;
  2852. c00 &= 0xFFFF;
  2853. c16 += a16 + b16;
  2854. c32 += c16 >>> 16;
  2855. c16 &= 0xFFFF;
  2856. c32 += a32 + b32;
  2857. c48 += c32 >>> 16;
  2858. c32 &= 0xFFFF;
  2859. c48 += a48 + b48;
  2860. c48 &= 0xFFFF;
  2861. return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2862. };
  2863. /**
  2864. * Returns the difference of this and the specified Long.
  2865. * @param {!Long|number|string} subtrahend Subtrahend
  2866. * @returns {!Long} Difference
  2867. */
  2868. LongPrototype.subtract = function subtract(subtrahend) {
  2869. if (!isLong(subtrahend))
  2870. subtrahend = fromValue(subtrahend);
  2871. return this.add(subtrahend.neg());
  2872. };
  2873. /**
  2874. * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
  2875. * @function
  2876. * @param {!Long|number|string} subtrahend Subtrahend
  2877. * @returns {!Long} Difference
  2878. */
  2879. LongPrototype.sub = LongPrototype.subtract;
  2880. /**
  2881. * Returns the product of this and the specified Long.
  2882. * @param {!Long|number|string} multiplier Multiplier
  2883. * @returns {!Long} Product
  2884. */
  2885. LongPrototype.multiply = function multiply(multiplier) {
  2886. if (this.isZero())
  2887. return ZERO;
  2888. if (!isLong(multiplier))
  2889. multiplier = fromValue(multiplier);
  2890. if (multiplier.isZero())
  2891. return ZERO;
  2892. if (this.eq(MIN_VALUE))
  2893. return multiplier.isOdd() ? MIN_VALUE : ZERO;
  2894. if (multiplier.eq(MIN_VALUE))
  2895. return this.isOdd() ? MIN_VALUE : ZERO;
  2896. if (this.isNegative()) {
  2897. if (multiplier.isNegative())
  2898. return this.neg().mul(multiplier.neg());
  2899. else
  2900. return this.neg().mul(multiplier).neg();
  2901. } else if (multiplier.isNegative())
  2902. return this.mul(multiplier.neg()).neg();
  2903. // If both longs are small, use float multiplication
  2904. if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
  2905. return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  2906. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  2907. // We can skip products that would overflow.
  2908. var a48 = this.high >>> 16;
  2909. var a32 = this.high & 0xFFFF;
  2910. var a16 = this.low >>> 16;
  2911. var a00 = this.low & 0xFFFF;
  2912. var b48 = multiplier.high >>> 16;
  2913. var b32 = multiplier.high & 0xFFFF;
  2914. var b16 = multiplier.low >>> 16;
  2915. var b00 = multiplier.low & 0xFFFF;
  2916. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2917. c00 += a00 * b00;
  2918. c16 += c00 >>> 16;
  2919. c00 &= 0xFFFF;
  2920. c16 += a16 * b00;
  2921. c32 += c16 >>> 16;
  2922. c16 &= 0xFFFF;
  2923. c16 += a00 * b16;
  2924. c32 += c16 >>> 16;
  2925. c16 &= 0xFFFF;
  2926. c32 += a32 * b00;
  2927. c48 += c32 >>> 16;
  2928. c32 &= 0xFFFF;
  2929. c32 += a16 * b16;
  2930. c48 += c32 >>> 16;
  2931. c32 &= 0xFFFF;
  2932. c32 += a00 * b32;
  2933. c48 += c32 >>> 16;
  2934. c32 &= 0xFFFF;
  2935. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  2936. c48 &= 0xFFFF;
  2937. return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2938. };
  2939. /**
  2940. * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
  2941. * @function
  2942. * @param {!Long|number|string} multiplier Multiplier
  2943. * @returns {!Long} Product
  2944. */
  2945. LongPrototype.mul = LongPrototype.multiply;
  2946. /**
  2947. * Returns this Long divided by the specified. The result is signed if this Long is signed or
  2948. * unsigned if this Long is unsigned.
  2949. * @param {!Long|number|string} divisor Divisor
  2950. * @returns {!Long} Quotient
  2951. */
  2952. LongPrototype.divide = function divide(divisor) {
  2953. if (!isLong(divisor))
  2954. divisor = fromValue(divisor);
  2955. if (divisor.isZero())
  2956. throw Error('division by zero');
  2957. if (this.isZero())
  2958. return this.unsigned ? UZERO : ZERO;
  2959. var approx, rem, res;
  2960. if (!this.unsigned) {
  2961. // This section is only relevant for signed longs and is derived from the
  2962. // closure library as a whole.
  2963. if (this.eq(MIN_VALUE)) {
  2964. if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
  2965. return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
  2966. else if (divisor.eq(MIN_VALUE))
  2967. return ONE;
  2968. else {
  2969. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  2970. var halfThis = this.shr(1);
  2971. approx = halfThis.div(divisor).shl(1);
  2972. if (approx.eq(ZERO)) {
  2973. return divisor.isNegative() ? ONE : NEG_ONE;
  2974. } else {
  2975. rem = this.sub(divisor.mul(approx));
  2976. res = approx.add(rem.div(divisor));
  2977. return res;
  2978. }
  2979. }
  2980. } else if (divisor.eq(MIN_VALUE))
  2981. return this.unsigned ? UZERO : ZERO;
  2982. if (this.isNegative()) {
  2983. if (divisor.isNegative())
  2984. return this.neg().div(divisor.neg());
  2985. return this.neg().div(divisor).neg();
  2986. } else if (divisor.isNegative())
  2987. return this.div(divisor.neg()).neg();
  2988. res = ZERO;
  2989. } else {
  2990. // The algorithm below has not been made for unsigned longs. It's therefore
  2991. // required to take special care of the MSB prior to running it.
  2992. if (!divisor.unsigned)
  2993. divisor = divisor.toUnsigned();
  2994. if (divisor.gt(this))
  2995. return UZERO;
  2996. if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
  2997. return UONE;
  2998. res = UZERO;
  2999. }
  3000. // Repeat the following until the remainder is less than other: find a
  3001. // floating-point that approximates remainder / other *from below*, add this
  3002. // into the result, and subtract it from the remainder. It is critical that
  3003. // the approximate value is less than or equal to the real value so that the
  3004. // remainder never becomes negative.
  3005. rem = this;
  3006. while (rem.gte(divisor)) {
  3007. // Approximate the result of division. This may be a little greater or
  3008. // smaller than the actual value.
  3009. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  3010. // We will tweak the approximate result by changing it in the 48-th digit or
  3011. // the smallest non-fractional digit, whichever is larger.
  3012. var log2 = Math.ceil(Math.log(approx) / Math.LN2),
  3013. delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
  3014. // Decrease the approximation until it is smaller than the remainder. Note
  3015. // that if it is too large, the product overflows and is negative.
  3016. approxRes = fromNumber(approx),
  3017. approxRem = approxRes.mul(divisor);
  3018. while (approxRem.isNegative() || approxRem.gt(rem)) {
  3019. approx -= delta;
  3020. approxRes = fromNumber(approx, this.unsigned);
  3021. approxRem = approxRes.mul(divisor);
  3022. }
  3023. // We know the answer can't be zero... and actually, zero would cause
  3024. // infinite recursion since we would make no progress.
  3025. if (approxRes.isZero())
  3026. approxRes = ONE;
  3027. res = res.add(approxRes);
  3028. rem = rem.sub(approxRem);
  3029. }
  3030. return res;
  3031. };
  3032. /**
  3033. * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
  3034. * @function
  3035. * @param {!Long|number|string} divisor Divisor
  3036. * @returns {!Long} Quotient
  3037. */
  3038. LongPrototype.div = LongPrototype.divide;
  3039. /**
  3040. * Returns this Long modulo the specified.
  3041. * @param {!Long|number|string} divisor Divisor
  3042. * @returns {!Long} Remainder
  3043. */
  3044. LongPrototype.modulo = function modulo(divisor) {
  3045. if (!isLong(divisor))
  3046. divisor = fromValue(divisor);
  3047. return this.sub(this.div(divisor).mul(divisor));
  3048. };
  3049. /**
  3050. * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
  3051. * @function
  3052. * @param {!Long|number|string} divisor Divisor
  3053. * @returns {!Long} Remainder
  3054. */
  3055. LongPrototype.mod = LongPrototype.modulo;
  3056. /**
  3057. * Returns the bitwise NOT of this Long.
  3058. * @returns {!Long}
  3059. */
  3060. LongPrototype.not = function not() {
  3061. return fromBits(~this.low, ~this.high, this.unsigned);
  3062. };
  3063. /**
  3064. * Returns the bitwise AND of this Long and the specified.
  3065. * @param {!Long|number|string} other Other Long
  3066. * @returns {!Long}
  3067. */
  3068. LongPrototype.and = function and(other) {
  3069. if (!isLong(other))
  3070. other = fromValue(other);
  3071. return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  3072. };
  3073. /**
  3074. * Returns the bitwise OR of this Long and the specified.
  3075. * @param {!Long|number|string} other Other Long
  3076. * @returns {!Long}
  3077. */
  3078. LongPrototype.or = function or(other) {
  3079. if (!isLong(other))
  3080. other = fromValue(other);
  3081. return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  3082. };
  3083. /**
  3084. * Returns the bitwise XOR of this Long and the given one.
  3085. * @param {!Long|number|string} other Other Long
  3086. * @returns {!Long}
  3087. */
  3088. LongPrototype.xor = function xor(other) {
  3089. if (!isLong(other))
  3090. other = fromValue(other);
  3091. return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  3092. };
  3093. /**
  3094. * Returns this Long with bits shifted to the left by the given amount.
  3095. * @param {number|!Long} numBits Number of bits
  3096. * @returns {!Long} Shifted Long
  3097. */
  3098. LongPrototype.shiftLeft = function shiftLeft(numBits) {
  3099. if (isLong(numBits))
  3100. numBits = numBits.toInt();
  3101. if ((numBits &= 63) === 0)
  3102. return this;
  3103. else if (numBits < 32)
  3104. return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  3105. else
  3106. return fromBits(0, this.low << (numBits - 32), this.unsigned);
  3107. };
  3108. /**
  3109. * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
  3110. * @function
  3111. * @param {number|!Long} numBits Number of bits
  3112. * @returns {!Long} Shifted Long
  3113. */
  3114. LongPrototype.shl = LongPrototype.shiftLeft;
  3115. /**
  3116. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  3117. * @param {number|!Long} numBits Number of bits
  3118. * @returns {!Long} Shifted Long
  3119. */
  3120. LongPrototype.shiftRight = function shiftRight(numBits) {
  3121. if (isLong(numBits))
  3122. numBits = numBits.toInt();
  3123. if ((numBits &= 63) === 0)
  3124. return this;
  3125. else if (numBits < 32)
  3126. return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  3127. else
  3128. return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  3129. };
  3130. /**
  3131. * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
  3132. * @function
  3133. * @param {number|!Long} numBits Number of bits
  3134. * @returns {!Long} Shifted Long
  3135. */
  3136. LongPrototype.shr = LongPrototype.shiftRight;
  3137. /**
  3138. * Returns this Long with bits logically shifted to the right by the given amount.
  3139. * @param {number|!Long} numBits Number of bits
  3140. * @returns {!Long} Shifted Long
  3141. */
  3142. LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
  3143. if (isLong(numBits))
  3144. numBits = numBits.toInt();
  3145. numBits &= 63;
  3146. if (numBits === 0)
  3147. return this;
  3148. else {
  3149. var high = this.high;
  3150. if (numBits < 32) {
  3151. var low = this.low;
  3152. return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  3153. } else if (numBits === 32)
  3154. return fromBits(high, 0, this.unsigned);
  3155. else
  3156. return fromBits(high >>> (numBits - 32), 0, this.unsigned);
  3157. }
  3158. };
  3159. /**
  3160. * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
  3161. * @function
  3162. * @param {number|!Long} numBits Number of bits
  3163. * @returns {!Long} Shifted Long
  3164. */
  3165. LongPrototype.shru = LongPrototype.shiftRightUnsigned;
  3166. /**
  3167. * Converts this Long to signed.
  3168. * @returns {!Long} Signed long
  3169. */
  3170. LongPrototype.toSigned = function toSigned() {
  3171. if (!this.unsigned)
  3172. return this;
  3173. return fromBits(this.low, this.high, false);
  3174. };
  3175. /**
  3176. * Converts this Long to unsigned.
  3177. * @returns {!Long} Unsigned long
  3178. */
  3179. LongPrototype.toUnsigned = function toUnsigned() {
  3180. if (this.unsigned)
  3181. return this;
  3182. return fromBits(this.low, this.high, true);
  3183. };
  3184. /**
  3185. * Converts this Long to its byte representation.
  3186. * @param {boolean=} le Whether little or big endian, defaults to big endian
  3187. * @returns {!Array.<number>} Byte representation
  3188. */
  3189. LongPrototype.toBytes = function(le) {
  3190. return le ? this.toBytesLE() : this.toBytesBE();
  3191. };
  3192. /**
  3193. * Converts this Long to its little endian byte representation.
  3194. * @returns {!Array.<number>} Little endian byte representation
  3195. */
  3196. LongPrototype.toBytesLE = function() {
  3197. var hi = this.high,
  3198. lo = this.low;
  3199. return [
  3200. lo & 0xff,
  3201. (lo >>> 8) & 0xff,
  3202. (lo >>> 16) & 0xff,
  3203. (lo >>> 24) & 0xff,
  3204. hi & 0xff,
  3205. (hi >>> 8) & 0xff,
  3206. (hi >>> 16) & 0xff,
  3207. (hi >>> 24) & 0xff
  3208. ];
  3209. };
  3210. /**
  3211. * Converts this Long to its big endian byte representation.
  3212. * @returns {!Array.<number>} Big endian byte representation
  3213. */
  3214. LongPrototype.toBytesBE = function() {
  3215. var hi = this.high,
  3216. lo = this.low;
  3217. return [
  3218. (hi >>> 24) & 0xff,
  3219. (hi >>> 16) & 0xff,
  3220. (hi >>> 8) & 0xff,
  3221. hi & 0xff,
  3222. (lo >>> 24) & 0xff,
  3223. (lo >>> 16) & 0xff,
  3224. (lo >>> 8) & 0xff,
  3225. lo & 0xff
  3226. ];
  3227. };
  3228. return Long;
  3229. });
  3230. });
  3231. var bytebuffer = createCommonjsModule(function (module) {
  3232. /*
  3233. Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
  3234. Licensed under the Apache License, Version 2.0 (the "License");
  3235. you may not use this file except in compliance with the License.
  3236. You may obtain a copy of the License at
  3237. http://www.apache.org/licenses/LICENSE-2.0
  3238. Unless required by applicable law or agreed to in writing, software
  3239. distributed under the License is distributed on an "AS IS" BASIS,
  3240. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3241. See the License for the specific language governing permissions and
  3242. limitations under the License.
  3243. */
  3244. /**
  3245. * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
  3246. * Backing buffer: ArrayBuffer, Accessor: Uint8Array
  3247. * Released under the Apache License, Version 2.0
  3248. * see: https://github.com/dcodeIO/bytebuffer.js for details
  3249. */
  3250. (function(global, factory) {
  3251. /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
  3252. module['exports'] = (function() {
  3253. var Long; try { Long = long_1; } catch (e) {}
  3254. return factory(Long);
  3255. })();
  3256. /* Global */ else
  3257. (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
  3258. })(commonjsGlobal, function(Long) {
  3259. /**
  3260. * Constructs a new ByteBuffer.
  3261. * @class The swiss army knife for binary data in JavaScript.
  3262. * @exports ByteBuffer
  3263. * @constructor
  3264. * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
  3265. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  3266. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  3267. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  3268. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  3269. * @expose
  3270. */
  3271. var ByteBuffer = function(capacity, littleEndian, noAssert) {
  3272. if (typeof capacity === 'undefined')
  3273. capacity = ByteBuffer.DEFAULT_CAPACITY;
  3274. if (typeof littleEndian === 'undefined')
  3275. littleEndian = ByteBuffer.DEFAULT_ENDIAN;
  3276. if (typeof noAssert === 'undefined')
  3277. noAssert = ByteBuffer.DEFAULT_NOASSERT;
  3278. if (!noAssert) {
  3279. capacity = capacity | 0;
  3280. if (capacity < 0)
  3281. throw RangeError("Illegal capacity");
  3282. littleEndian = !!littleEndian;
  3283. noAssert = !!noAssert;
  3284. }
  3285. /**
  3286. * Backing ArrayBuffer.
  3287. * @type {!ArrayBuffer}
  3288. * @expose
  3289. */
  3290. this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
  3291. /**
  3292. * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
  3293. * @type {?Uint8Array}
  3294. * @expose
  3295. */
  3296. this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
  3297. /**
  3298. * Absolute read/write offset.
  3299. * @type {number}
  3300. * @expose
  3301. * @see ByteBuffer#flip
  3302. * @see ByteBuffer#clear
  3303. */
  3304. this.offset = 0;
  3305. /**
  3306. * Marked offset.
  3307. * @type {number}
  3308. * @expose
  3309. * @see ByteBuffer#mark
  3310. * @see ByteBuffer#reset
  3311. */
  3312. this.markedOffset = -1;
  3313. /**
  3314. * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
  3315. * @type {number}
  3316. * @expose
  3317. * @see ByteBuffer#flip
  3318. * @see ByteBuffer#clear
  3319. */
  3320. this.limit = capacity;
  3321. /**
  3322. * Whether to use little endian byte order, defaults to `false` for big endian.
  3323. * @type {boolean}
  3324. * @expose
  3325. */
  3326. this.littleEndian = littleEndian;
  3327. /**
  3328. * Whether to skip assertions of offsets and values, defaults to `false`.
  3329. * @type {boolean}
  3330. * @expose
  3331. */
  3332. this.noAssert = noAssert;
  3333. };
  3334. /**
  3335. * ByteBuffer version.
  3336. * @type {string}
  3337. * @const
  3338. * @expose
  3339. */
  3340. ByteBuffer.VERSION = "5.0.1";
  3341. /**
  3342. * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
  3343. * @type {boolean}
  3344. * @const
  3345. * @expose
  3346. */
  3347. ByteBuffer.LITTLE_ENDIAN = true;
  3348. /**
  3349. * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
  3350. * @type {boolean}
  3351. * @const
  3352. * @expose
  3353. */
  3354. ByteBuffer.BIG_ENDIAN = false;
  3355. /**
  3356. * Default initial capacity of `16`.
  3357. * @type {number}
  3358. * @expose
  3359. */
  3360. ByteBuffer.DEFAULT_CAPACITY = 16;
  3361. /**
  3362. * Default endianess of `false` for big endian.
  3363. * @type {boolean}
  3364. * @expose
  3365. */
  3366. ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
  3367. /**
  3368. * Default no assertions flag of `false`.
  3369. * @type {boolean}
  3370. * @expose
  3371. */
  3372. ByteBuffer.DEFAULT_NOASSERT = false;
  3373. /**
  3374. * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
  3375. * and int64 support is not available.
  3376. * @type {?Long}
  3377. * @const
  3378. * @see https://github.com/dcodeIO/long.js
  3379. * @expose
  3380. */
  3381. ByteBuffer.Long = Long || null;
  3382. /**
  3383. * @alias ByteBuffer.prototype
  3384. * @inner
  3385. */
  3386. var ByteBufferPrototype = ByteBuffer.prototype;
  3387. /**
  3388. * An indicator used to reliably determine if an object is a ByteBuffer or not.
  3389. * @type {boolean}
  3390. * @const
  3391. * @expose
  3392. * @private
  3393. */
  3394. ByteBufferPrototype.__isByteBuffer__;
  3395. Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
  3396. value: true,
  3397. enumerable: false,
  3398. configurable: false
  3399. });
  3400. // helpers
  3401. /**
  3402. * @type {!ArrayBuffer}
  3403. * @inner
  3404. */
  3405. var EMPTY_BUFFER = new ArrayBuffer(0);
  3406. /**
  3407. * String.fromCharCode reference for compile-time renaming.
  3408. * @type {function(...number):string}
  3409. * @inner
  3410. */
  3411. var stringFromCharCode = String.fromCharCode;
  3412. /**
  3413. * Creates a source function for a string.
  3414. * @param {string} s String to read from
  3415. * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
  3416. * no more characters left.
  3417. * @throws {TypeError} If the argument is invalid
  3418. * @inner
  3419. */
  3420. function stringSource(s) {
  3421. var i=0; return function() {
  3422. return i < s.length ? s.charCodeAt(i++) : null;
  3423. };
  3424. }
  3425. /**
  3426. * Creates a destination function for a string.
  3427. * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
  3428. * Returns the final string when called without arguments.
  3429. * @inner
  3430. */
  3431. function stringDestination() {
  3432. var cs = [], ps = []; return function() {
  3433. if (arguments.length === 0)
  3434. return ps.join('')+stringFromCharCode.apply(String, cs);
  3435. if (cs.length + arguments.length > 1024)
  3436. ps.push(stringFromCharCode.apply(String, cs)),
  3437. cs.length = 0;
  3438. Array.prototype.push.apply(cs, arguments);
  3439. };
  3440. }
  3441. /**
  3442. * Gets the accessor type.
  3443. * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
  3444. * @expose
  3445. */
  3446. ByteBuffer.accessor = function() {
  3447. return Uint8Array;
  3448. };
  3449. /**
  3450. * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
  3451. * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
  3452. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  3453. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  3454. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  3455. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  3456. * @returns {!ByteBuffer}
  3457. * @expose
  3458. */
  3459. ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
  3460. return new ByteBuffer(capacity, littleEndian, noAssert);
  3461. };
  3462. /**
  3463. * Concatenates multiple ByteBuffers into one.
  3464. * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
  3465. * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
  3466. * defaults to "utf8")
  3467. * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
  3468. * to {@link ByteBuffer.DEFAULT_ENDIAN}.
  3469. * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
  3470. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  3471. * @returns {!ByteBuffer} Concatenated ByteBuffer
  3472. * @expose
  3473. */
  3474. ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
  3475. if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
  3476. noAssert = littleEndian;
  3477. littleEndian = encoding;
  3478. encoding = undefined;
  3479. }
  3480. var capacity = 0;
  3481. for (var i=0, k=buffers.length, length; i<k; ++i) {
  3482. if (!ByteBuffer.isByteBuffer(buffers[i]))
  3483. buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
  3484. length = buffers[i].limit - buffers[i].offset;
  3485. if (length > 0) capacity += length;
  3486. }
  3487. if (capacity === 0)
  3488. return new ByteBuffer(0, littleEndian, noAssert);
  3489. var bb = new ByteBuffer(capacity, littleEndian, noAssert),
  3490. bi;
  3491. i=0; while (i<k) {
  3492. bi = buffers[i++];
  3493. length = bi.limit - bi.offset;
  3494. if (length <= 0) continue;
  3495. bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
  3496. bb.offset += length;
  3497. }
  3498. bb.limit = bb.offset;
  3499. bb.offset = 0;
  3500. return bb;
  3501. };
  3502. /**
  3503. * Tests if the specified type is a ByteBuffer.
  3504. * @param {*} bb ByteBuffer to test
  3505. * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
  3506. * @expose
  3507. */
  3508. ByteBuffer.isByteBuffer = function(bb) {
  3509. return (bb && bb["__isByteBuffer__"]) === true;
  3510. };
  3511. /**
  3512. * Gets the backing buffer type.
  3513. * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
  3514. * @expose
  3515. */
  3516. ByteBuffer.type = function() {
  3517. return ArrayBuffer;
  3518. };
  3519. /**
  3520. * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
  3521. * {@link ByteBuffer#limit} to the length of the wrapped data.
  3522. * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
  3523. * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
  3524. * "utf8")
  3525. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  3526. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  3527. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  3528. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  3529. * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
  3530. * @expose
  3531. */
  3532. ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
  3533. if (typeof encoding !== 'string') {
  3534. noAssert = littleEndian;
  3535. littleEndian = encoding;
  3536. encoding = undefined;
  3537. }
  3538. if (typeof buffer === 'string') {
  3539. if (typeof encoding === 'undefined')
  3540. encoding = "utf8";
  3541. switch (encoding) {
  3542. case "base64":
  3543. return ByteBuffer.fromBase64(buffer, littleEndian);
  3544. case "hex":
  3545. return ByteBuffer.fromHex(buffer, littleEndian);
  3546. case "binary":
  3547. return ByteBuffer.fromBinary(buffer, littleEndian);
  3548. case "utf8":
  3549. return ByteBuffer.fromUTF8(buffer, littleEndian);
  3550. case "debug":
  3551. return ByteBuffer.fromDebug(buffer, littleEndian);
  3552. default:
  3553. throw Error("Unsupported encoding: "+encoding);
  3554. }
  3555. }
  3556. if (buffer === null || typeof buffer !== 'object')
  3557. throw TypeError("Illegal buffer");
  3558. var bb;
  3559. if (ByteBuffer.isByteBuffer(buffer)) {
  3560. bb = ByteBufferPrototype.clone.call(buffer);
  3561. bb.markedOffset = -1;
  3562. return bb;
  3563. }
  3564. if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
  3565. bb = new ByteBuffer(0, littleEndian, noAssert);
  3566. if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
  3567. bb.buffer = buffer.buffer;
  3568. bb.offset = buffer.byteOffset;
  3569. bb.limit = buffer.byteOffset + buffer.byteLength;
  3570. bb.view = new Uint8Array(buffer.buffer);
  3571. }
  3572. } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
  3573. bb = new ByteBuffer(0, littleEndian, noAssert);
  3574. if (buffer.byteLength > 0) {
  3575. bb.buffer = buffer;
  3576. bb.offset = 0;
  3577. bb.limit = buffer.byteLength;
  3578. bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
  3579. }
  3580. } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
  3581. bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
  3582. bb.limit = buffer.length;
  3583. for (var i=0; i<buffer.length; ++i)
  3584. bb.view[i] = buffer[i];
  3585. } else
  3586. throw TypeError("Illegal buffer"); // Otherwise fail
  3587. return bb;
  3588. };
  3589. /**
  3590. * Writes the array as a bitset.
  3591. * @param {Array<boolean>} value Array of booleans to write
  3592. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
  3593. * @returns {!ByteBuffer}
  3594. * @expose
  3595. */
  3596. ByteBufferPrototype.writeBitSet = function(value, offset) {
  3597. var relative = typeof offset === 'undefined';
  3598. if (relative) offset = this.offset;
  3599. if (!this.noAssert) {
  3600. if (!(value instanceof Array))
  3601. throw TypeError("Illegal BitSet: Not an array");
  3602. if (typeof offset !== 'number' || offset % 1 !== 0)
  3603. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3604. offset >>>= 0;
  3605. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  3606. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  3607. }
  3608. var start = offset,
  3609. bits = value.length,
  3610. bytes = (bits >> 3),
  3611. bit = 0,
  3612. k;
  3613. offset += this.writeVarint32(bits,offset);
  3614. while(bytes--) {
  3615. k = (!!value[bit++] & 1) |
  3616. ((!!value[bit++] & 1) << 1) |
  3617. ((!!value[bit++] & 1) << 2) |
  3618. ((!!value[bit++] & 1) << 3) |
  3619. ((!!value[bit++] & 1) << 4) |
  3620. ((!!value[bit++] & 1) << 5) |
  3621. ((!!value[bit++] & 1) << 6) |
  3622. ((!!value[bit++] & 1) << 7);
  3623. this.writeByte(k,offset++);
  3624. }
  3625. if(bit < bits) {
  3626. var m = 0; k = 0;
  3627. while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
  3628. this.writeByte(k,offset++);
  3629. }
  3630. if (relative) {
  3631. this.offset = offset;
  3632. return this;
  3633. }
  3634. return offset - start;
  3635. };
  3636. /**
  3637. * Reads a BitSet as an array of booleans.
  3638. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
  3639. * @returns {Array<boolean>
  3640. * @expose
  3641. */
  3642. ByteBufferPrototype.readBitSet = function(offset) {
  3643. var relative = typeof offset === 'undefined';
  3644. if (relative) offset = this.offset;
  3645. var ret = this.readVarint32(offset),
  3646. bits = ret.value,
  3647. bytes = (bits >> 3),
  3648. bit = 0,
  3649. value = [],
  3650. k;
  3651. offset += ret.length;
  3652. while(bytes--) {
  3653. k = this.readByte(offset++);
  3654. value[bit++] = !!(k & 0x01);
  3655. value[bit++] = !!(k & 0x02);
  3656. value[bit++] = !!(k & 0x04);
  3657. value[bit++] = !!(k & 0x08);
  3658. value[bit++] = !!(k & 0x10);
  3659. value[bit++] = !!(k & 0x20);
  3660. value[bit++] = !!(k & 0x40);
  3661. value[bit++] = !!(k & 0x80);
  3662. }
  3663. if(bit < bits) {
  3664. var m = 0;
  3665. k = this.readByte(offset++);
  3666. while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
  3667. }
  3668. if (relative) {
  3669. this.offset = offset;
  3670. }
  3671. return value;
  3672. };
  3673. /**
  3674. * Reads the specified number of bytes.
  3675. * @param {number} length Number of bytes to read
  3676. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
  3677. * @returns {!ByteBuffer}
  3678. * @expose
  3679. */
  3680. ByteBufferPrototype.readBytes = function(length, offset) {
  3681. var relative = typeof offset === 'undefined';
  3682. if (relative) offset = this.offset;
  3683. if (!this.noAssert) {
  3684. if (typeof offset !== 'number' || offset % 1 !== 0)
  3685. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3686. offset >>>= 0;
  3687. if (offset < 0 || offset + length > this.buffer.byteLength)
  3688. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
  3689. }
  3690. var slice = this.slice(offset, offset + length);
  3691. if (relative) this.offset += length;
  3692. return slice;
  3693. };
  3694. /**
  3695. * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
  3696. * @function
  3697. * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
  3698. * will be modified according to the performed read operation.
  3699. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
  3700. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  3701. * written if omitted.
  3702. * @returns {!ByteBuffer} this
  3703. * @expose
  3704. */
  3705. ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
  3706. // types/ints/int8
  3707. /**
  3708. * Writes an 8bit signed integer.
  3709. * @param {number} value Value to write
  3710. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3711. * @returns {!ByteBuffer} this
  3712. * @expose
  3713. */
  3714. ByteBufferPrototype.writeInt8 = function(value, offset) {
  3715. var relative = typeof offset === 'undefined';
  3716. if (relative) offset = this.offset;
  3717. if (!this.noAssert) {
  3718. if (typeof value !== 'number' || value % 1 !== 0)
  3719. throw TypeError("Illegal value: "+value+" (not an integer)");
  3720. value |= 0;
  3721. if (typeof offset !== 'number' || offset % 1 !== 0)
  3722. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3723. offset >>>= 0;
  3724. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  3725. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  3726. }
  3727. offset += 1;
  3728. var capacity0 = this.buffer.byteLength;
  3729. if (offset > capacity0)
  3730. this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
  3731. offset -= 1;
  3732. this.view[offset] = value;
  3733. if (relative) this.offset += 1;
  3734. return this;
  3735. };
  3736. /**
  3737. * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
  3738. * @function
  3739. * @param {number} value Value to write
  3740. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3741. * @returns {!ByteBuffer} this
  3742. * @expose
  3743. */
  3744. ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
  3745. /**
  3746. * Reads an 8bit signed integer.
  3747. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3748. * @returns {number} Value read
  3749. * @expose
  3750. */
  3751. ByteBufferPrototype.readInt8 = function(offset) {
  3752. var relative = typeof offset === 'undefined';
  3753. if (relative) offset = this.offset;
  3754. if (!this.noAssert) {
  3755. if (typeof offset !== 'number' || offset % 1 !== 0)
  3756. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3757. offset >>>= 0;
  3758. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  3759. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  3760. }
  3761. var value = this.view[offset];
  3762. if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
  3763. if (relative) this.offset += 1;
  3764. return value;
  3765. };
  3766. /**
  3767. * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
  3768. * @function
  3769. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3770. * @returns {number} Value read
  3771. * @expose
  3772. */
  3773. ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
  3774. /**
  3775. * Writes an 8bit unsigned integer.
  3776. * @param {number} value Value to write
  3777. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3778. * @returns {!ByteBuffer} this
  3779. * @expose
  3780. */
  3781. ByteBufferPrototype.writeUint8 = function(value, offset) {
  3782. var relative = typeof offset === 'undefined';
  3783. if (relative) offset = this.offset;
  3784. if (!this.noAssert) {
  3785. if (typeof value !== 'number' || value % 1 !== 0)
  3786. throw TypeError("Illegal value: "+value+" (not an integer)");
  3787. value >>>= 0;
  3788. if (typeof offset !== 'number' || offset % 1 !== 0)
  3789. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3790. offset >>>= 0;
  3791. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  3792. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  3793. }
  3794. offset += 1;
  3795. var capacity1 = this.buffer.byteLength;
  3796. if (offset > capacity1)
  3797. this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
  3798. offset -= 1;
  3799. this.view[offset] = value;
  3800. if (relative) this.offset += 1;
  3801. return this;
  3802. };
  3803. /**
  3804. * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
  3805. * @function
  3806. * @param {number} value Value to write
  3807. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3808. * @returns {!ByteBuffer} this
  3809. * @expose
  3810. */
  3811. ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
  3812. /**
  3813. * Reads an 8bit unsigned integer.
  3814. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3815. * @returns {number} Value read
  3816. * @expose
  3817. */
  3818. ByteBufferPrototype.readUint8 = function(offset) {
  3819. var relative = typeof offset === 'undefined';
  3820. if (relative) offset = this.offset;
  3821. if (!this.noAssert) {
  3822. if (typeof offset !== 'number' || offset % 1 !== 0)
  3823. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3824. offset >>>= 0;
  3825. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  3826. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  3827. }
  3828. var value = this.view[offset];
  3829. if (relative) this.offset += 1;
  3830. return value;
  3831. };
  3832. /**
  3833. * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
  3834. * @function
  3835. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
  3836. * @returns {number} Value read
  3837. * @expose
  3838. */
  3839. ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
  3840. // types/ints/int16
  3841. /**
  3842. * Writes a 16bit signed integer.
  3843. * @param {number} value Value to write
  3844. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3845. * @throws {TypeError} If `offset` or `value` is not a valid number
  3846. * @throws {RangeError} If `offset` is out of bounds
  3847. * @expose
  3848. */
  3849. ByteBufferPrototype.writeInt16 = function(value, offset) {
  3850. var relative = typeof offset === 'undefined';
  3851. if (relative) offset = this.offset;
  3852. if (!this.noAssert) {
  3853. if (typeof value !== 'number' || value % 1 !== 0)
  3854. throw TypeError("Illegal value: "+value+" (not an integer)");
  3855. value |= 0;
  3856. if (typeof offset !== 'number' || offset % 1 !== 0)
  3857. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3858. offset >>>= 0;
  3859. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  3860. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  3861. }
  3862. offset += 2;
  3863. var capacity2 = this.buffer.byteLength;
  3864. if (offset > capacity2)
  3865. this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
  3866. offset -= 2;
  3867. if (this.littleEndian) {
  3868. this.view[offset+1] = (value & 0xFF00) >>> 8;
  3869. this.view[offset ] = value & 0x00FF;
  3870. } else {
  3871. this.view[offset] = (value & 0xFF00) >>> 8;
  3872. this.view[offset+1] = value & 0x00FF;
  3873. }
  3874. if (relative) this.offset += 2;
  3875. return this;
  3876. };
  3877. /**
  3878. * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
  3879. * @function
  3880. * @param {number} value Value to write
  3881. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3882. * @throws {TypeError} If `offset` or `value` is not a valid number
  3883. * @throws {RangeError} If `offset` is out of bounds
  3884. * @expose
  3885. */
  3886. ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
  3887. /**
  3888. * Reads a 16bit signed integer.
  3889. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3890. * @returns {number} Value read
  3891. * @throws {TypeError} If `offset` is not a valid number
  3892. * @throws {RangeError} If `offset` is out of bounds
  3893. * @expose
  3894. */
  3895. ByteBufferPrototype.readInt16 = function(offset) {
  3896. var relative = typeof offset === 'undefined';
  3897. if (relative) offset = this.offset;
  3898. if (!this.noAssert) {
  3899. if (typeof offset !== 'number' || offset % 1 !== 0)
  3900. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3901. offset >>>= 0;
  3902. if (offset < 0 || offset + 2 > this.buffer.byteLength)
  3903. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
  3904. }
  3905. var value = 0;
  3906. if (this.littleEndian) {
  3907. value = this.view[offset ];
  3908. value |= this.view[offset+1] << 8;
  3909. } else {
  3910. value = this.view[offset ] << 8;
  3911. value |= this.view[offset+1];
  3912. }
  3913. if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
  3914. if (relative) this.offset += 2;
  3915. return value;
  3916. };
  3917. /**
  3918. * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
  3919. * @function
  3920. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3921. * @returns {number} Value read
  3922. * @throws {TypeError} If `offset` is not a valid number
  3923. * @throws {RangeError} If `offset` is out of bounds
  3924. * @expose
  3925. */
  3926. ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
  3927. /**
  3928. * Writes a 16bit unsigned integer.
  3929. * @param {number} value Value to write
  3930. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3931. * @throws {TypeError} If `offset` or `value` is not a valid number
  3932. * @throws {RangeError} If `offset` is out of bounds
  3933. * @expose
  3934. */
  3935. ByteBufferPrototype.writeUint16 = function(value, offset) {
  3936. var relative = typeof offset === 'undefined';
  3937. if (relative) offset = this.offset;
  3938. if (!this.noAssert) {
  3939. if (typeof value !== 'number' || value % 1 !== 0)
  3940. throw TypeError("Illegal value: "+value+" (not an integer)");
  3941. value >>>= 0;
  3942. if (typeof offset !== 'number' || offset % 1 !== 0)
  3943. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3944. offset >>>= 0;
  3945. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  3946. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  3947. }
  3948. offset += 2;
  3949. var capacity3 = this.buffer.byteLength;
  3950. if (offset > capacity3)
  3951. this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
  3952. offset -= 2;
  3953. if (this.littleEndian) {
  3954. this.view[offset+1] = (value & 0xFF00) >>> 8;
  3955. this.view[offset ] = value & 0x00FF;
  3956. } else {
  3957. this.view[offset] = (value & 0xFF00) >>> 8;
  3958. this.view[offset+1] = value & 0x00FF;
  3959. }
  3960. if (relative) this.offset += 2;
  3961. return this;
  3962. };
  3963. /**
  3964. * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
  3965. * @function
  3966. * @param {number} value Value to write
  3967. * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3968. * @throws {TypeError} If `offset` or `value` is not a valid number
  3969. * @throws {RangeError} If `offset` is out of bounds
  3970. * @expose
  3971. */
  3972. ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
  3973. /**
  3974. * Reads a 16bit unsigned integer.
  3975. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  3976. * @returns {number} Value read
  3977. * @throws {TypeError} If `offset` is not a valid number
  3978. * @throws {RangeError} If `offset` is out of bounds
  3979. * @expose
  3980. */
  3981. ByteBufferPrototype.readUint16 = function(offset) {
  3982. var relative = typeof offset === 'undefined';
  3983. if (relative) offset = this.offset;
  3984. if (!this.noAssert) {
  3985. if (typeof offset !== 'number' || offset % 1 !== 0)
  3986. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  3987. offset >>>= 0;
  3988. if (offset < 0 || offset + 2 > this.buffer.byteLength)
  3989. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
  3990. }
  3991. var value = 0;
  3992. if (this.littleEndian) {
  3993. value = this.view[offset ];
  3994. value |= this.view[offset+1] << 8;
  3995. } else {
  3996. value = this.view[offset ] << 8;
  3997. value |= this.view[offset+1];
  3998. }
  3999. if (relative) this.offset += 2;
  4000. return value;
  4001. };
  4002. /**
  4003. * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
  4004. * @function
  4005. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
  4006. * @returns {number} Value read
  4007. * @throws {TypeError} If `offset` is not a valid number
  4008. * @throws {RangeError} If `offset` is out of bounds
  4009. * @expose
  4010. */
  4011. ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
  4012. // types/ints/int32
  4013. /**
  4014. * Writes a 32bit signed integer.
  4015. * @param {number} value Value to write
  4016. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4017. * @expose
  4018. */
  4019. ByteBufferPrototype.writeInt32 = function(value, offset) {
  4020. var relative = typeof offset === 'undefined';
  4021. if (relative) offset = this.offset;
  4022. if (!this.noAssert) {
  4023. if (typeof value !== 'number' || value % 1 !== 0)
  4024. throw TypeError("Illegal value: "+value+" (not an integer)");
  4025. value |= 0;
  4026. if (typeof offset !== 'number' || offset % 1 !== 0)
  4027. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4028. offset >>>= 0;
  4029. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4030. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4031. }
  4032. offset += 4;
  4033. var capacity4 = this.buffer.byteLength;
  4034. if (offset > capacity4)
  4035. this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
  4036. offset -= 4;
  4037. if (this.littleEndian) {
  4038. this.view[offset+3] = (value >>> 24) & 0xFF;
  4039. this.view[offset+2] = (value >>> 16) & 0xFF;
  4040. this.view[offset+1] = (value >>> 8) & 0xFF;
  4041. this.view[offset ] = value & 0xFF;
  4042. } else {
  4043. this.view[offset ] = (value >>> 24) & 0xFF;
  4044. this.view[offset+1] = (value >>> 16) & 0xFF;
  4045. this.view[offset+2] = (value >>> 8) & 0xFF;
  4046. this.view[offset+3] = value & 0xFF;
  4047. }
  4048. if (relative) this.offset += 4;
  4049. return this;
  4050. };
  4051. /**
  4052. * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
  4053. * @param {number} value Value to write
  4054. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4055. * @expose
  4056. */
  4057. ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
  4058. /**
  4059. * Reads a 32bit signed integer.
  4060. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4061. * @returns {number} Value read
  4062. * @expose
  4063. */
  4064. ByteBufferPrototype.readInt32 = function(offset) {
  4065. var relative = typeof offset === 'undefined';
  4066. if (relative) offset = this.offset;
  4067. if (!this.noAssert) {
  4068. if (typeof offset !== 'number' || offset % 1 !== 0)
  4069. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4070. offset >>>= 0;
  4071. if (offset < 0 || offset + 4 > this.buffer.byteLength)
  4072. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
  4073. }
  4074. var value = 0;
  4075. if (this.littleEndian) {
  4076. value = this.view[offset+2] << 16;
  4077. value |= this.view[offset+1] << 8;
  4078. value |= this.view[offset ];
  4079. value += this.view[offset+3] << 24 >>> 0;
  4080. } else {
  4081. value = this.view[offset+1] << 16;
  4082. value |= this.view[offset+2] << 8;
  4083. value |= this.view[offset+3];
  4084. value += this.view[offset ] << 24 >>> 0;
  4085. }
  4086. value |= 0; // Cast to signed
  4087. if (relative) this.offset += 4;
  4088. return value;
  4089. };
  4090. /**
  4091. * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
  4092. * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
  4093. * @returns {number} Value read
  4094. * @expose
  4095. */
  4096. ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
  4097. /**
  4098. * Writes a 32bit unsigned integer.
  4099. * @param {number} value Value to write
  4100. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4101. * @expose
  4102. */
  4103. ByteBufferPrototype.writeUint32 = function(value, offset) {
  4104. var relative = typeof offset === 'undefined';
  4105. if (relative) offset = this.offset;
  4106. if (!this.noAssert) {
  4107. if (typeof value !== 'number' || value % 1 !== 0)
  4108. throw TypeError("Illegal value: "+value+" (not an integer)");
  4109. value >>>= 0;
  4110. if (typeof offset !== 'number' || offset % 1 !== 0)
  4111. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4112. offset >>>= 0;
  4113. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4114. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4115. }
  4116. offset += 4;
  4117. var capacity5 = this.buffer.byteLength;
  4118. if (offset > capacity5)
  4119. this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
  4120. offset -= 4;
  4121. if (this.littleEndian) {
  4122. this.view[offset+3] = (value >>> 24) & 0xFF;
  4123. this.view[offset+2] = (value >>> 16) & 0xFF;
  4124. this.view[offset+1] = (value >>> 8) & 0xFF;
  4125. this.view[offset ] = value & 0xFF;
  4126. } else {
  4127. this.view[offset ] = (value >>> 24) & 0xFF;
  4128. this.view[offset+1] = (value >>> 16) & 0xFF;
  4129. this.view[offset+2] = (value >>> 8) & 0xFF;
  4130. this.view[offset+3] = value & 0xFF;
  4131. }
  4132. if (relative) this.offset += 4;
  4133. return this;
  4134. };
  4135. /**
  4136. * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
  4137. * @function
  4138. * @param {number} value Value to write
  4139. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4140. * @expose
  4141. */
  4142. ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
  4143. /**
  4144. * Reads a 32bit unsigned integer.
  4145. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4146. * @returns {number} Value read
  4147. * @expose
  4148. */
  4149. ByteBufferPrototype.readUint32 = function(offset) {
  4150. var relative = typeof offset === 'undefined';
  4151. if (relative) offset = this.offset;
  4152. if (!this.noAssert) {
  4153. if (typeof offset !== 'number' || offset % 1 !== 0)
  4154. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4155. offset >>>= 0;
  4156. if (offset < 0 || offset + 4 > this.buffer.byteLength)
  4157. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
  4158. }
  4159. var value = 0;
  4160. if (this.littleEndian) {
  4161. value = this.view[offset+2] << 16;
  4162. value |= this.view[offset+1] << 8;
  4163. value |= this.view[offset ];
  4164. value += this.view[offset+3] << 24 >>> 0;
  4165. } else {
  4166. value = this.view[offset+1] << 16;
  4167. value |= this.view[offset+2] << 8;
  4168. value |= this.view[offset+3];
  4169. value += this.view[offset ] << 24 >>> 0;
  4170. }
  4171. if (relative) this.offset += 4;
  4172. return value;
  4173. };
  4174. /**
  4175. * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
  4176. * @function
  4177. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4178. * @returns {number} Value read
  4179. * @expose
  4180. */
  4181. ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
  4182. // types/ints/int64
  4183. if (Long) {
  4184. /**
  4185. * Writes a 64bit signed integer.
  4186. * @param {number|!Long} value Value to write
  4187. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4188. * @returns {!ByteBuffer} this
  4189. * @expose
  4190. */
  4191. ByteBufferPrototype.writeInt64 = function(value, offset) {
  4192. var relative = typeof offset === 'undefined';
  4193. if (relative) offset = this.offset;
  4194. if (!this.noAssert) {
  4195. if (typeof value === 'number')
  4196. value = Long.fromNumber(value);
  4197. else if (typeof value === 'string')
  4198. value = Long.fromString(value);
  4199. else if (!(value && value instanceof Long))
  4200. throw TypeError("Illegal value: "+value+" (not an integer or Long)");
  4201. if (typeof offset !== 'number' || offset % 1 !== 0)
  4202. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4203. offset >>>= 0;
  4204. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4205. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4206. }
  4207. if (typeof value === 'number')
  4208. value = Long.fromNumber(value);
  4209. else if (typeof value === 'string')
  4210. value = Long.fromString(value);
  4211. offset += 8;
  4212. var capacity6 = this.buffer.byteLength;
  4213. if (offset > capacity6)
  4214. this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
  4215. offset -= 8;
  4216. var lo = value.low,
  4217. hi = value.high;
  4218. if (this.littleEndian) {
  4219. this.view[offset+3] = (lo >>> 24) & 0xFF;
  4220. this.view[offset+2] = (lo >>> 16) & 0xFF;
  4221. this.view[offset+1] = (lo >>> 8) & 0xFF;
  4222. this.view[offset ] = lo & 0xFF;
  4223. offset += 4;
  4224. this.view[offset+3] = (hi >>> 24) & 0xFF;
  4225. this.view[offset+2] = (hi >>> 16) & 0xFF;
  4226. this.view[offset+1] = (hi >>> 8) & 0xFF;
  4227. this.view[offset ] = hi & 0xFF;
  4228. } else {
  4229. this.view[offset ] = (hi >>> 24) & 0xFF;
  4230. this.view[offset+1] = (hi >>> 16) & 0xFF;
  4231. this.view[offset+2] = (hi >>> 8) & 0xFF;
  4232. this.view[offset+3] = hi & 0xFF;
  4233. offset += 4;
  4234. this.view[offset ] = (lo >>> 24) & 0xFF;
  4235. this.view[offset+1] = (lo >>> 16) & 0xFF;
  4236. this.view[offset+2] = (lo >>> 8) & 0xFF;
  4237. this.view[offset+3] = lo & 0xFF;
  4238. }
  4239. if (relative) this.offset += 8;
  4240. return this;
  4241. };
  4242. /**
  4243. * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
  4244. * @param {number|!Long} value Value to write
  4245. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4246. * @returns {!ByteBuffer} this
  4247. * @expose
  4248. */
  4249. ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
  4250. /**
  4251. * Reads a 64bit signed integer.
  4252. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4253. * @returns {!Long}
  4254. * @expose
  4255. */
  4256. ByteBufferPrototype.readInt64 = function(offset) {
  4257. var relative = typeof offset === 'undefined';
  4258. if (relative) offset = this.offset;
  4259. if (!this.noAssert) {
  4260. if (typeof offset !== 'number' || offset % 1 !== 0)
  4261. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4262. offset >>>= 0;
  4263. if (offset < 0 || offset + 8 > this.buffer.byteLength)
  4264. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
  4265. }
  4266. var lo = 0,
  4267. hi = 0;
  4268. if (this.littleEndian) {
  4269. lo = this.view[offset+2] << 16;
  4270. lo |= this.view[offset+1] << 8;
  4271. lo |= this.view[offset ];
  4272. lo += this.view[offset+3] << 24 >>> 0;
  4273. offset += 4;
  4274. hi = this.view[offset+2] << 16;
  4275. hi |= this.view[offset+1] << 8;
  4276. hi |= this.view[offset ];
  4277. hi += this.view[offset+3] << 24 >>> 0;
  4278. } else {
  4279. hi = this.view[offset+1] << 16;
  4280. hi |= this.view[offset+2] << 8;
  4281. hi |= this.view[offset+3];
  4282. hi += this.view[offset ] << 24 >>> 0;
  4283. offset += 4;
  4284. lo = this.view[offset+1] << 16;
  4285. lo |= this.view[offset+2] << 8;
  4286. lo |= this.view[offset+3];
  4287. lo += this.view[offset ] << 24 >>> 0;
  4288. }
  4289. var value = new Long(lo, hi, false);
  4290. if (relative) this.offset += 8;
  4291. return value;
  4292. };
  4293. /**
  4294. * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
  4295. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4296. * @returns {!Long}
  4297. * @expose
  4298. */
  4299. ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
  4300. /**
  4301. * Writes a 64bit unsigned integer.
  4302. * @param {number|!Long} value Value to write
  4303. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4304. * @returns {!ByteBuffer} this
  4305. * @expose
  4306. */
  4307. ByteBufferPrototype.writeUint64 = function(value, offset) {
  4308. var relative = typeof offset === 'undefined';
  4309. if (relative) offset = this.offset;
  4310. if (!this.noAssert) {
  4311. if (typeof value === 'number')
  4312. value = Long.fromNumber(value);
  4313. else if (typeof value === 'string')
  4314. value = Long.fromString(value);
  4315. else if (!(value && value instanceof Long))
  4316. throw TypeError("Illegal value: "+value+" (not an integer or Long)");
  4317. if (typeof offset !== 'number' || offset % 1 !== 0)
  4318. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4319. offset >>>= 0;
  4320. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4321. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4322. }
  4323. if (typeof value === 'number')
  4324. value = Long.fromNumber(value);
  4325. else if (typeof value === 'string')
  4326. value = Long.fromString(value);
  4327. offset += 8;
  4328. var capacity7 = this.buffer.byteLength;
  4329. if (offset > capacity7)
  4330. this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
  4331. offset -= 8;
  4332. var lo = value.low,
  4333. hi = value.high;
  4334. if (this.littleEndian) {
  4335. this.view[offset+3] = (lo >>> 24) & 0xFF;
  4336. this.view[offset+2] = (lo >>> 16) & 0xFF;
  4337. this.view[offset+1] = (lo >>> 8) & 0xFF;
  4338. this.view[offset ] = lo & 0xFF;
  4339. offset += 4;
  4340. this.view[offset+3] = (hi >>> 24) & 0xFF;
  4341. this.view[offset+2] = (hi >>> 16) & 0xFF;
  4342. this.view[offset+1] = (hi >>> 8) & 0xFF;
  4343. this.view[offset ] = hi & 0xFF;
  4344. } else {
  4345. this.view[offset ] = (hi >>> 24) & 0xFF;
  4346. this.view[offset+1] = (hi >>> 16) & 0xFF;
  4347. this.view[offset+2] = (hi >>> 8) & 0xFF;
  4348. this.view[offset+3] = hi & 0xFF;
  4349. offset += 4;
  4350. this.view[offset ] = (lo >>> 24) & 0xFF;
  4351. this.view[offset+1] = (lo >>> 16) & 0xFF;
  4352. this.view[offset+2] = (lo >>> 8) & 0xFF;
  4353. this.view[offset+3] = lo & 0xFF;
  4354. }
  4355. if (relative) this.offset += 8;
  4356. return this;
  4357. };
  4358. /**
  4359. * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
  4360. * @function
  4361. * @param {number|!Long} value Value to write
  4362. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4363. * @returns {!ByteBuffer} this
  4364. * @expose
  4365. */
  4366. ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
  4367. /**
  4368. * Reads a 64bit unsigned integer.
  4369. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4370. * @returns {!Long}
  4371. * @expose
  4372. */
  4373. ByteBufferPrototype.readUint64 = function(offset) {
  4374. var relative = typeof offset === 'undefined';
  4375. if (relative) offset = this.offset;
  4376. if (!this.noAssert) {
  4377. if (typeof offset !== 'number' || offset % 1 !== 0)
  4378. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4379. offset >>>= 0;
  4380. if (offset < 0 || offset + 8 > this.buffer.byteLength)
  4381. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
  4382. }
  4383. var lo = 0,
  4384. hi = 0;
  4385. if (this.littleEndian) {
  4386. lo = this.view[offset+2] << 16;
  4387. lo |= this.view[offset+1] << 8;
  4388. lo |= this.view[offset ];
  4389. lo += this.view[offset+3] << 24 >>> 0;
  4390. offset += 4;
  4391. hi = this.view[offset+2] << 16;
  4392. hi |= this.view[offset+1] << 8;
  4393. hi |= this.view[offset ];
  4394. hi += this.view[offset+3] << 24 >>> 0;
  4395. } else {
  4396. hi = this.view[offset+1] << 16;
  4397. hi |= this.view[offset+2] << 8;
  4398. hi |= this.view[offset+3];
  4399. hi += this.view[offset ] << 24 >>> 0;
  4400. offset += 4;
  4401. lo = this.view[offset+1] << 16;
  4402. lo |= this.view[offset+2] << 8;
  4403. lo |= this.view[offset+3];
  4404. lo += this.view[offset ] << 24 >>> 0;
  4405. }
  4406. var value = new Long(lo, hi, true);
  4407. if (relative) this.offset += 8;
  4408. return value;
  4409. };
  4410. /**
  4411. * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
  4412. * @function
  4413. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4414. * @returns {!Long}
  4415. * @expose
  4416. */
  4417. ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
  4418. } // Long
  4419. // types/floats/float32
  4420. /*
  4421. ieee754 - https://github.com/feross/ieee754
  4422. The MIT License (MIT)
  4423. Copyright (c) Feross Aboukhadijeh
  4424. Permission is hereby granted, free of charge, to any person obtaining a copy
  4425. of this software and associated documentation files (the "Software"), to deal
  4426. in the Software without restriction, including without limitation the rights
  4427. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  4428. copies of the Software, and to permit persons to whom the Software is
  4429. furnished to do so, subject to the following conditions:
  4430. The above copyright notice and this permission notice shall be included in
  4431. all copies or substantial portions of the Software.
  4432. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4433. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4434. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4435. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4436. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4437. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4438. THE SOFTWARE.
  4439. */
  4440. /**
  4441. * Reads an IEEE754 float from a byte array.
  4442. * @param {!Array} buffer
  4443. * @param {number} offset
  4444. * @param {boolean} isLE
  4445. * @param {number} mLen
  4446. * @param {number} nBytes
  4447. * @returns {number}
  4448. * @inner
  4449. */
  4450. function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
  4451. var e, m,
  4452. eLen = nBytes * 8 - mLen - 1,
  4453. eMax = (1 << eLen) - 1,
  4454. eBias = eMax >> 1,
  4455. nBits = -7,
  4456. i = isLE ? (nBytes - 1) : 0,
  4457. d = isLE ? -1 : 1,
  4458. s = buffer[offset + i];
  4459. i += d;
  4460. e = s & ((1 << (-nBits)) - 1);
  4461. s >>= (-nBits);
  4462. nBits += eLen;
  4463. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  4464. m = e & ((1 << (-nBits)) - 1);
  4465. e >>= (-nBits);
  4466. nBits += mLen;
  4467. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  4468. if (e === 0) {
  4469. e = 1 - eBias;
  4470. } else if (e === eMax) {
  4471. return m ? NaN : ((s ? -1 : 1) * Infinity);
  4472. } else {
  4473. m = m + Math.pow(2, mLen);
  4474. e = e - eBias;
  4475. }
  4476. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  4477. }
  4478. /**
  4479. * Writes an IEEE754 float to a byte array.
  4480. * @param {!Array} buffer
  4481. * @param {number} value
  4482. * @param {number} offset
  4483. * @param {boolean} isLE
  4484. * @param {number} mLen
  4485. * @param {number} nBytes
  4486. * @inner
  4487. */
  4488. function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
  4489. var e, m, c,
  4490. eLen = nBytes * 8 - mLen - 1,
  4491. eMax = (1 << eLen) - 1,
  4492. eBias = eMax >> 1,
  4493. rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
  4494. i = isLE ? 0 : (nBytes - 1),
  4495. d = isLE ? 1 : -1,
  4496. s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  4497. value = Math.abs(value);
  4498. if (isNaN(value) || value === Infinity) {
  4499. m = isNaN(value) ? 1 : 0;
  4500. e = eMax;
  4501. } else {
  4502. e = Math.floor(Math.log(value) / Math.LN2);
  4503. if (value * (c = Math.pow(2, -e)) < 1) {
  4504. e--;
  4505. c *= 2;
  4506. }
  4507. if (e + eBias >= 1) {
  4508. value += rt / c;
  4509. } else {
  4510. value += rt * Math.pow(2, 1 - eBias);
  4511. }
  4512. if (value * c >= 2) {
  4513. e++;
  4514. c /= 2;
  4515. }
  4516. if (e + eBias >= eMax) {
  4517. m = 0;
  4518. e = eMax;
  4519. } else if (e + eBias >= 1) {
  4520. m = (value * c - 1) * Math.pow(2, mLen);
  4521. e = e + eBias;
  4522. } else {
  4523. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  4524. e = 0;
  4525. }
  4526. }
  4527. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  4528. e = (e << mLen) | m;
  4529. eLen += mLen;
  4530. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  4531. buffer[offset + i - d] |= s * 128;
  4532. }
  4533. /**
  4534. * Writes a 32bit float.
  4535. * @param {number} value Value to write
  4536. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4537. * @returns {!ByteBuffer} this
  4538. * @expose
  4539. */
  4540. ByteBufferPrototype.writeFloat32 = function(value, offset) {
  4541. var relative = typeof offset === 'undefined';
  4542. if (relative) offset = this.offset;
  4543. if (!this.noAssert) {
  4544. if (typeof value !== 'number')
  4545. throw TypeError("Illegal value: "+value+" (not a number)");
  4546. if (typeof offset !== 'number' || offset % 1 !== 0)
  4547. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4548. offset >>>= 0;
  4549. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4550. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4551. }
  4552. offset += 4;
  4553. var capacity8 = this.buffer.byteLength;
  4554. if (offset > capacity8)
  4555. this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
  4556. offset -= 4;
  4557. ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
  4558. if (relative) this.offset += 4;
  4559. return this;
  4560. };
  4561. /**
  4562. * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
  4563. * @function
  4564. * @param {number} value Value to write
  4565. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4566. * @returns {!ByteBuffer} this
  4567. * @expose
  4568. */
  4569. ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
  4570. /**
  4571. * Reads a 32bit float.
  4572. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4573. * @returns {number}
  4574. * @expose
  4575. */
  4576. ByteBufferPrototype.readFloat32 = function(offset) {
  4577. var relative = typeof offset === 'undefined';
  4578. if (relative) offset = this.offset;
  4579. if (!this.noAssert) {
  4580. if (typeof offset !== 'number' || offset % 1 !== 0)
  4581. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4582. offset >>>= 0;
  4583. if (offset < 0 || offset + 4 > this.buffer.byteLength)
  4584. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
  4585. }
  4586. var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
  4587. if (relative) this.offset += 4;
  4588. return value;
  4589. };
  4590. /**
  4591. * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
  4592. * @function
  4593. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
  4594. * @returns {number}
  4595. * @expose
  4596. */
  4597. ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
  4598. // types/floats/float64
  4599. /**
  4600. * Writes a 64bit float.
  4601. * @param {number} value Value to write
  4602. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4603. * @returns {!ByteBuffer} this
  4604. * @expose
  4605. */
  4606. ByteBufferPrototype.writeFloat64 = function(value, offset) {
  4607. var relative = typeof offset === 'undefined';
  4608. if (relative) offset = this.offset;
  4609. if (!this.noAssert) {
  4610. if (typeof value !== 'number')
  4611. throw TypeError("Illegal value: "+value+" (not a number)");
  4612. if (typeof offset !== 'number' || offset % 1 !== 0)
  4613. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4614. offset >>>= 0;
  4615. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4616. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4617. }
  4618. offset += 8;
  4619. var capacity9 = this.buffer.byteLength;
  4620. if (offset > capacity9)
  4621. this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
  4622. offset -= 8;
  4623. ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
  4624. if (relative) this.offset += 8;
  4625. return this;
  4626. };
  4627. /**
  4628. * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
  4629. * @function
  4630. * @param {number} value Value to write
  4631. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4632. * @returns {!ByteBuffer} this
  4633. * @expose
  4634. */
  4635. ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
  4636. /**
  4637. * Reads a 64bit float.
  4638. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4639. * @returns {number}
  4640. * @expose
  4641. */
  4642. ByteBufferPrototype.readFloat64 = function(offset) {
  4643. var relative = typeof offset === 'undefined';
  4644. if (relative) offset = this.offset;
  4645. if (!this.noAssert) {
  4646. if (typeof offset !== 'number' || offset % 1 !== 0)
  4647. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4648. offset >>>= 0;
  4649. if (offset < 0 || offset + 8 > this.buffer.byteLength)
  4650. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
  4651. }
  4652. var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
  4653. if (relative) this.offset += 8;
  4654. return value;
  4655. };
  4656. /**
  4657. * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
  4658. * @function
  4659. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
  4660. * @returns {number}
  4661. * @expose
  4662. */
  4663. ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
  4664. // types/varints/varint32
  4665. /**
  4666. * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
  4667. * @type {number}
  4668. * @const
  4669. * @expose
  4670. */
  4671. ByteBuffer.MAX_VARINT32_BYTES = 5;
  4672. /**
  4673. * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
  4674. * @param {number} value Value to encode
  4675. * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
  4676. * @expose
  4677. */
  4678. ByteBuffer.calculateVarint32 = function(value) {
  4679. // ref: src/google/protobuf/io/coded_stream.cc
  4680. value = value >>> 0;
  4681. if (value < 1 << 7 ) return 1;
  4682. else if (value < 1 << 14) return 2;
  4683. else if (value < 1 << 21) return 3;
  4684. else if (value < 1 << 28) return 4;
  4685. else return 5;
  4686. };
  4687. /**
  4688. * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
  4689. * @param {number} n Signed 32bit integer
  4690. * @returns {number} Unsigned zigzag encoded 32bit integer
  4691. * @expose
  4692. */
  4693. ByteBuffer.zigZagEncode32 = function(n) {
  4694. return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
  4695. };
  4696. /**
  4697. * Decodes a zigzag encoded signed 32bit integer.
  4698. * @param {number} n Unsigned zigzag encoded 32bit integer
  4699. * @returns {number} Signed 32bit integer
  4700. * @expose
  4701. */
  4702. ByteBuffer.zigZagDecode32 = function(n) {
  4703. return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
  4704. };
  4705. /**
  4706. * Writes a 32bit base 128 variable-length integer.
  4707. * @param {number} value Value to write
  4708. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4709. * written if omitted.
  4710. * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
  4711. * @expose
  4712. */
  4713. ByteBufferPrototype.writeVarint32 = function(value, offset) {
  4714. var relative = typeof offset === 'undefined';
  4715. if (relative) offset = this.offset;
  4716. if (!this.noAssert) {
  4717. if (typeof value !== 'number' || value % 1 !== 0)
  4718. throw TypeError("Illegal value: "+value+" (not an integer)");
  4719. value |= 0;
  4720. if (typeof offset !== 'number' || offset % 1 !== 0)
  4721. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4722. offset >>>= 0;
  4723. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4724. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4725. }
  4726. var size = ByteBuffer.calculateVarint32(value),
  4727. b;
  4728. offset += size;
  4729. var capacity10 = this.buffer.byteLength;
  4730. if (offset > capacity10)
  4731. this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
  4732. offset -= size;
  4733. value >>>= 0;
  4734. while (value >= 0x80) {
  4735. b = (value & 0x7f) | 0x80;
  4736. this.view[offset++] = b;
  4737. value >>>= 7;
  4738. }
  4739. this.view[offset++] = value;
  4740. if (relative) {
  4741. this.offset = offset;
  4742. return this;
  4743. }
  4744. return size;
  4745. };
  4746. /**
  4747. * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
  4748. * @param {number} value Value to write
  4749. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4750. * written if omitted.
  4751. * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
  4752. * @expose
  4753. */
  4754. ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
  4755. return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
  4756. };
  4757. /**
  4758. * Reads a 32bit base 128 variable-length integer.
  4759. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4760. * written if omitted.
  4761. * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
  4762. * and the actual number of bytes read.
  4763. * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
  4764. * to fully decode the varint.
  4765. * @expose
  4766. */
  4767. ByteBufferPrototype.readVarint32 = function(offset) {
  4768. var relative = typeof offset === 'undefined';
  4769. if (relative) offset = this.offset;
  4770. if (!this.noAssert) {
  4771. if (typeof offset !== 'number' || offset % 1 !== 0)
  4772. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4773. offset >>>= 0;
  4774. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  4775. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  4776. }
  4777. var c = 0,
  4778. value = 0 >>> 0,
  4779. b;
  4780. do {
  4781. if (!this.noAssert && offset > this.limit) {
  4782. var err = Error("Truncated");
  4783. err['truncated'] = true;
  4784. throw err;
  4785. }
  4786. b = this.view[offset++];
  4787. if (c < 5)
  4788. value |= (b & 0x7f) << (7*c);
  4789. ++c;
  4790. } while ((b & 0x80) !== 0);
  4791. value |= 0;
  4792. if (relative) {
  4793. this.offset = offset;
  4794. return value;
  4795. }
  4796. return {
  4797. "value": value,
  4798. "length": c
  4799. };
  4800. };
  4801. /**
  4802. * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
  4803. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4804. * written if omitted.
  4805. * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
  4806. * and the actual number of bytes read.
  4807. * @throws {Error} If it's not a valid varint
  4808. * @expose
  4809. */
  4810. ByteBufferPrototype.readVarint32ZigZag = function(offset) {
  4811. var val = this.readVarint32(offset);
  4812. if (typeof val === 'object')
  4813. val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
  4814. else
  4815. val = ByteBuffer.zigZagDecode32(val);
  4816. return val;
  4817. };
  4818. // types/varints/varint64
  4819. if (Long) {
  4820. /**
  4821. * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
  4822. * @type {number}
  4823. * @const
  4824. * @expose
  4825. */
  4826. ByteBuffer.MAX_VARINT64_BYTES = 10;
  4827. /**
  4828. * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
  4829. * @param {number|!Long} value Value to encode
  4830. * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
  4831. * @expose
  4832. */
  4833. ByteBuffer.calculateVarint64 = function(value) {
  4834. if (typeof value === 'number')
  4835. value = Long.fromNumber(value);
  4836. else if (typeof value === 'string')
  4837. value = Long.fromString(value);
  4838. // ref: src/google/protobuf/io/coded_stream.cc
  4839. var part0 = value.toInt() >>> 0,
  4840. part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
  4841. part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
  4842. if (part2 == 0) {
  4843. if (part1 == 0) {
  4844. if (part0 < 1 << 14)
  4845. return part0 < 1 << 7 ? 1 : 2;
  4846. else
  4847. return part0 < 1 << 21 ? 3 : 4;
  4848. } else {
  4849. if (part1 < 1 << 14)
  4850. return part1 < 1 << 7 ? 5 : 6;
  4851. else
  4852. return part1 < 1 << 21 ? 7 : 8;
  4853. }
  4854. } else
  4855. return part2 < 1 << 7 ? 9 : 10;
  4856. };
  4857. /**
  4858. * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
  4859. * @param {number|!Long} value Signed long
  4860. * @returns {!Long} Unsigned zigzag encoded long
  4861. * @expose
  4862. */
  4863. ByteBuffer.zigZagEncode64 = function(value) {
  4864. if (typeof value === 'number')
  4865. value = Long.fromNumber(value, false);
  4866. else if (typeof value === 'string')
  4867. value = Long.fromString(value, false);
  4868. else if (value.unsigned !== false) value = value.toSigned();
  4869. // ref: src/google/protobuf/wire_format_lite.h
  4870. return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
  4871. };
  4872. /**
  4873. * Decodes a zigzag encoded signed 64bit integer.
  4874. * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
  4875. * @returns {!Long} Signed long
  4876. * @expose
  4877. */
  4878. ByteBuffer.zigZagDecode64 = function(value) {
  4879. if (typeof value === 'number')
  4880. value = Long.fromNumber(value, false);
  4881. else if (typeof value === 'string')
  4882. value = Long.fromString(value, false);
  4883. else if (value.unsigned !== false) value = value.toSigned();
  4884. // ref: src/google/protobuf/wire_format_lite.h
  4885. return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
  4886. };
  4887. /**
  4888. * Writes a 64bit base 128 variable-length integer.
  4889. * @param {number|Long} value Value to write
  4890. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4891. * written if omitted.
  4892. * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
  4893. * @expose
  4894. */
  4895. ByteBufferPrototype.writeVarint64 = function(value, offset) {
  4896. var relative = typeof offset === 'undefined';
  4897. if (relative) offset = this.offset;
  4898. if (!this.noAssert) {
  4899. if (typeof value === 'number')
  4900. value = Long.fromNumber(value);
  4901. else if (typeof value === 'string')
  4902. value = Long.fromString(value);
  4903. else if (!(value && value instanceof Long))
  4904. throw TypeError("Illegal value: "+value+" (not an integer or Long)");
  4905. if (typeof offset !== 'number' || offset % 1 !== 0)
  4906. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4907. offset >>>= 0;
  4908. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  4909. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  4910. }
  4911. if (typeof value === 'number')
  4912. value = Long.fromNumber(value, false);
  4913. else if (typeof value === 'string')
  4914. value = Long.fromString(value, false);
  4915. else if (value.unsigned !== false) value = value.toSigned();
  4916. var size = ByteBuffer.calculateVarint64(value),
  4917. part0 = value.toInt() >>> 0,
  4918. part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
  4919. part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
  4920. offset += size;
  4921. var capacity11 = this.buffer.byteLength;
  4922. if (offset > capacity11)
  4923. this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
  4924. offset -= size;
  4925. switch (size) {
  4926. case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
  4927. case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
  4928. case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
  4929. case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
  4930. case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
  4931. case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
  4932. case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
  4933. case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
  4934. case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
  4935. case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
  4936. }
  4937. if (relative) {
  4938. this.offset += size;
  4939. return this;
  4940. } else {
  4941. return size;
  4942. }
  4943. };
  4944. /**
  4945. * Writes a zig-zag encoded 64bit base 128 variable-length integer.
  4946. * @param {number|Long} value Value to write
  4947. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4948. * written if omitted.
  4949. * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
  4950. * @expose
  4951. */
  4952. ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
  4953. return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
  4954. };
  4955. /**
  4956. * Reads a 64bit base 128 variable-length integer. Requires Long.js.
  4957. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  4958. * read if omitted.
  4959. * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
  4960. * the actual number of bytes read.
  4961. * @throws {Error} If it's not a valid varint
  4962. * @expose
  4963. */
  4964. ByteBufferPrototype.readVarint64 = function(offset) {
  4965. var relative = typeof offset === 'undefined';
  4966. if (relative) offset = this.offset;
  4967. if (!this.noAssert) {
  4968. if (typeof offset !== 'number' || offset % 1 !== 0)
  4969. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  4970. offset >>>= 0;
  4971. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  4972. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  4973. }
  4974. // ref: src/google/protobuf/io/coded_stream.cc
  4975. var start = offset,
  4976. part0 = 0,
  4977. part1 = 0,
  4978. part2 = 0,
  4979. b = 0;
  4980. b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
  4981. b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4982. b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4983. b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4984. b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4985. b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4986. b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4987. b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4988. b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4989. b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
  4990. throw Error("Buffer overrun"); }}}}}}}}}}
  4991. var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
  4992. if (relative) {
  4993. this.offset = offset;
  4994. return value;
  4995. } else {
  4996. return {
  4997. 'value': value,
  4998. 'length': offset-start
  4999. };
  5000. }
  5001. };
  5002. /**
  5003. * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
  5004. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5005. * read if omitted.
  5006. * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
  5007. * the actual number of bytes read.
  5008. * @throws {Error} If it's not a valid varint
  5009. * @expose
  5010. */
  5011. ByteBufferPrototype.readVarint64ZigZag = function(offset) {
  5012. var val = this.readVarint64(offset);
  5013. if (val && val['value'] instanceof Long)
  5014. val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
  5015. else
  5016. val = ByteBuffer.zigZagDecode64(val);
  5017. return val;
  5018. };
  5019. } // Long
  5020. // types/strings/cstring
  5021. /**
  5022. * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
  5023. * characters itself.
  5024. * @param {string} str String to write
  5025. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5026. * contained in `str` + 1 if omitted.
  5027. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
  5028. * @expose
  5029. */
  5030. ByteBufferPrototype.writeCString = function(str, offset) {
  5031. var relative = typeof offset === 'undefined';
  5032. if (relative) offset = this.offset;
  5033. var i,
  5034. k = str.length;
  5035. if (!this.noAssert) {
  5036. if (typeof str !== 'string')
  5037. throw TypeError("Illegal str: Not a string");
  5038. for (i=0; i<k; ++i) {
  5039. if (str.charCodeAt(i) === 0)
  5040. throw RangeError("Illegal str: Contains NULL-characters");
  5041. }
  5042. if (typeof offset !== 'number' || offset % 1 !== 0)
  5043. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5044. offset >>>= 0;
  5045. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5046. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5047. }
  5048. // UTF8 strings do not contain zero bytes in between except for the zero character, so:
  5049. k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
  5050. offset += k+1;
  5051. var capacity12 = this.buffer.byteLength;
  5052. if (offset > capacity12)
  5053. this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
  5054. offset -= k+1;
  5055. utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
  5056. this.view[offset++] = b;
  5057. }.bind(this));
  5058. this.view[offset++] = 0;
  5059. if (relative) {
  5060. this.offset = offset;
  5061. return this;
  5062. }
  5063. return k;
  5064. };
  5065. /**
  5066. * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
  5067. * itself.
  5068. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5069. * read if omitted.
  5070. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
  5071. * read and the actual number of bytes read.
  5072. * @expose
  5073. */
  5074. ByteBufferPrototype.readCString = function(offset) {
  5075. var relative = typeof offset === 'undefined';
  5076. if (relative) offset = this.offset;
  5077. if (!this.noAssert) {
  5078. if (typeof offset !== 'number' || offset % 1 !== 0)
  5079. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5080. offset >>>= 0;
  5081. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  5082. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  5083. }
  5084. var start = offset;
  5085. // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
  5086. var sd, b = -1;
  5087. utfx.decodeUTF8toUTF16(function() {
  5088. if (b === 0) return null;
  5089. if (offset >= this.limit)
  5090. throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
  5091. b = this.view[offset++];
  5092. return b === 0 ? null : b;
  5093. }.bind(this), sd = stringDestination(), true);
  5094. if (relative) {
  5095. this.offset = offset;
  5096. return sd();
  5097. } else {
  5098. return {
  5099. "string": sd(),
  5100. "length": offset - start
  5101. };
  5102. }
  5103. };
  5104. // types/strings/istring
  5105. /**
  5106. * Writes a length as uint32 prefixed UTF8 encoded string.
  5107. * @param {string} str String to write
  5108. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5109. * written if omitted.
  5110. * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
  5111. * @expose
  5112. * @see ByteBuffer#writeVarint32
  5113. */
  5114. ByteBufferPrototype.writeIString = function(str, offset) {
  5115. var relative = typeof offset === 'undefined';
  5116. if (relative) offset = this.offset;
  5117. if (!this.noAssert) {
  5118. if (typeof str !== 'string')
  5119. throw TypeError("Illegal str: Not a string");
  5120. if (typeof offset !== 'number' || offset % 1 !== 0)
  5121. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5122. offset >>>= 0;
  5123. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5124. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5125. }
  5126. var start = offset,
  5127. k;
  5128. k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
  5129. offset += 4+k;
  5130. var capacity13 = this.buffer.byteLength;
  5131. if (offset > capacity13)
  5132. this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
  5133. offset -= 4+k;
  5134. if (this.littleEndian) {
  5135. this.view[offset+3] = (k >>> 24) & 0xFF;
  5136. this.view[offset+2] = (k >>> 16) & 0xFF;
  5137. this.view[offset+1] = (k >>> 8) & 0xFF;
  5138. this.view[offset ] = k & 0xFF;
  5139. } else {
  5140. this.view[offset ] = (k >>> 24) & 0xFF;
  5141. this.view[offset+1] = (k >>> 16) & 0xFF;
  5142. this.view[offset+2] = (k >>> 8) & 0xFF;
  5143. this.view[offset+3] = k & 0xFF;
  5144. }
  5145. offset += 4;
  5146. utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
  5147. this.view[offset++] = b;
  5148. }.bind(this));
  5149. if (offset !== start + 4 + k)
  5150. throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
  5151. if (relative) {
  5152. this.offset = offset;
  5153. return this;
  5154. }
  5155. return offset - start;
  5156. };
  5157. /**
  5158. * Reads a length as uint32 prefixed UTF8 encoded string.
  5159. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5160. * read if omitted.
  5161. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
  5162. * read and the actual number of bytes read.
  5163. * @expose
  5164. * @see ByteBuffer#readVarint32
  5165. */
  5166. ByteBufferPrototype.readIString = function(offset) {
  5167. var relative = typeof offset === 'undefined';
  5168. if (relative) offset = this.offset;
  5169. if (!this.noAssert) {
  5170. if (typeof offset !== 'number' || offset % 1 !== 0)
  5171. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5172. offset >>>= 0;
  5173. if (offset < 0 || offset + 4 > this.buffer.byteLength)
  5174. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
  5175. }
  5176. var start = offset;
  5177. var len = this.readUint32(offset);
  5178. var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
  5179. offset += str['length'];
  5180. if (relative) {
  5181. this.offset = offset;
  5182. return str['string'];
  5183. } else {
  5184. return {
  5185. 'string': str['string'],
  5186. 'length': offset - start
  5187. };
  5188. }
  5189. };
  5190. // types/strings/utf8string
  5191. /**
  5192. * Metrics representing number of UTF8 characters. Evaluates to `c`.
  5193. * @type {string}
  5194. * @const
  5195. * @expose
  5196. */
  5197. ByteBuffer.METRICS_CHARS = 'c';
  5198. /**
  5199. * Metrics representing number of bytes. Evaluates to `b`.
  5200. * @type {string}
  5201. * @const
  5202. * @expose
  5203. */
  5204. ByteBuffer.METRICS_BYTES = 'b';
  5205. /**
  5206. * Writes an UTF8 encoded string.
  5207. * @param {string} str String to write
  5208. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
  5209. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
  5210. * @expose
  5211. */
  5212. ByteBufferPrototype.writeUTF8String = function(str, offset) {
  5213. var relative = typeof offset === 'undefined';
  5214. if (relative) offset = this.offset;
  5215. if (!this.noAssert) {
  5216. if (typeof offset !== 'number' || offset % 1 !== 0)
  5217. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5218. offset >>>= 0;
  5219. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5220. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5221. }
  5222. var k;
  5223. var start = offset;
  5224. k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
  5225. offset += k;
  5226. var capacity14 = this.buffer.byteLength;
  5227. if (offset > capacity14)
  5228. this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
  5229. offset -= k;
  5230. utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
  5231. this.view[offset++] = b;
  5232. }.bind(this));
  5233. if (relative) {
  5234. this.offset = offset;
  5235. return this;
  5236. }
  5237. return offset - start;
  5238. };
  5239. /**
  5240. * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
  5241. * @function
  5242. * @param {string} str String to write
  5243. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
  5244. * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
  5245. * @expose
  5246. */
  5247. ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
  5248. /**
  5249. * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
  5250. * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
  5251. * @param {string} str String to calculate
  5252. * @returns {number} Number of UTF8 characters
  5253. * @expose
  5254. */
  5255. ByteBuffer.calculateUTF8Chars = function(str) {
  5256. return utfx.calculateUTF16asUTF8(stringSource(str))[0];
  5257. };
  5258. /**
  5259. * Calculates the number of UTF8 bytes of a string.
  5260. * @param {string} str String to calculate
  5261. * @returns {number} Number of UTF8 bytes
  5262. * @expose
  5263. */
  5264. ByteBuffer.calculateUTF8Bytes = function(str) {
  5265. return utfx.calculateUTF16asUTF8(stringSource(str))[1];
  5266. };
  5267. /**
  5268. * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
  5269. * @function
  5270. * @param {string} str String to calculate
  5271. * @returns {number} Number of UTF8 bytes
  5272. * @expose
  5273. */
  5274. ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
  5275. /**
  5276. * Reads an UTF8 encoded string.
  5277. * @param {number} length Number of characters or bytes to read.
  5278. * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
  5279. * {@link ByteBuffer.METRICS_CHARS}.
  5280. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5281. * read if omitted.
  5282. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
  5283. * read and the actual number of bytes read.
  5284. * @expose
  5285. */
  5286. ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
  5287. if (typeof metrics === 'number') {
  5288. offset = metrics;
  5289. metrics = undefined;
  5290. }
  5291. var relative = typeof offset === 'undefined';
  5292. if (relative) offset = this.offset;
  5293. if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
  5294. if (!this.noAssert) {
  5295. if (typeof length !== 'number' || length % 1 !== 0)
  5296. throw TypeError("Illegal length: "+length+" (not an integer)");
  5297. length |= 0;
  5298. if (typeof offset !== 'number' || offset % 1 !== 0)
  5299. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5300. offset >>>= 0;
  5301. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5302. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5303. }
  5304. var i = 0,
  5305. start = offset,
  5306. sd;
  5307. if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
  5308. sd = stringDestination();
  5309. utfx.decodeUTF8(function() {
  5310. return i < length && offset < this.limit ? this.view[offset++] : null;
  5311. }.bind(this), function(cp) {
  5312. ++i; utfx.UTF8toUTF16(cp, sd);
  5313. });
  5314. if (i !== length)
  5315. throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
  5316. if (relative) {
  5317. this.offset = offset;
  5318. return sd();
  5319. } else {
  5320. return {
  5321. "string": sd(),
  5322. "length": offset - start
  5323. };
  5324. }
  5325. } else if (metrics === ByteBuffer.METRICS_BYTES) {
  5326. if (!this.noAssert) {
  5327. if (typeof offset !== 'number' || offset % 1 !== 0)
  5328. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5329. offset >>>= 0;
  5330. if (offset < 0 || offset + length > this.buffer.byteLength)
  5331. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
  5332. }
  5333. var k = offset + length;
  5334. utfx.decodeUTF8toUTF16(function() {
  5335. return offset < k ? this.view[offset++] : null;
  5336. }.bind(this), sd = stringDestination(), this.noAssert);
  5337. if (offset !== k)
  5338. throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
  5339. if (relative) {
  5340. this.offset = offset;
  5341. return sd();
  5342. } else {
  5343. return {
  5344. 'string': sd(),
  5345. 'length': offset - start
  5346. };
  5347. }
  5348. } else
  5349. throw TypeError("Unsupported metrics: "+metrics);
  5350. };
  5351. /**
  5352. * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
  5353. * @function
  5354. * @param {number} length Number of characters or bytes to read
  5355. * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
  5356. * {@link ByteBuffer.METRICS_CHARS}.
  5357. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5358. * read if omitted.
  5359. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
  5360. * read and the actual number of bytes read.
  5361. * @expose
  5362. */
  5363. ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
  5364. // types/strings/vstring
  5365. /**
  5366. * Writes a length as varint32 prefixed UTF8 encoded string.
  5367. * @param {string} str String to write
  5368. * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5369. * written if omitted.
  5370. * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
  5371. * @expose
  5372. * @see ByteBuffer#writeVarint32
  5373. */
  5374. ByteBufferPrototype.writeVString = function(str, offset) {
  5375. var relative = typeof offset === 'undefined';
  5376. if (relative) offset = this.offset;
  5377. if (!this.noAssert) {
  5378. if (typeof str !== 'string')
  5379. throw TypeError("Illegal str: Not a string");
  5380. if (typeof offset !== 'number' || offset % 1 !== 0)
  5381. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5382. offset >>>= 0;
  5383. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5384. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5385. }
  5386. var start = offset,
  5387. k, l;
  5388. k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
  5389. l = ByteBuffer.calculateVarint32(k);
  5390. offset += l+k;
  5391. var capacity15 = this.buffer.byteLength;
  5392. if (offset > capacity15)
  5393. this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
  5394. offset -= l+k;
  5395. offset += this.writeVarint32(k, offset);
  5396. utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
  5397. this.view[offset++] = b;
  5398. }.bind(this));
  5399. if (offset !== start+k+l)
  5400. throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
  5401. if (relative) {
  5402. this.offset = offset;
  5403. return this;
  5404. }
  5405. return offset - start;
  5406. };
  5407. /**
  5408. * Reads a length as varint32 prefixed UTF8 encoded string.
  5409. * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5410. * read if omitted.
  5411. * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
  5412. * read and the actual number of bytes read.
  5413. * @expose
  5414. * @see ByteBuffer#readVarint32
  5415. */
  5416. ByteBufferPrototype.readVString = function(offset) {
  5417. var relative = typeof offset === 'undefined';
  5418. if (relative) offset = this.offset;
  5419. if (!this.noAssert) {
  5420. if (typeof offset !== 'number' || offset % 1 !== 0)
  5421. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5422. offset >>>= 0;
  5423. if (offset < 0 || offset + 1 > this.buffer.byteLength)
  5424. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
  5425. }
  5426. var start = offset;
  5427. var len = this.readVarint32(offset);
  5428. var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
  5429. offset += str['length'];
  5430. if (relative) {
  5431. this.offset = offset;
  5432. return str['string'];
  5433. } else {
  5434. return {
  5435. 'string': str['string'],
  5436. 'length': offset - start
  5437. };
  5438. }
  5439. };
  5440. /**
  5441. * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
  5442. * data's length.
  5443. * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
  5444. * will be modified according to the performed read operation.
  5445. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
  5446. * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5447. * written if omitted.
  5448. * @returns {!ByteBuffer} this
  5449. * @expose
  5450. * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
  5451. * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
  5452. */
  5453. ByteBufferPrototype.append = function(source, encoding, offset) {
  5454. if (typeof encoding === 'number' || typeof encoding !== 'string') {
  5455. offset = encoding;
  5456. encoding = undefined;
  5457. }
  5458. var relative = typeof offset === 'undefined';
  5459. if (relative) offset = this.offset;
  5460. if (!this.noAssert) {
  5461. if (typeof offset !== 'number' || offset % 1 !== 0)
  5462. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5463. offset >>>= 0;
  5464. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5465. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5466. }
  5467. if (!(source instanceof ByteBuffer))
  5468. source = ByteBuffer.wrap(source, encoding);
  5469. var length = source.limit - source.offset;
  5470. if (length <= 0) return this; // Nothing to append
  5471. offset += length;
  5472. var capacity16 = this.buffer.byteLength;
  5473. if (offset > capacity16)
  5474. this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
  5475. offset -= length;
  5476. this.view.set(source.view.subarray(source.offset, source.limit), offset);
  5477. source.offset += length;
  5478. if (relative) this.offset += length;
  5479. return this;
  5480. };
  5481. /**
  5482. * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
  5483. specified offset up to the length of this ByteBuffer's data.
  5484. * @param {!ByteBuffer} target Target ByteBuffer
  5485. * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5486. * read if omitted.
  5487. * @returns {!ByteBuffer} this
  5488. * @expose
  5489. * @see ByteBuffer#append
  5490. */
  5491. ByteBufferPrototype.appendTo = function(target, offset) {
  5492. target.append(this, offset);
  5493. return this;
  5494. };
  5495. /**
  5496. * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
  5497. * disable them if your code already makes sure that everything is valid.
  5498. * @param {boolean} assert `true` to enable assertions, otherwise `false`
  5499. * @returns {!ByteBuffer} this
  5500. * @expose
  5501. */
  5502. ByteBufferPrototype.assert = function(assert) {
  5503. this.noAssert = !assert;
  5504. return this;
  5505. };
  5506. /**
  5507. * Gets the capacity of this ByteBuffer's backing buffer.
  5508. * @returns {number} Capacity of the backing buffer
  5509. * @expose
  5510. */
  5511. ByteBufferPrototype.capacity = function() {
  5512. return this.buffer.byteLength;
  5513. };
  5514. /**
  5515. * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
  5516. * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
  5517. * @returns {!ByteBuffer} this
  5518. * @expose
  5519. */
  5520. ByteBufferPrototype.clear = function() {
  5521. this.offset = 0;
  5522. this.limit = this.buffer.byteLength;
  5523. this.markedOffset = -1;
  5524. return this;
  5525. };
  5526. /**
  5527. * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
  5528. * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
  5529. * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
  5530. * @returns {!ByteBuffer} Cloned instance
  5531. * @expose
  5532. */
  5533. ByteBufferPrototype.clone = function(copy) {
  5534. var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
  5535. if (copy) {
  5536. bb.buffer = new ArrayBuffer(this.buffer.byteLength);
  5537. bb.view = new Uint8Array(bb.buffer);
  5538. } else {
  5539. bb.buffer = this.buffer;
  5540. bb.view = this.view;
  5541. }
  5542. bb.offset = this.offset;
  5543. bb.markedOffset = this.markedOffset;
  5544. bb.limit = this.limit;
  5545. return bb;
  5546. };
  5547. /**
  5548. * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
  5549. * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
  5550. * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
  5551. * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
  5552. * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
  5553. * @returns {!ByteBuffer} this
  5554. * @expose
  5555. */
  5556. ByteBufferPrototype.compact = function(begin, end) {
  5557. if (typeof begin === 'undefined') begin = this.offset;
  5558. if (typeof end === 'undefined') end = this.limit;
  5559. if (!this.noAssert) {
  5560. if (typeof begin !== 'number' || begin % 1 !== 0)
  5561. throw TypeError("Illegal begin: Not an integer");
  5562. begin >>>= 0;
  5563. if (typeof end !== 'number' || end % 1 !== 0)
  5564. throw TypeError("Illegal end: Not an integer");
  5565. end >>>= 0;
  5566. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  5567. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  5568. }
  5569. if (begin === 0 && end === this.buffer.byteLength)
  5570. return this; // Already compacted
  5571. var len = end - begin;
  5572. if (len === 0) {
  5573. this.buffer = EMPTY_BUFFER;
  5574. this.view = null;
  5575. if (this.markedOffset >= 0) this.markedOffset -= begin;
  5576. this.offset = 0;
  5577. this.limit = 0;
  5578. return this;
  5579. }
  5580. var buffer = new ArrayBuffer(len);
  5581. var view = new Uint8Array(buffer);
  5582. view.set(this.view.subarray(begin, end));
  5583. this.buffer = buffer;
  5584. this.view = view;
  5585. if (this.markedOffset >= 0) this.markedOffset -= begin;
  5586. this.offset = 0;
  5587. this.limit = len;
  5588. return this;
  5589. };
  5590. /**
  5591. * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
  5592. * {@link ByteBuffer#limit}.
  5593. * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
  5594. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
  5595. * @returns {!ByteBuffer} Copy
  5596. * @expose
  5597. */
  5598. ByteBufferPrototype.copy = function(begin, end) {
  5599. if (typeof begin === 'undefined') begin = this.offset;
  5600. if (typeof end === 'undefined') end = this.limit;
  5601. if (!this.noAssert) {
  5602. if (typeof begin !== 'number' || begin % 1 !== 0)
  5603. throw TypeError("Illegal begin: Not an integer");
  5604. begin >>>= 0;
  5605. if (typeof end !== 'number' || end % 1 !== 0)
  5606. throw TypeError("Illegal end: Not an integer");
  5607. end >>>= 0;
  5608. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  5609. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  5610. }
  5611. if (begin === end)
  5612. return new ByteBuffer(0, this.littleEndian, this.noAssert);
  5613. var capacity = end - begin,
  5614. bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
  5615. bb.offset = 0;
  5616. bb.limit = capacity;
  5617. if (bb.markedOffset >= 0) bb.markedOffset -= begin;
  5618. this.copyTo(bb, 0, begin, end);
  5619. return bb;
  5620. };
  5621. /**
  5622. * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
  5623. * {@link ByteBuffer#limit}.
  5624. * @param {!ByteBuffer} target Target ByteBuffer
  5625. * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
  5626. * by the number of bytes copied if omitted.
  5627. * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
  5628. * number of bytes copied if omitted.
  5629. * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
  5630. * @returns {!ByteBuffer} this
  5631. * @expose
  5632. */
  5633. ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
  5634. var relative,
  5635. targetRelative;
  5636. if (!this.noAssert) {
  5637. if (!ByteBuffer.isByteBuffer(target))
  5638. throw TypeError("Illegal target: Not a ByteBuffer");
  5639. }
  5640. targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
  5641. sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
  5642. sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
  5643. if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
  5644. throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
  5645. if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
  5646. throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
  5647. var len = sourceLimit - sourceOffset;
  5648. if (len === 0)
  5649. return target; // Nothing to copy
  5650. target.ensureCapacity(targetOffset + len);
  5651. target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
  5652. if (relative) this.offset += len;
  5653. if (targetRelative) target.offset += len;
  5654. return this;
  5655. };
  5656. /**
  5657. * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
  5658. * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
  5659. * the required capacity will be used instead.
  5660. * @param {number} capacity Required capacity
  5661. * @returns {!ByteBuffer} this
  5662. * @expose
  5663. */
  5664. ByteBufferPrototype.ensureCapacity = function(capacity) {
  5665. var current = this.buffer.byteLength;
  5666. if (current < capacity)
  5667. return this.resize((current *= 2) > capacity ? current : capacity);
  5668. return this;
  5669. };
  5670. /**
  5671. * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
  5672. * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
  5673. * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
  5674. * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
  5675. * written if omitted. defaults to {@link ByteBuffer#offset}.
  5676. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
  5677. * @returns {!ByteBuffer} this
  5678. * @expose
  5679. * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
  5680. */
  5681. ByteBufferPrototype.fill = function(value, begin, end) {
  5682. var relative = typeof begin === 'undefined';
  5683. if (relative) begin = this.offset;
  5684. if (typeof value === 'string' && value.length > 0)
  5685. value = value.charCodeAt(0);
  5686. if (typeof begin === 'undefined') begin = this.offset;
  5687. if (typeof end === 'undefined') end = this.limit;
  5688. if (!this.noAssert) {
  5689. if (typeof value !== 'number' || value % 1 !== 0)
  5690. throw TypeError("Illegal value: "+value+" (not an integer)");
  5691. value |= 0;
  5692. if (typeof begin !== 'number' || begin % 1 !== 0)
  5693. throw TypeError("Illegal begin: Not an integer");
  5694. begin >>>= 0;
  5695. if (typeof end !== 'number' || end % 1 !== 0)
  5696. throw TypeError("Illegal end: Not an integer");
  5697. end >>>= 0;
  5698. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  5699. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  5700. }
  5701. if (begin >= end)
  5702. return this; // Nothing to fill
  5703. while (begin < end) this.view[begin++] = value;
  5704. if (relative) this.offset = begin;
  5705. return this;
  5706. };
  5707. /**
  5708. * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
  5709. * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
  5710. * @returns {!ByteBuffer} this
  5711. * @expose
  5712. */
  5713. ByteBufferPrototype.flip = function() {
  5714. this.limit = this.offset;
  5715. this.offset = 0;
  5716. return this;
  5717. };
  5718. /**
  5719. * Marks an offset on this ByteBuffer to be used later.
  5720. * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
  5721. * @returns {!ByteBuffer} this
  5722. * @throws {TypeError} If `offset` is not a valid number
  5723. * @throws {RangeError} If `offset` is out of bounds
  5724. * @see ByteBuffer#reset
  5725. * @expose
  5726. */
  5727. ByteBufferPrototype.mark = function(offset) {
  5728. offset = typeof offset === 'undefined' ? this.offset : offset;
  5729. if (!this.noAssert) {
  5730. if (typeof offset !== 'number' || offset % 1 !== 0)
  5731. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5732. offset >>>= 0;
  5733. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5734. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5735. }
  5736. this.markedOffset = offset;
  5737. return this;
  5738. };
  5739. /**
  5740. * Sets the byte order.
  5741. * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
  5742. * @returns {!ByteBuffer} this
  5743. * @expose
  5744. */
  5745. ByteBufferPrototype.order = function(littleEndian) {
  5746. if (!this.noAssert) {
  5747. if (typeof littleEndian !== 'boolean')
  5748. throw TypeError("Illegal littleEndian: Not a boolean");
  5749. }
  5750. this.littleEndian = !!littleEndian;
  5751. return this;
  5752. };
  5753. /**
  5754. * Switches (to) little endian byte order.
  5755. * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
  5756. * @returns {!ByteBuffer} this
  5757. * @expose
  5758. */
  5759. ByteBufferPrototype.LE = function(littleEndian) {
  5760. this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
  5761. return this;
  5762. };
  5763. /**
  5764. * Switches (to) big endian byte order.
  5765. * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
  5766. * @returns {!ByteBuffer} this
  5767. * @expose
  5768. */
  5769. ByteBufferPrototype.BE = function(bigEndian) {
  5770. this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
  5771. return this;
  5772. };
  5773. /**
  5774. * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
  5775. * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
  5776. * will be resized and its contents moved accordingly.
  5777. * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
  5778. * modified according to the performed read operation.
  5779. * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
  5780. * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
  5781. * prepended if omitted.
  5782. * @returns {!ByteBuffer} this
  5783. * @expose
  5784. * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
  5785. * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
  5786. */
  5787. ByteBufferPrototype.prepend = function(source, encoding, offset) {
  5788. if (typeof encoding === 'number' || typeof encoding !== 'string') {
  5789. offset = encoding;
  5790. encoding = undefined;
  5791. }
  5792. var relative = typeof offset === 'undefined';
  5793. if (relative) offset = this.offset;
  5794. if (!this.noAssert) {
  5795. if (typeof offset !== 'number' || offset % 1 !== 0)
  5796. throw TypeError("Illegal offset: "+offset+" (not an integer)");
  5797. offset >>>= 0;
  5798. if (offset < 0 || offset + 0 > this.buffer.byteLength)
  5799. throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
  5800. }
  5801. if (!(source instanceof ByteBuffer))
  5802. source = ByteBuffer.wrap(source, encoding);
  5803. var len = source.limit - source.offset;
  5804. if (len <= 0) return this; // Nothing to prepend
  5805. var diff = len - offset;
  5806. if (diff > 0) { // Not enough space before offset, so resize + move
  5807. var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
  5808. var view = new Uint8Array(buffer);
  5809. view.set(this.view.subarray(offset, this.buffer.byteLength), len);
  5810. this.buffer = buffer;
  5811. this.view = view;
  5812. this.offset += diff;
  5813. if (this.markedOffset >= 0) this.markedOffset += diff;
  5814. this.limit += diff;
  5815. offset += diff;
  5816. } else {
  5817. var arrayView = new Uint8Array(this.buffer);
  5818. }
  5819. this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
  5820. source.offset = source.limit;
  5821. if (relative)
  5822. this.offset -= len;
  5823. return this;
  5824. };
  5825. /**
  5826. * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
  5827. * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
  5828. * will be resized and its contents moved accordingly.
  5829. * @param {!ByteBuffer} target Target ByteBuffer
  5830. * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
  5831. * prepended if omitted.
  5832. * @returns {!ByteBuffer} this
  5833. * @expose
  5834. * @see ByteBuffer#prepend
  5835. */
  5836. ByteBufferPrototype.prependTo = function(target, offset) {
  5837. target.prepend(this, offset);
  5838. return this;
  5839. };
  5840. /**
  5841. * Prints debug information about this ByteBuffer's contents.
  5842. * @param {function(string)=} out Output function to call, defaults to console.log
  5843. * @expose
  5844. */
  5845. ByteBufferPrototype.printDebug = function(out) {
  5846. if (typeof out !== 'function') out = console.log.bind(console);
  5847. out(
  5848. this.toString()+"\n"+
  5849. "-------------------------------------------------------------------\n"+
  5850. this.toDebug(/* columns */ true)
  5851. );
  5852. };
  5853. /**
  5854. * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
  5855. * {@link ByteBuffer#limit}, so this returns `limit - offset`.
  5856. * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
  5857. * @expose
  5858. */
  5859. ByteBufferPrototype.remaining = function() {
  5860. return this.limit - this.offset;
  5861. };
  5862. /**
  5863. * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
  5864. * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
  5865. * marked, sets `offset = 0`.
  5866. * @returns {!ByteBuffer} this
  5867. * @see ByteBuffer#mark
  5868. * @expose
  5869. */
  5870. ByteBufferPrototype.reset = function() {
  5871. if (this.markedOffset >= 0) {
  5872. this.offset = this.markedOffset;
  5873. this.markedOffset = -1;
  5874. } else {
  5875. this.offset = 0;
  5876. }
  5877. return this;
  5878. };
  5879. /**
  5880. * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
  5881. * large or larger.
  5882. * @param {number} capacity Capacity required
  5883. * @returns {!ByteBuffer} this
  5884. * @throws {TypeError} If `capacity` is not a number
  5885. * @throws {RangeError} If `capacity < 0`
  5886. * @expose
  5887. */
  5888. ByteBufferPrototype.resize = function(capacity) {
  5889. if (!this.noAssert) {
  5890. if (typeof capacity !== 'number' || capacity % 1 !== 0)
  5891. throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
  5892. capacity |= 0;
  5893. if (capacity < 0)
  5894. throw RangeError("Illegal capacity: 0 <= "+capacity);
  5895. }
  5896. if (this.buffer.byteLength < capacity) {
  5897. var buffer = new ArrayBuffer(capacity);
  5898. var view = new Uint8Array(buffer);
  5899. view.set(this.view);
  5900. this.buffer = buffer;
  5901. this.view = view;
  5902. }
  5903. return this;
  5904. };
  5905. /**
  5906. * Reverses this ByteBuffer's contents.
  5907. * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
  5908. * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
  5909. * @returns {!ByteBuffer} this
  5910. * @expose
  5911. */
  5912. ByteBufferPrototype.reverse = function(begin, end) {
  5913. if (typeof begin === 'undefined') begin = this.offset;
  5914. if (typeof end === 'undefined') end = this.limit;
  5915. if (!this.noAssert) {
  5916. if (typeof begin !== 'number' || begin % 1 !== 0)
  5917. throw TypeError("Illegal begin: Not an integer");
  5918. begin >>>= 0;
  5919. if (typeof end !== 'number' || end % 1 !== 0)
  5920. throw TypeError("Illegal end: Not an integer");
  5921. end >>>= 0;
  5922. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  5923. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  5924. }
  5925. if (begin === end)
  5926. return this; // Nothing to reverse
  5927. Array.prototype.reverse.call(this.view.subarray(begin, end));
  5928. return this;
  5929. };
  5930. /**
  5931. * Skips the next `length` bytes. This will just advance
  5932. * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
  5933. * @returns {!ByteBuffer} this
  5934. * @expose
  5935. */
  5936. ByteBufferPrototype.skip = function(length) {
  5937. if (!this.noAssert) {
  5938. if (typeof length !== 'number' || length % 1 !== 0)
  5939. throw TypeError("Illegal length: "+length+" (not an integer)");
  5940. length |= 0;
  5941. }
  5942. var offset = this.offset + length;
  5943. if (!this.noAssert) {
  5944. if (offset < 0 || offset > this.buffer.byteLength)
  5945. throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
  5946. }
  5947. this.offset = offset;
  5948. return this;
  5949. };
  5950. /**
  5951. * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
  5952. * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
  5953. * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
  5954. * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
  5955. * @expose
  5956. */
  5957. ByteBufferPrototype.slice = function(begin, end) {
  5958. if (typeof begin === 'undefined') begin = this.offset;
  5959. if (typeof end === 'undefined') end = this.limit;
  5960. if (!this.noAssert) {
  5961. if (typeof begin !== 'number' || begin % 1 !== 0)
  5962. throw TypeError("Illegal begin: Not an integer");
  5963. begin >>>= 0;
  5964. if (typeof end !== 'number' || end % 1 !== 0)
  5965. throw TypeError("Illegal end: Not an integer");
  5966. end >>>= 0;
  5967. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  5968. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  5969. }
  5970. var bb = this.clone();
  5971. bb.offset = begin;
  5972. bb.limit = end;
  5973. return bb;
  5974. };
  5975. /**
  5976. * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
  5977. * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
  5978. * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
  5979. * possible. Defaults to `false`
  5980. * @returns {!ArrayBuffer} Contents as an ArrayBuffer
  5981. * @expose
  5982. */
  5983. ByteBufferPrototype.toBuffer = function(forceCopy) {
  5984. var offset = this.offset,
  5985. limit = this.limit;
  5986. if (!this.noAssert) {
  5987. if (typeof offset !== 'number' || offset % 1 !== 0)
  5988. throw TypeError("Illegal offset: Not an integer");
  5989. offset >>>= 0;
  5990. if (typeof limit !== 'number' || limit % 1 !== 0)
  5991. throw TypeError("Illegal limit: Not an integer");
  5992. limit >>>= 0;
  5993. if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
  5994. throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
  5995. }
  5996. // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
  5997. // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
  5998. if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
  5999. return this.buffer;
  6000. if (offset === limit)
  6001. return EMPTY_BUFFER;
  6002. var buffer = new ArrayBuffer(limit - offset);
  6003. new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
  6004. return buffer;
  6005. };
  6006. /**
  6007. * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
  6008. * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
  6009. * @function
  6010. * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
  6011. * Defaults to `false`
  6012. * @returns {!ArrayBuffer} Contents as an ArrayBuffer
  6013. * @expose
  6014. */
  6015. ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
  6016. /**
  6017. * Converts the ByteBuffer's contents to a string.
  6018. * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
  6019. * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
  6020. * highlighted offsets.
  6021. * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
  6022. * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
  6023. * @returns {string} String representation
  6024. * @throws {Error} If `encoding` is invalid
  6025. * @expose
  6026. */
  6027. ByteBufferPrototype.toString = function(encoding, begin, end) {
  6028. if (typeof encoding === 'undefined')
  6029. return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
  6030. if (typeof encoding === 'number')
  6031. encoding = "utf8",
  6032. begin = encoding,
  6033. end = begin;
  6034. switch (encoding) {
  6035. case "utf8":
  6036. return this.toUTF8(begin, end);
  6037. case "base64":
  6038. return this.toBase64(begin, end);
  6039. case "hex":
  6040. return this.toHex(begin, end);
  6041. case "binary":
  6042. return this.toBinary(begin, end);
  6043. case "debug":
  6044. return this.toDebug();
  6045. case "columns":
  6046. return this.toColumns();
  6047. default:
  6048. throw Error("Unsupported encoding: "+encoding);
  6049. }
  6050. };
  6051. // lxiv-embeddable
  6052. /**
  6053. * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
  6054. * Released under the Apache License, Version 2.0
  6055. * see: https://github.com/dcodeIO/lxiv for details
  6056. */
  6057. var lxiv = function() {
  6058. /**
  6059. * lxiv namespace.
  6060. * @type {!Object.<string,*>}
  6061. * @exports lxiv
  6062. */
  6063. var lxiv = {};
  6064. /**
  6065. * Character codes for output.
  6066. * @type {!Array.<number>}
  6067. * @inner
  6068. */
  6069. var aout = [
  6070. 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  6071. 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
  6072. 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
  6073. 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
  6074. ];
  6075. /**
  6076. * Character codes for input.
  6077. * @type {!Array.<number>}
  6078. * @inner
  6079. */
  6080. var ain = [];
  6081. for (var i=0, k=aout.length; i<k; ++i)
  6082. ain[aout[i]] = i;
  6083. /**
  6084. * Encodes bytes to base64 char codes.
  6085. * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
  6086. * there are no more bytes left.
  6087. * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
  6088. * code.
  6089. */
  6090. lxiv.encode = function(src, dst) {
  6091. var b, t;
  6092. while ((b = src()) !== null) {
  6093. dst(aout[(b>>2)&0x3f]);
  6094. t = (b&0x3)<<4;
  6095. if ((b = src()) !== null) {
  6096. t |= (b>>4)&0xf;
  6097. dst(aout[(t|((b>>4)&0xf))&0x3f]);
  6098. t = (b&0xf)<<2;
  6099. if ((b = src()) !== null)
  6100. dst(aout[(t|((b>>6)&0x3))&0x3f]),
  6101. dst(aout[b&0x3f]);
  6102. else
  6103. dst(aout[t&0x3f]),
  6104. dst(61);
  6105. } else
  6106. dst(aout[t&0x3f]),
  6107. dst(61),
  6108. dst(61);
  6109. }
  6110. };
  6111. /**
  6112. * Decodes base64 char codes to bytes.
  6113. * @param {!function():number|null} src Characters source as a function returning the next char code respectively
  6114. * `null` if there are no more characters left.
  6115. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
  6116. * @throws {Error} If a character code is invalid
  6117. */
  6118. lxiv.decode = function(src, dst) {
  6119. var c, t1, t2;
  6120. function fail(c) {
  6121. throw Error("Illegal character code: "+c);
  6122. }
  6123. while ((c = src()) !== null) {
  6124. t1 = ain[c];
  6125. if (typeof t1 === 'undefined') fail(c);
  6126. if ((c = src()) !== null) {
  6127. t2 = ain[c];
  6128. if (typeof t2 === 'undefined') fail(c);
  6129. dst((t1<<2)>>>0|(t2&0x30)>>4);
  6130. if ((c = src()) !== null) {
  6131. t1 = ain[c];
  6132. if (typeof t1 === 'undefined')
  6133. if (c === 61) break; else fail(c);
  6134. dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
  6135. if ((c = src()) !== null) {
  6136. t2 = ain[c];
  6137. if (typeof t2 === 'undefined')
  6138. if (c === 61) break; else fail(c);
  6139. dst(((t1&0x3)<<6)>>>0|t2);
  6140. }
  6141. }
  6142. }
  6143. }
  6144. };
  6145. /**
  6146. * Tests if a string is valid base64.
  6147. * @param {string} str String to test
  6148. * @returns {boolean} `true` if valid, otherwise `false`
  6149. */
  6150. lxiv.test = function(str) {
  6151. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
  6152. };
  6153. return lxiv;
  6154. }();
  6155. // encodings/base64
  6156. /**
  6157. * Encodes this ByteBuffer's contents to a base64 encoded string.
  6158. * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
  6159. * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
  6160. * @returns {string} Base64 encoded string
  6161. * @throws {RangeError} If `begin` or `end` is out of bounds
  6162. * @expose
  6163. */
  6164. ByteBufferPrototype.toBase64 = function(begin, end) {
  6165. if (typeof begin === 'undefined')
  6166. begin = this.offset;
  6167. if (typeof end === 'undefined')
  6168. end = this.limit;
  6169. begin = begin | 0; end = end | 0;
  6170. if (begin < 0 || end > this.capacity || begin > end)
  6171. throw RangeError("begin, end");
  6172. var sd; lxiv.encode(function() {
  6173. return begin < end ? this.view[begin++] : null;
  6174. }.bind(this), sd = stringDestination());
  6175. return sd();
  6176. };
  6177. /**
  6178. * Decodes a base64 encoded string to a ByteBuffer.
  6179. * @param {string} str String to decode
  6180. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  6181. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  6182. * @returns {!ByteBuffer} ByteBuffer
  6183. * @expose
  6184. */
  6185. ByteBuffer.fromBase64 = function(str, littleEndian) {
  6186. if (typeof str !== 'string')
  6187. throw TypeError("str");
  6188. var bb = new ByteBuffer(str.length/4*3, littleEndian),
  6189. i = 0;
  6190. lxiv.decode(stringSource(str), function(b) {
  6191. bb.view[i++] = b;
  6192. });
  6193. bb.limit = i;
  6194. return bb;
  6195. };
  6196. /**
  6197. * Encodes a binary string to base64 like `window.btoa` does.
  6198. * @param {string} str Binary string
  6199. * @returns {string} Base64 encoded string
  6200. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
  6201. * @expose
  6202. */
  6203. ByteBuffer.btoa = function(str) {
  6204. return ByteBuffer.fromBinary(str).toBase64();
  6205. };
  6206. /**
  6207. * Decodes a base64 encoded string to binary like `window.atob` does.
  6208. * @param {string} b64 Base64 encoded string
  6209. * @returns {string} Binary string
  6210. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
  6211. * @expose
  6212. */
  6213. ByteBuffer.atob = function(b64) {
  6214. return ByteBuffer.fromBase64(b64).toBinary();
  6215. };
  6216. // encodings/binary
  6217. /**
  6218. * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
  6219. * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
  6220. * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
  6221. * @returns {string} Binary encoded string
  6222. * @throws {RangeError} If `offset > limit`
  6223. * @expose
  6224. */
  6225. ByteBufferPrototype.toBinary = function(begin, end) {
  6226. if (typeof begin === 'undefined')
  6227. begin = this.offset;
  6228. if (typeof end === 'undefined')
  6229. end = this.limit;
  6230. begin |= 0; end |= 0;
  6231. if (begin < 0 || end > this.capacity() || begin > end)
  6232. throw RangeError("begin, end");
  6233. if (begin === end)
  6234. return "";
  6235. var chars = [],
  6236. parts = [];
  6237. while (begin < end) {
  6238. chars.push(this.view[begin++]);
  6239. if (chars.length >= 1024)
  6240. parts.push(String.fromCharCode.apply(String, chars)),
  6241. chars = [];
  6242. }
  6243. return parts.join('') + String.fromCharCode.apply(String, chars);
  6244. };
  6245. /**
  6246. * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
  6247. * @param {string} str String to decode
  6248. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  6249. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  6250. * @returns {!ByteBuffer} ByteBuffer
  6251. * @expose
  6252. */
  6253. ByteBuffer.fromBinary = function(str, littleEndian) {
  6254. if (typeof str !== 'string')
  6255. throw TypeError("str");
  6256. var i = 0,
  6257. k = str.length,
  6258. charCode,
  6259. bb = new ByteBuffer(k, littleEndian);
  6260. while (i<k) {
  6261. charCode = str.charCodeAt(i);
  6262. if (charCode > 0xff)
  6263. throw RangeError("illegal char code: "+charCode);
  6264. bb.view[i++] = charCode;
  6265. }
  6266. bb.limit = k;
  6267. return bb;
  6268. };
  6269. // encodings/debug
  6270. /**
  6271. * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
  6272. * * `<` : offset,
  6273. * * `'` : markedOffset,
  6274. * * `>` : limit,
  6275. * * `|` : offset and limit,
  6276. * * `[` : offset and markedOffset,
  6277. * * `]` : markedOffset and limit,
  6278. * * `!` : offset, markedOffset and limit
  6279. * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
  6280. * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
  6281. * @expose
  6282. * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
  6283. * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
  6284. * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
  6285. * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
  6286. */
  6287. ByteBufferPrototype.toDebug = function(columns) {
  6288. var i = -1,
  6289. k = this.buffer.byteLength,
  6290. b,
  6291. hex = "",
  6292. asc = "",
  6293. out = "";
  6294. while (i<k) {
  6295. if (i !== -1) {
  6296. b = this.view[i];
  6297. if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
  6298. else hex += b.toString(16).toUpperCase();
  6299. if (columns)
  6300. asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
  6301. }
  6302. ++i;
  6303. if (columns) {
  6304. if (i > 0 && i % 16 === 0 && i !== k) {
  6305. while (hex.length < 3*16+3) hex += " ";
  6306. out += hex+asc+"\n";
  6307. hex = asc = "";
  6308. }
  6309. }
  6310. if (i === this.offset && i === this.limit)
  6311. hex += i === this.markedOffset ? "!" : "|";
  6312. else if (i === this.offset)
  6313. hex += i === this.markedOffset ? "[" : "<";
  6314. else if (i === this.limit)
  6315. hex += i === this.markedOffset ? "]" : ">";
  6316. else
  6317. hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
  6318. }
  6319. if (columns && hex !== " ") {
  6320. while (hex.length < 3*16+3)
  6321. hex += " ";
  6322. out += hex + asc + "\n";
  6323. }
  6324. return columns ? out : hex;
  6325. };
  6326. /**
  6327. * Decodes a hex encoded string with marked offsets to a ByteBuffer.
  6328. * @param {string} str Debug string to decode (not be generated with `columns = true`)
  6329. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  6330. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  6331. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  6332. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  6333. * @returns {!ByteBuffer} ByteBuffer
  6334. * @expose
  6335. * @see ByteBuffer#toDebug
  6336. */
  6337. ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
  6338. var k = str.length,
  6339. bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
  6340. var i = 0, j = 0, ch, b,
  6341. rs = false, // Require symbol next
  6342. ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
  6343. fail = false;
  6344. while (i<k) {
  6345. switch (ch = str.charAt(i++)) {
  6346. case '!':
  6347. if (!noAssert) {
  6348. if (ho || hm || hl) {
  6349. fail = true;
  6350. break;
  6351. }
  6352. ho = hm = hl = true;
  6353. }
  6354. bb.offset = bb.markedOffset = bb.limit = j;
  6355. rs = false;
  6356. break;
  6357. case '|':
  6358. if (!noAssert) {
  6359. if (ho || hl) {
  6360. fail = true;
  6361. break;
  6362. }
  6363. ho = hl = true;
  6364. }
  6365. bb.offset = bb.limit = j;
  6366. rs = false;
  6367. break;
  6368. case '[':
  6369. if (!noAssert) {
  6370. if (ho || hm) {
  6371. fail = true;
  6372. break;
  6373. }
  6374. ho = hm = true;
  6375. }
  6376. bb.offset = bb.markedOffset = j;
  6377. rs = false;
  6378. break;
  6379. case '<':
  6380. if (!noAssert) {
  6381. if (ho) {
  6382. fail = true;
  6383. break;
  6384. }
  6385. ho = true;
  6386. }
  6387. bb.offset = j;
  6388. rs = false;
  6389. break;
  6390. case ']':
  6391. if (!noAssert) {
  6392. if (hl || hm) {
  6393. fail = true;
  6394. break;
  6395. }
  6396. hl = hm = true;
  6397. }
  6398. bb.limit = bb.markedOffset = j;
  6399. rs = false;
  6400. break;
  6401. case '>':
  6402. if (!noAssert) {
  6403. if (hl) {
  6404. fail = true;
  6405. break;
  6406. }
  6407. hl = true;
  6408. }
  6409. bb.limit = j;
  6410. rs = false;
  6411. break;
  6412. case "'":
  6413. if (!noAssert) {
  6414. if (hm) {
  6415. fail = true;
  6416. break;
  6417. }
  6418. hm = true;
  6419. }
  6420. bb.markedOffset = j;
  6421. rs = false;
  6422. break;
  6423. case ' ':
  6424. rs = false;
  6425. break;
  6426. default:
  6427. if (!noAssert) {
  6428. if (rs) {
  6429. fail = true;
  6430. break;
  6431. }
  6432. }
  6433. b = parseInt(ch+str.charAt(i++), 16);
  6434. if (!noAssert) {
  6435. if (isNaN(b) || b < 0 || b > 255)
  6436. throw TypeError("Illegal str: Not a debug encoded string");
  6437. }
  6438. bb.view[j++] = b;
  6439. rs = true;
  6440. }
  6441. if (fail)
  6442. throw TypeError("Illegal str: Invalid symbol at "+i);
  6443. }
  6444. if (!noAssert) {
  6445. if (!ho || !hl)
  6446. throw TypeError("Illegal str: Missing offset or limit");
  6447. if (j<bb.buffer.byteLength)
  6448. throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
  6449. }
  6450. return bb;
  6451. };
  6452. // encodings/hex
  6453. /**
  6454. * Encodes this ByteBuffer's contents to a hex encoded string.
  6455. * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
  6456. * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
  6457. * @returns {string} Hex encoded string
  6458. * @expose
  6459. */
  6460. ByteBufferPrototype.toHex = function(begin, end) {
  6461. begin = typeof begin === 'undefined' ? this.offset : begin;
  6462. end = typeof end === 'undefined' ? this.limit : end;
  6463. if (!this.noAssert) {
  6464. if (typeof begin !== 'number' || begin % 1 !== 0)
  6465. throw TypeError("Illegal begin: Not an integer");
  6466. begin >>>= 0;
  6467. if (typeof end !== 'number' || end % 1 !== 0)
  6468. throw TypeError("Illegal end: Not an integer");
  6469. end >>>= 0;
  6470. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  6471. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  6472. }
  6473. var out = new Array(end - begin),
  6474. b;
  6475. while (begin < end) {
  6476. b = this.view[begin++];
  6477. if (b < 0x10)
  6478. out.push("0", b.toString(16));
  6479. else out.push(b.toString(16));
  6480. }
  6481. return out.join('');
  6482. };
  6483. /**
  6484. * Decodes a hex encoded string to a ByteBuffer.
  6485. * @param {string} str String to decode
  6486. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  6487. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  6488. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  6489. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  6490. * @returns {!ByteBuffer} ByteBuffer
  6491. * @expose
  6492. */
  6493. ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
  6494. if (!noAssert) {
  6495. if (typeof str !== 'string')
  6496. throw TypeError("Illegal str: Not a string");
  6497. if (str.length % 2 !== 0)
  6498. throw TypeError("Illegal str: Length not a multiple of 2");
  6499. }
  6500. var k = str.length,
  6501. bb = new ByteBuffer((k / 2) | 0, littleEndian),
  6502. b;
  6503. for (var i=0, j=0; i<k; i+=2) {
  6504. b = parseInt(str.substring(i, i+2), 16);
  6505. if (!noAssert)
  6506. if (!isFinite(b) || b < 0 || b > 255)
  6507. throw TypeError("Illegal str: Contains non-hex characters");
  6508. bb.view[j++] = b;
  6509. }
  6510. bb.limit = j;
  6511. return bb;
  6512. };
  6513. // utfx-embeddable
  6514. /**
  6515. * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
  6516. * Released under the Apache License, Version 2.0
  6517. * see: https://github.com/dcodeIO/utfx for details
  6518. */
  6519. var utfx = function() {
  6520. /**
  6521. * utfx namespace.
  6522. * @inner
  6523. * @type {!Object.<string,*>}
  6524. */
  6525. var utfx = {};
  6526. /**
  6527. * Maximum valid code point.
  6528. * @type {number}
  6529. * @const
  6530. */
  6531. utfx.MAX_CODEPOINT = 0x10FFFF;
  6532. /**
  6533. * Encodes UTF8 code points to UTF8 bytes.
  6534. * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
  6535. * respectively `null` if there are no more code points left or a single numeric code point.
  6536. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
  6537. */
  6538. utfx.encodeUTF8 = function(src, dst) {
  6539. var cp = null;
  6540. if (typeof src === 'number')
  6541. cp = src,
  6542. src = function() { return null; };
  6543. while (cp !== null || (cp = src()) !== null) {
  6544. if (cp < 0x80)
  6545. dst(cp&0x7F);
  6546. else if (cp < 0x800)
  6547. dst(((cp>>6)&0x1F)|0xC0),
  6548. dst((cp&0x3F)|0x80);
  6549. else if (cp < 0x10000)
  6550. dst(((cp>>12)&0x0F)|0xE0),
  6551. dst(((cp>>6)&0x3F)|0x80),
  6552. dst((cp&0x3F)|0x80);
  6553. else
  6554. dst(((cp>>18)&0x07)|0xF0),
  6555. dst(((cp>>12)&0x3F)|0x80),
  6556. dst(((cp>>6)&0x3F)|0x80),
  6557. dst((cp&0x3F)|0x80);
  6558. cp = null;
  6559. }
  6560. };
  6561. /**
  6562. * Decodes UTF8 bytes to UTF8 code points.
  6563. * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
  6564. * are no more bytes left.
  6565. * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
  6566. * @throws {RangeError} If a starting byte is invalid in UTF8
  6567. * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
  6568. * remaining bytes.
  6569. */
  6570. utfx.decodeUTF8 = function(src, dst) {
  6571. var a, b, c, d, fail = function(b) {
  6572. b = b.slice(0, b.indexOf(null));
  6573. var err = Error(b.toString());
  6574. err.name = "TruncatedError";
  6575. err['bytes'] = b;
  6576. throw err;
  6577. };
  6578. while ((a = src()) !== null) {
  6579. if ((a&0x80) === 0)
  6580. dst(a);
  6581. else if ((a&0xE0) === 0xC0)
  6582. ((b = src()) === null) && fail([a, b]),
  6583. dst(((a&0x1F)<<6) | (b&0x3F));
  6584. else if ((a&0xF0) === 0xE0)
  6585. ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
  6586. dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
  6587. else if ((a&0xF8) === 0xF0)
  6588. ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
  6589. dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
  6590. else throw RangeError("Illegal starting byte: "+a);
  6591. }
  6592. };
  6593. /**
  6594. * Converts UTF16 characters to UTF8 code points.
  6595. * @param {!function():number|null} src Characters source as a function returning the next char code respectively
  6596. * `null` if there are no more characters left.
  6597. * @param {!function(number)} dst Code points destination as a function successively called with each converted code
  6598. * point.
  6599. */
  6600. utfx.UTF16toUTF8 = function(src, dst) {
  6601. var c1, c2 = null;
  6602. while (true) {
  6603. if ((c1 = c2 !== null ? c2 : src()) === null)
  6604. break;
  6605. if (c1 >= 0xD800 && c1 <= 0xDFFF) {
  6606. if ((c2 = src()) !== null) {
  6607. if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
  6608. dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
  6609. c2 = null; continue;
  6610. }
  6611. }
  6612. }
  6613. dst(c1);
  6614. }
  6615. if (c2 !== null) dst(c2);
  6616. };
  6617. /**
  6618. * Converts UTF8 code points to UTF16 characters.
  6619. * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
  6620. * respectively `null` if there are no more code points left or a single numeric code point.
  6621. * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
  6622. * @throws {RangeError} If a code point is out of range
  6623. */
  6624. utfx.UTF8toUTF16 = function(src, dst) {
  6625. var cp = null;
  6626. if (typeof src === 'number')
  6627. cp = src, src = function() { return null; };
  6628. while (cp !== null || (cp = src()) !== null) {
  6629. if (cp <= 0xFFFF)
  6630. dst(cp);
  6631. else
  6632. cp -= 0x10000,
  6633. dst((cp>>10)+0xD800),
  6634. dst((cp%0x400)+0xDC00);
  6635. cp = null;
  6636. }
  6637. };
  6638. /**
  6639. * Converts and encodes UTF16 characters to UTF8 bytes.
  6640. * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
  6641. * if there are no more characters left.
  6642. * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
  6643. */
  6644. utfx.encodeUTF16toUTF8 = function(src, dst) {
  6645. utfx.UTF16toUTF8(src, function(cp) {
  6646. utfx.encodeUTF8(cp, dst);
  6647. });
  6648. };
  6649. /**
  6650. * Decodes and converts UTF8 bytes to UTF16 characters.
  6651. * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
  6652. * are no more bytes left.
  6653. * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
  6654. * @throws {RangeError} If a starting byte is invalid in UTF8
  6655. * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
  6656. */
  6657. utfx.decodeUTF8toUTF16 = function(src, dst) {
  6658. utfx.decodeUTF8(src, function(cp) {
  6659. utfx.UTF8toUTF16(cp, dst);
  6660. });
  6661. };
  6662. /**
  6663. * Calculates the byte length of an UTF8 code point.
  6664. * @param {number} cp UTF8 code point
  6665. * @returns {number} Byte length
  6666. */
  6667. utfx.calculateCodePoint = function(cp) {
  6668. return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
  6669. };
  6670. /**
  6671. * Calculates the number of UTF8 bytes required to store UTF8 code points.
  6672. * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
  6673. * `null` if there are no more code points left.
  6674. * @returns {number} The number of UTF8 bytes required
  6675. */
  6676. utfx.calculateUTF8 = function(src) {
  6677. var cp, l=0;
  6678. while ((cp = src()) !== null)
  6679. l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
  6680. return l;
  6681. };
  6682. /**
  6683. * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
  6684. * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
  6685. * `null` if there are no more characters left.
  6686. * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
  6687. */
  6688. utfx.calculateUTF16asUTF8 = function(src) {
  6689. var n=0, l=0;
  6690. utfx.UTF16toUTF8(src, function(cp) {
  6691. ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
  6692. });
  6693. return [n,l];
  6694. };
  6695. return utfx;
  6696. }();
  6697. // encodings/utf8
  6698. /**
  6699. * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
  6700. * string.
  6701. * @returns {string} Hex encoded string
  6702. * @throws {RangeError} If `offset > limit`
  6703. * @expose
  6704. */
  6705. ByteBufferPrototype.toUTF8 = function(begin, end) {
  6706. if (typeof begin === 'undefined') begin = this.offset;
  6707. if (typeof end === 'undefined') end = this.limit;
  6708. if (!this.noAssert) {
  6709. if (typeof begin !== 'number' || begin % 1 !== 0)
  6710. throw TypeError("Illegal begin: Not an integer");
  6711. begin >>>= 0;
  6712. if (typeof end !== 'number' || end % 1 !== 0)
  6713. throw TypeError("Illegal end: Not an integer");
  6714. end >>>= 0;
  6715. if (begin < 0 || begin > end || end > this.buffer.byteLength)
  6716. throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
  6717. }
  6718. var sd; try {
  6719. utfx.decodeUTF8toUTF16(function() {
  6720. return begin < end ? this.view[begin++] : null;
  6721. }.bind(this), sd = stringDestination());
  6722. } catch (e) {
  6723. if (begin !== end)
  6724. throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
  6725. }
  6726. return sd();
  6727. };
  6728. /**
  6729. * Decodes an UTF8 encoded string to a ByteBuffer.
  6730. * @param {string} str String to decode
  6731. * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
  6732. * {@link ByteBuffer.DEFAULT_ENDIAN}.
  6733. * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
  6734. * {@link ByteBuffer.DEFAULT_NOASSERT}.
  6735. * @returns {!ByteBuffer} ByteBuffer
  6736. * @expose
  6737. */
  6738. ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
  6739. if (!noAssert)
  6740. if (typeof str !== 'string')
  6741. throw TypeError("Illegal str: Not a string");
  6742. var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
  6743. i = 0;
  6744. utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
  6745. bb.view[i++] = b;
  6746. });
  6747. bb.limit = i;
  6748. return bb;
  6749. };
  6750. return ByteBuffer;
  6751. });
  6752. });
  6753. var _nodeResolve_empty = {};
  6754. var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
  6755. __proto__: null,
  6756. 'default': _nodeResolve_empty
  6757. });
  6758. var require$$2 = getCjsExportFromNamespace(_nodeResolve_empty$1);
  6759. var protobufLight = createCommonjsModule(function (module) {
  6760. /*
  6761. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  6762. Licensed under the Apache License, Version 2.0 (the "License");
  6763. you may not use this file except in compliance with the License.
  6764. You may obtain a copy of the License at
  6765. http://www.apache.org/licenses/LICENSE-2.0
  6766. Unless required by applicable law or agreed to in writing, software
  6767. distributed under the License is distributed on an "AS IS" BASIS,
  6768. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6769. See the License for the specific language governing permissions and
  6770. limitations under the License.
  6771. */
  6772. /**
  6773. * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
  6774. * Released under the Apache License, Version 2.0
  6775. * see: https://github.com/dcodeIO/protobuf.js for details
  6776. */
  6777. (function(global, factory) {
  6778. /* AMD */ if (typeof commonjsRequire === "function" && 'object' === "object" && module && module["exports"])
  6779. module["exports"] = factory(bytebuffer, true);
  6780. /* Global */ else
  6781. (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
  6782. })(commonjsGlobal, function(ByteBuffer, isCommonJS) {
  6783. /**
  6784. * The ProtoBuf namespace.
  6785. * @exports ProtoBuf
  6786. * @namespace
  6787. * @expose
  6788. */
  6789. var ProtoBuf = {};
  6790. /**
  6791. * @type {!function(new: ByteBuffer, ...[*])}
  6792. * @expose
  6793. */
  6794. ProtoBuf.ByteBuffer = ByteBuffer;
  6795. /**
  6796. * @type {?function(new: Long, ...[*])}
  6797. * @expose
  6798. */
  6799. ProtoBuf.Long = ByteBuffer.Long || null;
  6800. /**
  6801. * ProtoBuf.js version.
  6802. * @type {string}
  6803. * @const
  6804. * @expose
  6805. */
  6806. ProtoBuf.VERSION = "5.0.3";
  6807. /**
  6808. * Wire types.
  6809. * @type {Object.<string,number>}
  6810. * @const
  6811. * @expose
  6812. */
  6813. ProtoBuf.WIRE_TYPES = {};
  6814. /**
  6815. * Varint wire type.
  6816. * @type {number}
  6817. * @expose
  6818. */
  6819. ProtoBuf.WIRE_TYPES.VARINT = 0;
  6820. /**
  6821. * Fixed 64 bits wire type.
  6822. * @type {number}
  6823. * @const
  6824. * @expose
  6825. */
  6826. ProtoBuf.WIRE_TYPES.BITS64 = 1;
  6827. /**
  6828. * Length delimited wire type.
  6829. * @type {number}
  6830. * @const
  6831. * @expose
  6832. */
  6833. ProtoBuf.WIRE_TYPES.LDELIM = 2;
  6834. /**
  6835. * Start group wire type.
  6836. * @type {number}
  6837. * @const
  6838. * @expose
  6839. */
  6840. ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
  6841. /**
  6842. * End group wire type.
  6843. * @type {number}
  6844. * @const
  6845. * @expose
  6846. */
  6847. ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
  6848. /**
  6849. * Fixed 32 bits wire type.
  6850. * @type {number}
  6851. * @const
  6852. * @expose
  6853. */
  6854. ProtoBuf.WIRE_TYPES.BITS32 = 5;
  6855. /**
  6856. * Packable wire types.
  6857. * @type {!Array.<number>}
  6858. * @const
  6859. * @expose
  6860. */
  6861. ProtoBuf.PACKABLE_WIRE_TYPES = [
  6862. ProtoBuf.WIRE_TYPES.VARINT,
  6863. ProtoBuf.WIRE_TYPES.BITS64,
  6864. ProtoBuf.WIRE_TYPES.BITS32
  6865. ];
  6866. /**
  6867. * Types.
  6868. * @dict
  6869. * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
  6870. * @const
  6871. * @expose
  6872. */
  6873. ProtoBuf.TYPES = {
  6874. // According to the protobuf spec.
  6875. "int32": {
  6876. name: "int32",
  6877. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6878. defaultValue: 0
  6879. },
  6880. "uint32": {
  6881. name: "uint32",
  6882. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6883. defaultValue: 0
  6884. },
  6885. "sint32": {
  6886. name: "sint32",
  6887. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6888. defaultValue: 0
  6889. },
  6890. "int64": {
  6891. name: "int64",
  6892. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6893. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  6894. },
  6895. "uint64": {
  6896. name: "uint64",
  6897. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6898. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  6899. },
  6900. "sint64": {
  6901. name: "sint64",
  6902. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6903. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  6904. },
  6905. "bool": {
  6906. name: "bool",
  6907. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6908. defaultValue: false
  6909. },
  6910. "double": {
  6911. name: "double",
  6912. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  6913. defaultValue: 0
  6914. },
  6915. "string": {
  6916. name: "string",
  6917. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  6918. defaultValue: ""
  6919. },
  6920. "bytes": {
  6921. name: "bytes",
  6922. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  6923. defaultValue: null // overridden in the code, must be a unique instance
  6924. },
  6925. "fixed32": {
  6926. name: "fixed32",
  6927. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  6928. defaultValue: 0
  6929. },
  6930. "sfixed32": {
  6931. name: "sfixed32",
  6932. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  6933. defaultValue: 0
  6934. },
  6935. "fixed64": {
  6936. name: "fixed64",
  6937. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  6938. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  6939. },
  6940. "sfixed64": {
  6941. name: "sfixed64",
  6942. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  6943. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  6944. },
  6945. "float": {
  6946. name: "float",
  6947. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  6948. defaultValue: 0
  6949. },
  6950. "enum": {
  6951. name: "enum",
  6952. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  6953. defaultValue: 0
  6954. },
  6955. "message": {
  6956. name: "message",
  6957. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  6958. defaultValue: null
  6959. },
  6960. "group": {
  6961. name: "group",
  6962. wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
  6963. defaultValue: null
  6964. }
  6965. };
  6966. /**
  6967. * Valid map key types.
  6968. * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
  6969. * @const
  6970. * @expose
  6971. */
  6972. ProtoBuf.MAP_KEY_TYPES = [
  6973. ProtoBuf.TYPES["int32"],
  6974. ProtoBuf.TYPES["sint32"],
  6975. ProtoBuf.TYPES["sfixed32"],
  6976. ProtoBuf.TYPES["uint32"],
  6977. ProtoBuf.TYPES["fixed32"],
  6978. ProtoBuf.TYPES["int64"],
  6979. ProtoBuf.TYPES["sint64"],
  6980. ProtoBuf.TYPES["sfixed64"],
  6981. ProtoBuf.TYPES["uint64"],
  6982. ProtoBuf.TYPES["fixed64"],
  6983. ProtoBuf.TYPES["bool"],
  6984. ProtoBuf.TYPES["string"],
  6985. ProtoBuf.TYPES["bytes"]
  6986. ];
  6987. /**
  6988. * Minimum field id.
  6989. * @type {number}
  6990. * @const
  6991. * @expose
  6992. */
  6993. ProtoBuf.ID_MIN = 1;
  6994. /**
  6995. * Maximum field id.
  6996. * @type {number}
  6997. * @const
  6998. * @expose
  6999. */
  7000. ProtoBuf.ID_MAX = 0x1FFFFFFF;
  7001. /**
  7002. * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
  7003. * Must be set prior to parsing.
  7004. * @type {boolean}
  7005. * @expose
  7006. */
  7007. ProtoBuf.convertFieldsToCamelCase = false;
  7008. /**
  7009. * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
  7010. * setting this to `false` prior to building messages.
  7011. * @type {boolean}
  7012. * @expose
  7013. */
  7014. ProtoBuf.populateAccessors = true;
  7015. /**
  7016. * By default, messages are populated with default values if a field is not present on the wire. To disable
  7017. * this behavior, set this setting to `false`.
  7018. * @type {boolean}
  7019. * @expose
  7020. */
  7021. ProtoBuf.populateDefaults = true;
  7022. /**
  7023. * @alias ProtoBuf.Util
  7024. * @expose
  7025. */
  7026. ProtoBuf.Util = (function() {
  7027. /**
  7028. * ProtoBuf utilities.
  7029. * @exports ProtoBuf.Util
  7030. * @namespace
  7031. */
  7032. var Util = {};
  7033. /**
  7034. * Flag if running in node or not.
  7035. * @type {boolean}
  7036. * @const
  7037. * @expose
  7038. */
  7039. Util.IS_NODE = !!(
  7040. typeof process === 'object' && process+'' === '[object process]' && !process['browser']
  7041. );
  7042. /**
  7043. * Constructs a XMLHttpRequest object.
  7044. * @return {XMLHttpRequest}
  7045. * @throws {Error} If XMLHttpRequest is not supported
  7046. * @expose
  7047. */
  7048. Util.XHR = function() {
  7049. // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
  7050. var XMLHttpFactories = [
  7051. function () {return new XMLHttpRequest()},
  7052. function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  7053. function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  7054. function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  7055. ];
  7056. /** @type {?XMLHttpRequest} */
  7057. var xhr = null;
  7058. for (var i=0;i<XMLHttpFactories.length;i++) {
  7059. try { xhr = XMLHttpFactories[i](); }
  7060. catch (e) { continue; }
  7061. break;
  7062. }
  7063. if (!xhr)
  7064. throw Error("XMLHttpRequest is not supported");
  7065. return xhr;
  7066. };
  7067. /**
  7068. * Fetches a resource.
  7069. * @param {string} path Resource path
  7070. * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
  7071. * be fetched synchronously. If the request failed, contents will be null.
  7072. * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
  7073. * @expose
  7074. */
  7075. Util.fetch = function(path, callback) {
  7076. if (callback && typeof callback != 'function')
  7077. callback = null;
  7078. if (Util.IS_NODE) {
  7079. var fs = require$$2;
  7080. if (callback) {
  7081. fs.readFile(path, function(err, data) {
  7082. if (err)
  7083. callback(null);
  7084. else
  7085. callback(""+data);
  7086. });
  7087. } else
  7088. try {
  7089. return fs.readFileSync(path);
  7090. } catch (e) {
  7091. return null;
  7092. }
  7093. } else {
  7094. var xhr = Util.XHR();
  7095. xhr.open('GET', path, callback ? true : false);
  7096. // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
  7097. xhr.setRequestHeader('Accept', 'text/plain');
  7098. if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
  7099. if (callback) {
  7100. xhr.onreadystatechange = function() {
  7101. if (xhr.readyState != 4) return;
  7102. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  7103. callback(xhr.responseText);
  7104. else
  7105. callback(null);
  7106. };
  7107. if (xhr.readyState == 4)
  7108. return;
  7109. xhr.send(null);
  7110. } else {
  7111. xhr.send(null);
  7112. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  7113. return xhr.responseText;
  7114. return null;
  7115. }
  7116. }
  7117. };
  7118. /**
  7119. * Converts a string to camel case.
  7120. * @param {string} str
  7121. * @returns {string}
  7122. * @expose
  7123. */
  7124. Util.toCamelCase = function(str) {
  7125. return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
  7126. return $1.toUpperCase();
  7127. });
  7128. };
  7129. return Util;
  7130. })();
  7131. /**
  7132. * Language expressions.
  7133. * @type {!Object.<string,!RegExp>}
  7134. * @expose
  7135. */
  7136. ProtoBuf.Lang = {
  7137. // Characters always ending a statement
  7138. DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
  7139. // Field rules
  7140. RULE: /^(?:required|optional|repeated|map)$/,
  7141. // Field types
  7142. TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
  7143. // Names
  7144. NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
  7145. // Type definitions
  7146. TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
  7147. // Type references
  7148. TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
  7149. // Fully qualified type references
  7150. FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
  7151. // All numbers
  7152. NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
  7153. // Decimal numbers
  7154. NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
  7155. // Hexadecimal numbers
  7156. NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
  7157. // Octal numbers
  7158. NUMBER_OCT: /^0[0-7]+$/,
  7159. // Floating point numbers
  7160. NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
  7161. // Booleans
  7162. BOOL: /^(?:true|false)$/i,
  7163. // Id numbers
  7164. ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  7165. // Negative id numbers (enum values)
  7166. NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  7167. // Whitespaces
  7168. WHITESPACE: /\s/,
  7169. // All strings
  7170. STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
  7171. // Double quoted strings
  7172. STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
  7173. // Single quoted strings
  7174. STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
  7175. };
  7176. /**
  7177. * @alias ProtoBuf.Reflect
  7178. * @expose
  7179. */
  7180. ProtoBuf.Reflect = (function(ProtoBuf) {
  7181. /**
  7182. * Reflection types.
  7183. * @exports ProtoBuf.Reflect
  7184. * @namespace
  7185. */
  7186. var Reflect = {};
  7187. /**
  7188. * Constructs a Reflect base class.
  7189. * @exports ProtoBuf.Reflect.T
  7190. * @constructor
  7191. * @abstract
  7192. * @param {!ProtoBuf.Builder} builder Builder reference
  7193. * @param {?ProtoBuf.Reflect.T} parent Parent object
  7194. * @param {string} name Object name
  7195. */
  7196. var T = function(builder, parent, name) {
  7197. /**
  7198. * Builder reference.
  7199. * @type {!ProtoBuf.Builder}
  7200. * @expose
  7201. */
  7202. this.builder = builder;
  7203. /**
  7204. * Parent object.
  7205. * @type {?ProtoBuf.Reflect.T}
  7206. * @expose
  7207. */
  7208. this.parent = parent;
  7209. /**
  7210. * Object name in namespace.
  7211. * @type {string}
  7212. * @expose
  7213. */
  7214. this.name = name;
  7215. /**
  7216. * Fully qualified class name
  7217. * @type {string}
  7218. * @expose
  7219. */
  7220. this.className;
  7221. };
  7222. /**
  7223. * @alias ProtoBuf.Reflect.T.prototype
  7224. * @inner
  7225. */
  7226. var TPrototype = T.prototype;
  7227. /**
  7228. * Returns the fully qualified name of this object.
  7229. * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
  7230. * @expose
  7231. */
  7232. TPrototype.fqn = function() {
  7233. var name = this.name,
  7234. ptr = this;
  7235. do {
  7236. ptr = ptr.parent;
  7237. if (ptr == null)
  7238. break;
  7239. name = ptr.name+"."+name;
  7240. } while (true);
  7241. return name;
  7242. };
  7243. /**
  7244. * Returns a string representation of this Reflect object (its fully qualified name).
  7245. * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
  7246. * @return String representation
  7247. * @expose
  7248. */
  7249. TPrototype.toString = function(includeClass) {
  7250. return (includeClass ? this.className + " " : "") + this.fqn();
  7251. };
  7252. /**
  7253. * Builds this type.
  7254. * @throws {Error} If this type cannot be built directly
  7255. * @expose
  7256. */
  7257. TPrototype.build = function() {
  7258. throw Error(this.toString(true)+" cannot be built directly");
  7259. };
  7260. /**
  7261. * @alias ProtoBuf.Reflect.T
  7262. * @expose
  7263. */
  7264. Reflect.T = T;
  7265. /**
  7266. * Constructs a new Namespace.
  7267. * @exports ProtoBuf.Reflect.Namespace
  7268. * @param {!ProtoBuf.Builder} builder Builder reference
  7269. * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
  7270. * @param {string} name Namespace name
  7271. * @param {Object.<string,*>=} options Namespace options
  7272. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  7273. * @constructor
  7274. * @extends ProtoBuf.Reflect.T
  7275. */
  7276. var Namespace = function(builder, parent, name, options, syntax) {
  7277. T.call(this, builder, parent, name);
  7278. /**
  7279. * @override
  7280. */
  7281. this.className = "Namespace";
  7282. /**
  7283. * Children inside the namespace.
  7284. * @type {!Array.<ProtoBuf.Reflect.T>}
  7285. */
  7286. this.children = [];
  7287. /**
  7288. * Options.
  7289. * @type {!Object.<string, *>}
  7290. */
  7291. this.options = options || {};
  7292. /**
  7293. * Syntax level (e.g., proto2 or proto3).
  7294. * @type {!string}
  7295. */
  7296. this.syntax = syntax || "proto2";
  7297. };
  7298. /**
  7299. * @alias ProtoBuf.Reflect.Namespace.prototype
  7300. * @inner
  7301. */
  7302. var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
  7303. /**
  7304. * Returns an array of the namespace's children.
  7305. * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
  7306. * @return {Array.<ProtoBuf.Reflect.T>}
  7307. * @expose
  7308. */
  7309. NamespacePrototype.getChildren = function(type) {
  7310. type = type || null;
  7311. if (type == null)
  7312. return this.children.slice();
  7313. var children = [];
  7314. for (var i=0, k=this.children.length; i<k; ++i)
  7315. if (this.children[i] instanceof type)
  7316. children.push(this.children[i]);
  7317. return children;
  7318. };
  7319. /**
  7320. * Adds a child to the namespace.
  7321. * @param {ProtoBuf.Reflect.T} child Child
  7322. * @throws {Error} If the child cannot be added (duplicate)
  7323. * @expose
  7324. */
  7325. NamespacePrototype.addChild = function(child) {
  7326. var other;
  7327. if (other = this.getChild(child.name)) {
  7328. // Try to revert camelcase transformation on collision
  7329. if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
  7330. other.name = other.originalName; // Revert previous first (effectively keeps both originals)
  7331. else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
  7332. child.name = child.originalName;
  7333. else
  7334. throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
  7335. }
  7336. this.children.push(child);
  7337. };
  7338. /**
  7339. * Gets a child by its name or id.
  7340. * @param {string|number} nameOrId Child name or id
  7341. * @return {?ProtoBuf.Reflect.T} The child or null if not found
  7342. * @expose
  7343. */
  7344. NamespacePrototype.getChild = function(nameOrId) {
  7345. var key = typeof nameOrId === 'number' ? 'id' : 'name';
  7346. for (var i=0, k=this.children.length; i<k; ++i)
  7347. if (this.children[i][key] === nameOrId)
  7348. return this.children[i];
  7349. return null;
  7350. };
  7351. /**
  7352. * Resolves a reflect object inside of this namespace.
  7353. * @param {string|!Array.<string>} qn Qualified name to resolve
  7354. * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
  7355. * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
  7356. * @expose
  7357. */
  7358. NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
  7359. var part = typeof qn === 'string' ? qn.split(".") : qn,
  7360. ptr = this,
  7361. i = 0;
  7362. if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
  7363. while (ptr.parent !== null)
  7364. ptr = ptr.parent;
  7365. i++;
  7366. }
  7367. var child;
  7368. do {
  7369. do {
  7370. if (!(ptr instanceof Reflect.Namespace)) {
  7371. ptr = null;
  7372. break;
  7373. }
  7374. child = ptr.getChild(part[i]);
  7375. if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
  7376. ptr = null;
  7377. break;
  7378. }
  7379. ptr = child; i++;
  7380. } while (i < part.length);
  7381. if (ptr != null)
  7382. break; // Found
  7383. // Else search the parent
  7384. if (this.parent !== null)
  7385. return this.parent.resolve(qn, excludeNonNamespace);
  7386. } while (ptr != null);
  7387. return ptr;
  7388. };
  7389. /**
  7390. * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
  7391. * @param {!ProtoBuf.Reflect.T} t Reflection type
  7392. * @returns {string} The shortest qualified name or, if there is none, the fqn
  7393. * @expose
  7394. */
  7395. NamespacePrototype.qn = function(t) {
  7396. var part = [], ptr = t;
  7397. do {
  7398. part.unshift(ptr.name);
  7399. ptr = ptr.parent;
  7400. } while (ptr !== null);
  7401. for (var len=1; len <= part.length; len++) {
  7402. var qn = part.slice(part.length-len);
  7403. if (t === this.resolve(qn, t instanceof Reflect.Namespace))
  7404. return qn.join(".");
  7405. }
  7406. return t.fqn();
  7407. };
  7408. /**
  7409. * Builds the namespace and returns the runtime counterpart.
  7410. * @return {Object.<string,Function|Object>} Runtime namespace
  7411. * @expose
  7412. */
  7413. NamespacePrototype.build = function() {
  7414. /** @dict */
  7415. var ns = {};
  7416. var children = this.children;
  7417. for (var i=0, k=children.length, child; i<k; ++i) {
  7418. child = children[i];
  7419. if (child instanceof Namespace)
  7420. ns[child.name] = child.build();
  7421. }
  7422. if (Object.defineProperty)
  7423. Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
  7424. return ns;
  7425. };
  7426. /**
  7427. * Builds the namespace's '$options' property.
  7428. * @return {Object.<string,*>}
  7429. */
  7430. NamespacePrototype.buildOpt = function() {
  7431. var opt = {},
  7432. keys = Object.keys(this.options);
  7433. for (var i=0, k=keys.length; i<k; ++i) {
  7434. var key = keys[i],
  7435. val = this.options[keys[i]];
  7436. // TODO: Options are not resolved, yet.
  7437. // if (val instanceof Namespace) {
  7438. // opt[key] = val.build();
  7439. // } else {
  7440. opt[key] = val;
  7441. // }
  7442. }
  7443. return opt;
  7444. };
  7445. /**
  7446. * Gets the value assigned to the option with the specified name.
  7447. * @param {string=} name Returns the option value if specified, otherwise all options are returned.
  7448. * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
  7449. */
  7450. NamespacePrototype.getOption = function(name) {
  7451. if (typeof name === 'undefined')
  7452. return this.options;
  7453. return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
  7454. };
  7455. /**
  7456. * @alias ProtoBuf.Reflect.Namespace
  7457. * @expose
  7458. */
  7459. Reflect.Namespace = Namespace;
  7460. /**
  7461. * Constructs a new Element implementation that checks and converts values for a
  7462. * particular field type, as appropriate.
  7463. *
  7464. * An Element represents a single value: either the value of a singular field,
  7465. * or a value contained in one entry of a repeated field or map field. This
  7466. * class does not implement these higher-level concepts; it only encapsulates
  7467. * the low-level typechecking and conversion.
  7468. *
  7469. * @exports ProtoBuf.Reflect.Element
  7470. * @param {{name: string, wireType: number}} type Resolved data type
  7471. * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
  7472. * (e.g. submessage field).
  7473. * @param {boolean} isMapKey Is this element a Map key? The value will be
  7474. * converted to string form if so.
  7475. * @param {string} syntax Syntax level of defining message type, e.g.,
  7476. * proto2 or proto3.
  7477. * @param {string} name Name of the field containing this element (for error
  7478. * messages)
  7479. * @constructor
  7480. */
  7481. var Element = function(type, resolvedType, isMapKey, syntax, name) {
  7482. /**
  7483. * Element type, as a string (e.g., int32).
  7484. * @type {{name: string, wireType: number}}
  7485. */
  7486. this.type = type;
  7487. /**
  7488. * Element type reference to submessage or enum definition, if needed.
  7489. * @type {ProtoBuf.Reflect.T|null}
  7490. */
  7491. this.resolvedType = resolvedType;
  7492. /**
  7493. * Element is a map key.
  7494. * @type {boolean}
  7495. */
  7496. this.isMapKey = isMapKey;
  7497. /**
  7498. * Syntax level of defining message type, e.g., proto2 or proto3.
  7499. * @type {string}
  7500. */
  7501. this.syntax = syntax;
  7502. /**
  7503. * Name of the field containing this element (for error messages)
  7504. * @type {string}
  7505. */
  7506. this.name = name;
  7507. if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
  7508. throw Error("Invalid map key type: " + type.name);
  7509. };
  7510. var ElementPrototype = Element.prototype;
  7511. /**
  7512. * Obtains a (new) default value for the specified type.
  7513. * @param type {string|{name: string, wireType: number}} Field type
  7514. * @returns {*} Default value
  7515. * @inner
  7516. */
  7517. function mkDefault(type) {
  7518. if (typeof type === 'string')
  7519. type = ProtoBuf.TYPES[type];
  7520. if (typeof type.defaultValue === 'undefined')
  7521. throw Error("default value for type "+type.name+" is not supported");
  7522. if (type == ProtoBuf.TYPES["bytes"])
  7523. return new ByteBuffer(0);
  7524. return type.defaultValue;
  7525. }
  7526. /**
  7527. * Returns the default value for this field in proto3.
  7528. * @function
  7529. * @param type {string|{name: string, wireType: number}} the field type
  7530. * @returns {*} Default value
  7531. */
  7532. Element.defaultFieldValue = mkDefault;
  7533. /**
  7534. * Makes a Long from a value.
  7535. * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
  7536. * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
  7537. * strings and numbers
  7538. * @returns {!Long}
  7539. * @throws {Error} If the value cannot be converted to a Long
  7540. * @inner
  7541. */
  7542. function mkLong(value, unsigned) {
  7543. if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
  7544. && value.low === value.low && value.high === value.high)
  7545. return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
  7546. if (typeof value === 'string')
  7547. return ProtoBuf.Long.fromString(value, unsigned || false, 10);
  7548. if (typeof value === 'number')
  7549. return ProtoBuf.Long.fromNumber(value, unsigned || false);
  7550. throw Error("not convertible to Long");
  7551. }
  7552. ElementPrototype.toString = function() {
  7553. return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
  7554. };
  7555. /**
  7556. * Checks if the given value can be set for an element of this type (singular
  7557. * field or one element of a repeated field or map).
  7558. * @param {*} value Value to check
  7559. * @return {*} Verified, maybe adjusted, value
  7560. * @throws {Error} If the value cannot be verified for this element slot
  7561. * @expose
  7562. */
  7563. ElementPrototype.verifyValue = function(value) {
  7564. var self = this;
  7565. function fail(val, msg) {
  7566. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  7567. }
  7568. switch (this.type) {
  7569. // Signed 32bit
  7570. case ProtoBuf.TYPES["int32"]:
  7571. case ProtoBuf.TYPES["sint32"]:
  7572. case ProtoBuf.TYPES["sfixed32"]:
  7573. // Account for !NaN: value === value
  7574. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  7575. fail(typeof value, "not an integer");
  7576. return value > 4294967295 ? value | 0 : value;
  7577. // Unsigned 32bit
  7578. case ProtoBuf.TYPES["uint32"]:
  7579. case ProtoBuf.TYPES["fixed32"]:
  7580. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  7581. fail(typeof value, "not an integer");
  7582. return value < 0 ? value >>> 0 : value;
  7583. // Signed 64bit
  7584. case ProtoBuf.TYPES["int64"]:
  7585. case ProtoBuf.TYPES["sint64"]:
  7586. case ProtoBuf.TYPES["sfixed64"]: {
  7587. if (ProtoBuf.Long)
  7588. try {
  7589. return mkLong(value, false);
  7590. } catch (e) {
  7591. fail(typeof value, e.message);
  7592. }
  7593. else
  7594. fail(typeof value, "requires Long.js");
  7595. }
  7596. // Unsigned 64bit
  7597. case ProtoBuf.TYPES["uint64"]:
  7598. case ProtoBuf.TYPES["fixed64"]: {
  7599. if (ProtoBuf.Long)
  7600. try {
  7601. return mkLong(value, true);
  7602. } catch (e) {
  7603. fail(typeof value, e.message);
  7604. }
  7605. else
  7606. fail(typeof value, "requires Long.js");
  7607. }
  7608. // Bool
  7609. case ProtoBuf.TYPES["bool"]:
  7610. if (typeof value !== 'boolean')
  7611. fail(typeof value, "not a boolean");
  7612. return value;
  7613. // Float
  7614. case ProtoBuf.TYPES["float"]:
  7615. case ProtoBuf.TYPES["double"]:
  7616. if (typeof value !== 'number')
  7617. fail(typeof value, "not a number");
  7618. return value;
  7619. // Length-delimited string
  7620. case ProtoBuf.TYPES["string"]:
  7621. if (typeof value !== 'string' && !(value && value instanceof String))
  7622. fail(typeof value, "not a string");
  7623. return ""+value; // Convert String object to string
  7624. // Length-delimited bytes
  7625. case ProtoBuf.TYPES["bytes"]:
  7626. if (ByteBuffer.isByteBuffer(value))
  7627. return value;
  7628. return ByteBuffer.wrap(value, "base64");
  7629. // Constant enum value
  7630. case ProtoBuf.TYPES["enum"]: {
  7631. var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
  7632. for (i=0; i<values.length; i++)
  7633. if (values[i].name == value)
  7634. return values[i].id;
  7635. else if (values[i].id == value)
  7636. return values[i].id;
  7637. if (this.syntax === 'proto3') {
  7638. // proto3: just make sure it's an integer.
  7639. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  7640. fail(typeof value, "not an integer");
  7641. if (value > 4294967295 || value < 0)
  7642. fail(typeof value, "not in range for uint32");
  7643. return value;
  7644. } else {
  7645. // proto2 requires enum values to be valid.
  7646. fail(value, "not a valid enum value");
  7647. }
  7648. }
  7649. // Embedded message
  7650. case ProtoBuf.TYPES["group"]:
  7651. case ProtoBuf.TYPES["message"]: {
  7652. if (!value || typeof value !== 'object')
  7653. fail(typeof value, "object expected");
  7654. if (value instanceof this.resolvedType.clazz)
  7655. return value;
  7656. if (value instanceof ProtoBuf.Builder.Message) {
  7657. // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
  7658. var obj = {};
  7659. for (var i in value)
  7660. if (value.hasOwnProperty(i))
  7661. obj[i] = value[i];
  7662. value = obj;
  7663. }
  7664. // Else let's try to construct one from a key-value object
  7665. return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
  7666. }
  7667. }
  7668. // We should never end here
  7669. throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
  7670. };
  7671. /**
  7672. * Calculates the byte length of an element on the wire.
  7673. * @param {number} id Field number
  7674. * @param {*} value Field value
  7675. * @returns {number} Byte length
  7676. * @throws {Error} If the value cannot be calculated
  7677. * @expose
  7678. */
  7679. ElementPrototype.calculateLength = function(id, value) {
  7680. if (value === null) return 0; // Nothing to encode
  7681. // Tag has already been written
  7682. var n;
  7683. switch (this.type) {
  7684. case ProtoBuf.TYPES["int32"]:
  7685. return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
  7686. case ProtoBuf.TYPES["uint32"]:
  7687. return ByteBuffer.calculateVarint32(value);
  7688. case ProtoBuf.TYPES["sint32"]:
  7689. return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
  7690. case ProtoBuf.TYPES["fixed32"]:
  7691. case ProtoBuf.TYPES["sfixed32"]:
  7692. case ProtoBuf.TYPES["float"]:
  7693. return 4;
  7694. case ProtoBuf.TYPES["int64"]:
  7695. case ProtoBuf.TYPES["uint64"]:
  7696. return ByteBuffer.calculateVarint64(value);
  7697. case ProtoBuf.TYPES["sint64"]:
  7698. return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
  7699. case ProtoBuf.TYPES["fixed64"]:
  7700. case ProtoBuf.TYPES["sfixed64"]:
  7701. return 8;
  7702. case ProtoBuf.TYPES["bool"]:
  7703. return 1;
  7704. case ProtoBuf.TYPES["enum"]:
  7705. return ByteBuffer.calculateVarint32(value);
  7706. case ProtoBuf.TYPES["double"]:
  7707. return 8;
  7708. case ProtoBuf.TYPES["string"]:
  7709. n = ByteBuffer.calculateUTF8Bytes(value);
  7710. return ByteBuffer.calculateVarint32(n) + n;
  7711. case ProtoBuf.TYPES["bytes"]:
  7712. if (value.remaining() < 0)
  7713. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  7714. return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
  7715. case ProtoBuf.TYPES["message"]:
  7716. n = this.resolvedType.calculate(value);
  7717. return ByteBuffer.calculateVarint32(n) + n;
  7718. case ProtoBuf.TYPES["group"]:
  7719. n = this.resolvedType.calculate(value);
  7720. return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  7721. }
  7722. // We should never end here
  7723. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  7724. };
  7725. /**
  7726. * Encodes a value to the specified buffer. Does not encode the key.
  7727. * @param {number} id Field number
  7728. * @param {*} value Field value
  7729. * @param {ByteBuffer} buffer ByteBuffer to encode to
  7730. * @return {ByteBuffer} The ByteBuffer for chaining
  7731. * @throws {Error} If the value cannot be encoded
  7732. * @expose
  7733. */
  7734. ElementPrototype.encodeValue = function(id, value, buffer) {
  7735. if (value === null) return buffer; // Nothing to encode
  7736. // Tag has already been written
  7737. switch (this.type) {
  7738. // 32bit signed varint
  7739. case ProtoBuf.TYPES["int32"]:
  7740. // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
  7741. // long – it is, effectively, treated like a very large unsigned integer." (see #122)
  7742. if (value < 0)
  7743. buffer.writeVarint64(value);
  7744. else
  7745. buffer.writeVarint32(value);
  7746. break;
  7747. // 32bit unsigned varint
  7748. case ProtoBuf.TYPES["uint32"]:
  7749. buffer.writeVarint32(value);
  7750. break;
  7751. // 32bit varint zig-zag
  7752. case ProtoBuf.TYPES["sint32"]:
  7753. buffer.writeVarint32ZigZag(value);
  7754. break;
  7755. // Fixed unsigned 32bit
  7756. case ProtoBuf.TYPES["fixed32"]:
  7757. buffer.writeUint32(value);
  7758. break;
  7759. // Fixed signed 32bit
  7760. case ProtoBuf.TYPES["sfixed32"]:
  7761. buffer.writeInt32(value);
  7762. break;
  7763. // 64bit varint as-is
  7764. case ProtoBuf.TYPES["int64"]:
  7765. case ProtoBuf.TYPES["uint64"]:
  7766. buffer.writeVarint64(value); // throws
  7767. break;
  7768. // 64bit varint zig-zag
  7769. case ProtoBuf.TYPES["sint64"]:
  7770. buffer.writeVarint64ZigZag(value); // throws
  7771. break;
  7772. // Fixed unsigned 64bit
  7773. case ProtoBuf.TYPES["fixed64"]:
  7774. buffer.writeUint64(value); // throws
  7775. break;
  7776. // Fixed signed 64bit
  7777. case ProtoBuf.TYPES["sfixed64"]:
  7778. buffer.writeInt64(value); // throws
  7779. break;
  7780. // Bool
  7781. case ProtoBuf.TYPES["bool"]:
  7782. if (typeof value === 'string')
  7783. buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
  7784. else
  7785. buffer.writeVarint32(value ? 1 : 0);
  7786. break;
  7787. // Constant enum value
  7788. case ProtoBuf.TYPES["enum"]:
  7789. buffer.writeVarint32(value);
  7790. break;
  7791. // 32bit float
  7792. case ProtoBuf.TYPES["float"]:
  7793. buffer.writeFloat32(value);
  7794. break;
  7795. // 64bit float
  7796. case ProtoBuf.TYPES["double"]:
  7797. buffer.writeFloat64(value);
  7798. break;
  7799. // Length-delimited string
  7800. case ProtoBuf.TYPES["string"]:
  7801. buffer.writeVString(value);
  7802. break;
  7803. // Length-delimited bytes
  7804. case ProtoBuf.TYPES["bytes"]:
  7805. if (value.remaining() < 0)
  7806. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  7807. var prevOffset = value.offset;
  7808. buffer.writeVarint32(value.remaining());
  7809. buffer.append(value);
  7810. value.offset = prevOffset;
  7811. break;
  7812. // Embedded message
  7813. case ProtoBuf.TYPES["message"]:
  7814. var bb = new ByteBuffer().LE();
  7815. this.resolvedType.encode(value, bb);
  7816. buffer.writeVarint32(bb.offset);
  7817. buffer.append(bb.flip());
  7818. break;
  7819. // Legacy group
  7820. case ProtoBuf.TYPES["group"]:
  7821. this.resolvedType.encode(value, buffer);
  7822. buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  7823. break;
  7824. default:
  7825. // We should never end here
  7826. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  7827. }
  7828. return buffer;
  7829. };
  7830. /**
  7831. * Decode one element value from the specified buffer.
  7832. * @param {ByteBuffer} buffer ByteBuffer to decode from
  7833. * @param {number} wireType The field wire type
  7834. * @param {number} id The field number
  7835. * @return {*} Decoded value
  7836. * @throws {Error} If the field cannot be decoded
  7837. * @expose
  7838. */
  7839. ElementPrototype.decode = function(buffer, wireType, id) {
  7840. if (wireType != this.type.wireType)
  7841. throw Error("Unexpected wire type for element");
  7842. var value, nBytes;
  7843. switch (this.type) {
  7844. // 32bit signed varint
  7845. case ProtoBuf.TYPES["int32"]:
  7846. return buffer.readVarint32() | 0;
  7847. // 32bit unsigned varint
  7848. case ProtoBuf.TYPES["uint32"]:
  7849. return buffer.readVarint32() >>> 0;
  7850. // 32bit signed varint zig-zag
  7851. case ProtoBuf.TYPES["sint32"]:
  7852. return buffer.readVarint32ZigZag() | 0;
  7853. // Fixed 32bit unsigned
  7854. case ProtoBuf.TYPES["fixed32"]:
  7855. return buffer.readUint32() >>> 0;
  7856. case ProtoBuf.TYPES["sfixed32"]:
  7857. return buffer.readInt32() | 0;
  7858. // 64bit signed varint
  7859. case ProtoBuf.TYPES["int64"]:
  7860. return buffer.readVarint64();
  7861. // 64bit unsigned varint
  7862. case ProtoBuf.TYPES["uint64"]:
  7863. return buffer.readVarint64().toUnsigned();
  7864. // 64bit signed varint zig-zag
  7865. case ProtoBuf.TYPES["sint64"]:
  7866. return buffer.readVarint64ZigZag();
  7867. // Fixed 64bit unsigned
  7868. case ProtoBuf.TYPES["fixed64"]:
  7869. return buffer.readUint64();
  7870. // Fixed 64bit signed
  7871. case ProtoBuf.TYPES["sfixed64"]:
  7872. return buffer.readInt64();
  7873. // Bool varint
  7874. case ProtoBuf.TYPES["bool"]:
  7875. return !!buffer.readVarint32();
  7876. // Constant enum value (varint)
  7877. case ProtoBuf.TYPES["enum"]:
  7878. // The following Builder.Message#set will already throw
  7879. return buffer.readVarint32();
  7880. // 32bit float
  7881. case ProtoBuf.TYPES["float"]:
  7882. return buffer.readFloat();
  7883. // 64bit float
  7884. case ProtoBuf.TYPES["double"]:
  7885. return buffer.readDouble();
  7886. // Length-delimited string
  7887. case ProtoBuf.TYPES["string"]:
  7888. return buffer.readVString();
  7889. // Length-delimited bytes
  7890. case ProtoBuf.TYPES["bytes"]: {
  7891. nBytes = buffer.readVarint32();
  7892. if (buffer.remaining() < nBytes)
  7893. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  7894. value = buffer.clone(); // Offset already set
  7895. value.limit = value.offset+nBytes;
  7896. buffer.offset += nBytes;
  7897. return value;
  7898. }
  7899. // Length-delimited embedded message
  7900. case ProtoBuf.TYPES["message"]: {
  7901. nBytes = buffer.readVarint32();
  7902. return this.resolvedType.decode(buffer, nBytes);
  7903. }
  7904. // Legacy group
  7905. case ProtoBuf.TYPES["group"]:
  7906. return this.resolvedType.decode(buffer, -1, id);
  7907. }
  7908. // We should never end here
  7909. throw Error("[INTERNAL] Illegal decode type");
  7910. };
  7911. /**
  7912. * Converts a value from a string to the canonical element type.
  7913. *
  7914. * Legal only when isMapKey is true.
  7915. *
  7916. * @param {string} str The string value
  7917. * @returns {*} The value
  7918. */
  7919. ElementPrototype.valueFromString = function(str) {
  7920. if (!this.isMapKey) {
  7921. throw Error("valueFromString() called on non-map-key element");
  7922. }
  7923. switch (this.type) {
  7924. case ProtoBuf.TYPES["int32"]:
  7925. case ProtoBuf.TYPES["sint32"]:
  7926. case ProtoBuf.TYPES["sfixed32"]:
  7927. case ProtoBuf.TYPES["uint32"]:
  7928. case ProtoBuf.TYPES["fixed32"]:
  7929. return this.verifyValue(parseInt(str));
  7930. case ProtoBuf.TYPES["int64"]:
  7931. case ProtoBuf.TYPES["sint64"]:
  7932. case ProtoBuf.TYPES["sfixed64"]:
  7933. case ProtoBuf.TYPES["uint64"]:
  7934. case ProtoBuf.TYPES["fixed64"]:
  7935. // Long-based fields support conversions from string already.
  7936. return this.verifyValue(str);
  7937. case ProtoBuf.TYPES["bool"]:
  7938. return str === "true";
  7939. case ProtoBuf.TYPES["string"]:
  7940. return this.verifyValue(str);
  7941. case ProtoBuf.TYPES["bytes"]:
  7942. return ByteBuffer.fromBinary(str);
  7943. }
  7944. };
  7945. /**
  7946. * Converts a value from the canonical element type to a string.
  7947. *
  7948. * It should be the case that `valueFromString(valueToString(val))` returns
  7949. * a value equivalent to `verifyValue(val)` for every legal value of `val`
  7950. * according to this element type.
  7951. *
  7952. * This may be used when the element must be stored or used as a string,
  7953. * e.g., as a map key on an Object.
  7954. *
  7955. * Legal only when isMapKey is true.
  7956. *
  7957. * @param {*} val The value
  7958. * @returns {string} The string form of the value.
  7959. */
  7960. ElementPrototype.valueToString = function(value) {
  7961. if (!this.isMapKey) {
  7962. throw Error("valueToString() called on non-map-key element");
  7963. }
  7964. if (this.type === ProtoBuf.TYPES["bytes"]) {
  7965. return value.toString("binary");
  7966. } else {
  7967. return value.toString();
  7968. }
  7969. };
  7970. /**
  7971. * @alias ProtoBuf.Reflect.Element
  7972. * @expose
  7973. */
  7974. Reflect.Element = Element;
  7975. /**
  7976. * Constructs a new Message.
  7977. * @exports ProtoBuf.Reflect.Message
  7978. * @param {!ProtoBuf.Builder} builder Builder reference
  7979. * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
  7980. * @param {string} name Message name
  7981. * @param {Object.<string,*>=} options Message options
  7982. * @param {boolean=} isGroup `true` if this is a legacy group
  7983. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  7984. * @constructor
  7985. * @extends ProtoBuf.Reflect.Namespace
  7986. */
  7987. var Message = function(builder, parent, name, options, isGroup, syntax) {
  7988. Namespace.call(this, builder, parent, name, options, syntax);
  7989. /**
  7990. * @override
  7991. */
  7992. this.className = "Message";
  7993. /**
  7994. * Extensions range.
  7995. * @type {!Array.<number>|undefined}
  7996. * @expose
  7997. */
  7998. this.extensions = undefined;
  7999. /**
  8000. * Runtime message class.
  8001. * @type {?function(new:ProtoBuf.Builder.Message)}
  8002. * @expose
  8003. */
  8004. this.clazz = null;
  8005. /**
  8006. * Whether this is a legacy group or not.
  8007. * @type {boolean}
  8008. * @expose
  8009. */
  8010. this.isGroup = !!isGroup;
  8011. // The following cached collections are used to efficiently iterate over or look up fields when decoding.
  8012. /**
  8013. * Cached fields.
  8014. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
  8015. * @private
  8016. */
  8017. this._fields = null;
  8018. /**
  8019. * Cached fields by id.
  8020. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
  8021. * @private
  8022. */
  8023. this._fieldsById = null;
  8024. /**
  8025. * Cached fields by name.
  8026. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
  8027. * @private
  8028. */
  8029. this._fieldsByName = null;
  8030. };
  8031. /**
  8032. * @alias ProtoBuf.Reflect.Message.prototype
  8033. * @inner
  8034. */
  8035. var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
  8036. /**
  8037. * Builds the message and returns the runtime counterpart, which is a fully functional class.
  8038. * @see ProtoBuf.Builder.Message
  8039. * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
  8040. * @return {ProtoBuf.Reflect.Message} Message class
  8041. * @throws {Error} If the message cannot be built
  8042. * @expose
  8043. */
  8044. MessagePrototype.build = function(rebuild) {
  8045. if (this.clazz && !rebuild)
  8046. return this.clazz;
  8047. // Create the runtime Message class in its own scope
  8048. var clazz = (function(ProtoBuf, T) {
  8049. var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
  8050. oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
  8051. /**
  8052. * Constructs a new runtime Message.
  8053. * @name ProtoBuf.Builder.Message
  8054. * @class Barebone of all runtime messages.
  8055. * @param {!Object.<string,*>|string} values Preset values
  8056. * @param {...string} var_args
  8057. * @constructor
  8058. * @throws {Error} If the message cannot be created
  8059. */
  8060. var Message = function(values, var_args) {
  8061. ProtoBuf.Builder.Message.call(this);
  8062. // Create virtual oneof properties
  8063. for (var i=0, k=oneofs.length; i<k; ++i)
  8064. this[oneofs[i].name] = null;
  8065. // Create fields and set default values
  8066. for (i=0, k=fields.length; i<k; ++i) {
  8067. var field = fields[i];
  8068. this[field.name] =
  8069. field.repeated ? [] :
  8070. (field.map ? new ProtoBuf.Map(field) : null);
  8071. if ((field.required || T.syntax === 'proto3') &&
  8072. field.defaultValue !== null)
  8073. this[field.name] = field.defaultValue;
  8074. }
  8075. if (arguments.length > 0) {
  8076. var value;
  8077. // Set field values from a values object
  8078. if (arguments.length === 1 && values !== null && typeof values === 'object' &&
  8079. /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
  8080. /* not a repeated field */ !Array.isArray(values) &&
  8081. /* not a Map */ !(values instanceof ProtoBuf.Map) &&
  8082. /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
  8083. /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
  8084. /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
  8085. this.$set(values);
  8086. } else // Set field values from arguments, in declaration order
  8087. for (i=0, k=arguments.length; i<k; ++i)
  8088. if (typeof (value = arguments[i]) !== 'undefined')
  8089. this.$set(fields[i].name, value); // May throw
  8090. }
  8091. };
  8092. /**
  8093. * @alias ProtoBuf.Builder.Message.prototype
  8094. * @inner
  8095. */
  8096. var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
  8097. /**
  8098. * Adds a value to a repeated field.
  8099. * @name ProtoBuf.Builder.Message#add
  8100. * @function
  8101. * @param {string} key Field name
  8102. * @param {*} value Value to add
  8103. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  8104. * @returns {!ProtoBuf.Builder.Message} this
  8105. * @throws {Error} If the value cannot be added
  8106. * @expose
  8107. */
  8108. MessagePrototype.add = function(key, value, noAssert) {
  8109. var field = T._fieldsByName[key];
  8110. if (!noAssert) {
  8111. if (!field)
  8112. throw Error(this+"#"+key+" is undefined");
  8113. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  8114. throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
  8115. if (!field.repeated)
  8116. throw Error(this+"#"+key+" is not a repeated field");
  8117. value = field.verifyValue(value, true);
  8118. }
  8119. if (this[key] === null)
  8120. this[key] = [];
  8121. this[key].push(value);
  8122. return this;
  8123. };
  8124. /**
  8125. * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
  8126. * @name ProtoBuf.Builder.Message#$add
  8127. * @function
  8128. * @param {string} key Field name
  8129. * @param {*} value Value to add
  8130. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  8131. * @returns {!ProtoBuf.Builder.Message} this
  8132. * @throws {Error} If the value cannot be added
  8133. * @expose
  8134. */
  8135. MessagePrototype.$add = MessagePrototype.add;
  8136. /**
  8137. * Sets a field's value.
  8138. * @name ProtoBuf.Builder.Message#set
  8139. * @function
  8140. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  8141. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  8142. * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
  8143. * @returns {!ProtoBuf.Builder.Message} this
  8144. * @throws {Error} If the value cannot be set
  8145. * @expose
  8146. */
  8147. MessagePrototype.set = function(keyOrObj, value, noAssert) {
  8148. if (keyOrObj && typeof keyOrObj === 'object') {
  8149. noAssert = value;
  8150. for (var ikey in keyOrObj) {
  8151. // Check if virtual oneof field - don't set these
  8152. if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
  8153. this.$set(ikey, value, noAssert);
  8154. }
  8155. return this;
  8156. }
  8157. var field = T._fieldsByName[keyOrObj];
  8158. if (!noAssert) {
  8159. if (!field)
  8160. throw Error(this+"#"+keyOrObj+" is not a field: undefined");
  8161. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  8162. throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
  8163. this[field.name] = (value = field.verifyValue(value)); // May throw
  8164. } else
  8165. this[keyOrObj] = value;
  8166. if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  8167. var currentField = this[field.oneof.name]; // Virtual field references currently set field
  8168. if (value !== null) {
  8169. if (currentField !== null && currentField !== field.name)
  8170. this[currentField] = null; // Clear currently set field
  8171. this[field.oneof.name] = field.name; // Point virtual field at this field
  8172. } else if (/* value === null && */currentField === keyOrObj)
  8173. this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
  8174. }
  8175. return this;
  8176. };
  8177. /**
  8178. * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
  8179. * @name ProtoBuf.Builder.Message#$set
  8180. * @function
  8181. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  8182. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  8183. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  8184. * @throws {Error} If the value cannot be set
  8185. * @expose
  8186. */
  8187. MessagePrototype.$set = MessagePrototype.set;
  8188. /**
  8189. * Gets a field's value.
  8190. * @name ProtoBuf.Builder.Message#get
  8191. * @function
  8192. * @param {string} key Key
  8193. * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
  8194. * @return {*} Value
  8195. * @throws {Error} If there is no such field
  8196. * @expose
  8197. */
  8198. MessagePrototype.get = function(key, noAssert) {
  8199. if (noAssert)
  8200. return this[key];
  8201. var field = T._fieldsByName[key];
  8202. if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
  8203. throw Error(this+"#"+key+" is not a field: undefined");
  8204. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  8205. throw Error(this+"#"+key+" is not a field: "+field.toString(true));
  8206. return this[field.name];
  8207. };
  8208. /**
  8209. * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
  8210. * @name ProtoBuf.Builder.Message#$get
  8211. * @function
  8212. * @param {string} key Key
  8213. * @return {*} Value
  8214. * @throws {Error} If there is no such field
  8215. * @expose
  8216. */
  8217. MessagePrototype.$get = MessagePrototype.get;
  8218. // Getters and setters
  8219. for (var i=0; i<fields.length; i++) {
  8220. var field = fields[i];
  8221. // no setters for extension fields as these are named by their fqn
  8222. if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
  8223. continue;
  8224. if (T.builder.options['populateAccessors'])
  8225. (function(field) {
  8226. // set/get[SomeValue]
  8227. var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
  8228. return match.toUpperCase().replace('_','');
  8229. });
  8230. Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
  8231. // set/get_[some_value] FIXME: Do we really need these?
  8232. var name = field.originalName.replace(/([A-Z])/g, function(match) {
  8233. return "_"+match;
  8234. });
  8235. /**
  8236. * The current field's unbound setter function.
  8237. * @function
  8238. * @param {*} value
  8239. * @param {boolean=} noAssert
  8240. * @returns {!ProtoBuf.Builder.Message}
  8241. * @inner
  8242. */
  8243. var setter = function(value, noAssert) {
  8244. this[field.name] = noAssert ? value : field.verifyValue(value);
  8245. return this;
  8246. };
  8247. /**
  8248. * The current field's unbound getter function.
  8249. * @function
  8250. * @returns {*}
  8251. * @inner
  8252. */
  8253. var getter = function() {
  8254. return this[field.name];
  8255. };
  8256. if (T.getChild("set"+Name) === null)
  8257. /**
  8258. * Sets a value. This method is present for each field, but only if there is no name conflict with
  8259. * another field.
  8260. * @name ProtoBuf.Builder.Message#set[SomeField]
  8261. * @function
  8262. * @param {*} value Value to set
  8263. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  8264. * @returns {!ProtoBuf.Builder.Message} this
  8265. * @abstract
  8266. * @throws {Error} If the value cannot be set
  8267. */
  8268. MessagePrototype["set"+Name] = setter;
  8269. if (T.getChild("set_"+name) === null)
  8270. /**
  8271. * Sets a value. This method is present for each field, but only if there is no name conflict with
  8272. * another field.
  8273. * @name ProtoBuf.Builder.Message#set_[some_field]
  8274. * @function
  8275. * @param {*} value Value to set
  8276. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  8277. * @returns {!ProtoBuf.Builder.Message} this
  8278. * @abstract
  8279. * @throws {Error} If the value cannot be set
  8280. */
  8281. MessagePrototype["set_"+name] = setter;
  8282. if (T.getChild("get"+Name) === null)
  8283. /**
  8284. * Gets a value. This method is present for each field, but only if there is no name conflict with
  8285. * another field.
  8286. * @name ProtoBuf.Builder.Message#get[SomeField]
  8287. * @function
  8288. * @abstract
  8289. * @return {*} The value
  8290. */
  8291. MessagePrototype["get"+Name] = getter;
  8292. if (T.getChild("get_"+name) === null)
  8293. /**
  8294. * Gets a value. This method is present for each field, but only if there is no name conflict with
  8295. * another field.
  8296. * @name ProtoBuf.Builder.Message#get_[some_field]
  8297. * @function
  8298. * @return {*} The value
  8299. * @abstract
  8300. */
  8301. MessagePrototype["get_"+name] = getter;
  8302. })(field);
  8303. }
  8304. // En-/decoding
  8305. /**
  8306. * Encodes the message.
  8307. * @name ProtoBuf.Builder.Message#$encode
  8308. * @function
  8309. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  8310. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  8311. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  8312. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8313. * returns the encoded ByteBuffer in the `encoded` property on the error.
  8314. * @expose
  8315. * @see ProtoBuf.Builder.Message#encode64
  8316. * @see ProtoBuf.Builder.Message#encodeHex
  8317. * @see ProtoBuf.Builder.Message#encodeAB
  8318. */
  8319. MessagePrototype.encode = function(buffer, noVerify) {
  8320. if (typeof buffer === 'boolean')
  8321. noVerify = buffer,
  8322. buffer = undefined;
  8323. var isNew = false;
  8324. if (!buffer)
  8325. buffer = new ByteBuffer(),
  8326. isNew = true;
  8327. var le = buffer.littleEndian;
  8328. try {
  8329. T.encode(this, buffer.LE(), noVerify);
  8330. return (isNew ? buffer.flip() : buffer).LE(le);
  8331. } catch (e) {
  8332. buffer.LE(le);
  8333. throw(e);
  8334. }
  8335. };
  8336. /**
  8337. * Encodes a message using the specified data payload.
  8338. * @param {!Object.<string,*>} data Data payload
  8339. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  8340. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  8341. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  8342. * @expose
  8343. */
  8344. Message.encode = function(data, buffer, noVerify) {
  8345. return new Message(data).encode(buffer, noVerify);
  8346. };
  8347. /**
  8348. * Calculates the byte length of the message.
  8349. * @name ProtoBuf.Builder.Message#calculate
  8350. * @function
  8351. * @returns {number} Byte length
  8352. * @throws {Error} If the message cannot be calculated or if required fields are missing.
  8353. * @expose
  8354. */
  8355. MessagePrototype.calculate = function() {
  8356. return T.calculate(this);
  8357. };
  8358. /**
  8359. * Encodes the varint32 length-delimited message.
  8360. * @name ProtoBuf.Builder.Message#encodeDelimited
  8361. * @function
  8362. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  8363. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  8364. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  8365. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8366. * returns the encoded ByteBuffer in the `encoded` property on the error.
  8367. * @expose
  8368. */
  8369. MessagePrototype.encodeDelimited = function(buffer, noVerify) {
  8370. var isNew = false;
  8371. if (!buffer)
  8372. buffer = new ByteBuffer(),
  8373. isNew = true;
  8374. var enc = new ByteBuffer().LE();
  8375. T.encode(this, enc, noVerify).flip();
  8376. buffer.writeVarint32(enc.remaining());
  8377. buffer.append(enc);
  8378. return isNew ? buffer.flip() : buffer;
  8379. };
  8380. /**
  8381. * Directly encodes the message to an ArrayBuffer.
  8382. * @name ProtoBuf.Builder.Message#encodeAB
  8383. * @function
  8384. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  8385. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8386. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  8387. * @expose
  8388. */
  8389. MessagePrototype.encodeAB = function() {
  8390. try {
  8391. return this.encode().toArrayBuffer();
  8392. } catch (e) {
  8393. if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
  8394. throw(e);
  8395. }
  8396. };
  8397. /**
  8398. * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
  8399. * @name ProtoBuf.Builder.Message#toArrayBuffer
  8400. * @function
  8401. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  8402. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8403. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  8404. * @expose
  8405. */
  8406. MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
  8407. /**
  8408. * Directly encodes the message to a node Buffer.
  8409. * @name ProtoBuf.Builder.Message#encodeNB
  8410. * @function
  8411. * @return {!Buffer}
  8412. * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
  8413. * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
  8414. * @expose
  8415. */
  8416. MessagePrototype.encodeNB = function() {
  8417. try {
  8418. return this.encode().toBuffer();
  8419. } catch (e) {
  8420. if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
  8421. throw(e);
  8422. }
  8423. };
  8424. /**
  8425. * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
  8426. * @name ProtoBuf.Builder.Message#toBuffer
  8427. * @function
  8428. * @return {!Buffer}
  8429. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8430. * returns the encoded node Buffer in the `encoded` property on the error.
  8431. * @expose
  8432. */
  8433. MessagePrototype.toBuffer = MessagePrototype.encodeNB;
  8434. /**
  8435. * Directly encodes the message to a base64 encoded string.
  8436. * @name ProtoBuf.Builder.Message#encode64
  8437. * @function
  8438. * @return {string} Base64 encoded string
  8439. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  8440. * still returns the encoded base64 string in the `encoded` property on the error.
  8441. * @expose
  8442. */
  8443. MessagePrototype.encode64 = function() {
  8444. try {
  8445. return this.encode().toBase64();
  8446. } catch (e) {
  8447. if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
  8448. throw(e);
  8449. }
  8450. };
  8451. /**
  8452. * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
  8453. * @name ProtoBuf.Builder.Message#toBase64
  8454. * @function
  8455. * @return {string} Base64 encoded string
  8456. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8457. * returns the encoded base64 string in the `encoded` property on the error.
  8458. * @expose
  8459. */
  8460. MessagePrototype.toBase64 = MessagePrototype.encode64;
  8461. /**
  8462. * Directly encodes the message to a hex encoded string.
  8463. * @name ProtoBuf.Builder.Message#encodeHex
  8464. * @function
  8465. * @return {string} Hex encoded string
  8466. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  8467. * still returns the encoded hex string in the `encoded` property on the error.
  8468. * @expose
  8469. */
  8470. MessagePrototype.encodeHex = function() {
  8471. try {
  8472. return this.encode().toHex();
  8473. } catch (e) {
  8474. if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
  8475. throw(e);
  8476. }
  8477. };
  8478. /**
  8479. * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
  8480. * @name ProtoBuf.Builder.Message#toHex
  8481. * @function
  8482. * @return {string} Hex encoded string
  8483. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  8484. * returns the encoded hex string in the `encoded` property on the error.
  8485. * @expose
  8486. */
  8487. MessagePrototype.toHex = MessagePrototype.encodeHex;
  8488. /**
  8489. * Clones a message object or field value to a raw object.
  8490. * @param {*} obj Object to clone
  8491. * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
  8492. * @param {boolean} longsAsStrings Whether to encode longs as strings
  8493. * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
  8494. * @returns {*} Cloned object
  8495. * @inner
  8496. */
  8497. function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
  8498. if (obj === null || typeof obj !== 'object') {
  8499. // Convert enum values to their respective names
  8500. if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
  8501. var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
  8502. if (name !== null)
  8503. return name;
  8504. }
  8505. // Pass-through string, number, boolean, null...
  8506. return obj;
  8507. }
  8508. // Convert ByteBuffers to raw buffer or strings
  8509. if (ByteBuffer.isByteBuffer(obj))
  8510. return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
  8511. // Convert Longs to proper objects or strings
  8512. if (ProtoBuf.Long.isLong(obj))
  8513. return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
  8514. var clone;
  8515. // Clone arrays
  8516. if (Array.isArray(obj)) {
  8517. clone = [];
  8518. obj.forEach(function(v, k) {
  8519. clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
  8520. });
  8521. return clone;
  8522. }
  8523. clone = {};
  8524. // Convert maps to objects
  8525. if (obj instanceof ProtoBuf.Map) {
  8526. var it = obj.entries();
  8527. for (var e = it.next(); !e.done; e = it.next())
  8528. clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
  8529. return clone;
  8530. }
  8531. // Everything else is a non-null object
  8532. var type = obj.$type,
  8533. field = undefined;
  8534. for (var i in obj)
  8535. if (obj.hasOwnProperty(i)) {
  8536. if (type && (field = type.getChild(i)))
  8537. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
  8538. else
  8539. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
  8540. }
  8541. return clone;
  8542. }
  8543. /**
  8544. * Returns the message's raw payload.
  8545. * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
  8546. * @param {boolean} longsAsStrings Whether to encode longs as strings
  8547. * @returns {Object.<string,*>} Raw payload
  8548. * @expose
  8549. */
  8550. MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
  8551. return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
  8552. };
  8553. /**
  8554. * Encodes a message to JSON.
  8555. * @returns {string} JSON string
  8556. * @expose
  8557. */
  8558. MessagePrototype.encodeJSON = function() {
  8559. return JSON.stringify(
  8560. cloneRaw(this,
  8561. /* binary-as-base64 */ true,
  8562. /* longs-as-strings */ true,
  8563. this.$type
  8564. )
  8565. );
  8566. };
  8567. /**
  8568. * Decodes a message from the specified buffer or string.
  8569. * @name ProtoBuf.Builder.Message.decode
  8570. * @function
  8571. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  8572. * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
  8573. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  8574. * @return {!ProtoBuf.Builder.Message} Decoded message
  8575. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  8576. * returns the decoded message with missing fields in the `decoded` property on the error.
  8577. * @expose
  8578. * @see ProtoBuf.Builder.Message.decode64
  8579. * @see ProtoBuf.Builder.Message.decodeHex
  8580. */
  8581. Message.decode = function(buffer, length, enc) {
  8582. if (typeof length === 'string')
  8583. enc = length,
  8584. length = -1;
  8585. if (typeof buffer === 'string')
  8586. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  8587. else if (!ByteBuffer.isByteBuffer(buffer))
  8588. buffer = ByteBuffer.wrap(buffer); // May throw
  8589. var le = buffer.littleEndian;
  8590. try {
  8591. var msg = T.decode(buffer.LE(), length);
  8592. buffer.LE(le);
  8593. return msg;
  8594. } catch (e) {
  8595. buffer.LE(le);
  8596. throw(e);
  8597. }
  8598. };
  8599. /**
  8600. * Decodes a varint32 length-delimited message from the specified buffer or string.
  8601. * @name ProtoBuf.Builder.Message.decodeDelimited
  8602. * @function
  8603. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  8604. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  8605. * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
  8606. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  8607. * returns the decoded message with missing fields in the `decoded` property on the error.
  8608. * @expose
  8609. */
  8610. Message.decodeDelimited = function(buffer, enc) {
  8611. if (typeof buffer === 'string')
  8612. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  8613. else if (!ByteBuffer.isByteBuffer(buffer))
  8614. buffer = ByteBuffer.wrap(buffer); // May throw
  8615. if (buffer.remaining() < 1)
  8616. return null;
  8617. var off = buffer.offset,
  8618. len = buffer.readVarint32();
  8619. if (buffer.remaining() < len) {
  8620. buffer.offset = off;
  8621. return null;
  8622. }
  8623. try {
  8624. var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
  8625. buffer.offset += len;
  8626. return msg;
  8627. } catch (err) {
  8628. buffer.offset += len;
  8629. throw err;
  8630. }
  8631. };
  8632. /**
  8633. * Decodes the message from the specified base64 encoded string.
  8634. * @name ProtoBuf.Builder.Message.decode64
  8635. * @function
  8636. * @param {string} str String to decode from
  8637. * @return {!ProtoBuf.Builder.Message} Decoded message
  8638. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  8639. * returns the decoded message with missing fields in the `decoded` property on the error.
  8640. * @expose
  8641. */
  8642. Message.decode64 = function(str) {
  8643. return Message.decode(str, "base64");
  8644. };
  8645. /**
  8646. * Decodes the message from the specified hex encoded string.
  8647. * @name ProtoBuf.Builder.Message.decodeHex
  8648. * @function
  8649. * @param {string} str String to decode from
  8650. * @return {!ProtoBuf.Builder.Message} Decoded message
  8651. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  8652. * returns the decoded message with missing fields in the `decoded` property on the error.
  8653. * @expose
  8654. */
  8655. Message.decodeHex = function(str) {
  8656. return Message.decode(str, "hex");
  8657. };
  8658. /**
  8659. * Decodes the message from a JSON string.
  8660. * @name ProtoBuf.Builder.Message.decodeJSON
  8661. * @function
  8662. * @param {string} str String to decode from
  8663. * @return {!ProtoBuf.Builder.Message} Decoded message
  8664. * @throws {Error} If the message cannot be decoded or if required fields are
  8665. * missing.
  8666. * @expose
  8667. */
  8668. Message.decodeJSON = function(str) {
  8669. return new Message(JSON.parse(str));
  8670. };
  8671. // Utility
  8672. /**
  8673. * Returns a string representation of this Message.
  8674. * @name ProtoBuf.Builder.Message#toString
  8675. * @function
  8676. * @return {string} String representation as of ".Fully.Qualified.MessageName"
  8677. * @expose
  8678. */
  8679. MessagePrototype.toString = function() {
  8680. return T.toString();
  8681. };
  8682. if (Object.defineProperty)
  8683. Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
  8684. Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
  8685. Object.defineProperty(Message, "$type", { "value": T }),
  8686. Object.defineProperty(MessagePrototype, "$type", { "value": T });
  8687. return Message;
  8688. })(ProtoBuf, this);
  8689. // Static enums and prototyped sub-messages / cached collections
  8690. this._fields = [];
  8691. this._fieldsById = {};
  8692. this._fieldsByName = {};
  8693. this._oneofsByName = {};
  8694. for (var i=0, k=this.children.length, child; i<k; i++) {
  8695. child = this.children[i];
  8696. if (child instanceof Enum || child instanceof Message || child instanceof Service) {
  8697. if (clazz.hasOwnProperty(child.name))
  8698. throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
  8699. clazz[child.name] = child.build();
  8700. } else if (child instanceof Message.Field)
  8701. child.build(),
  8702. this._fields.push(child),
  8703. this._fieldsById[child.id] = child,
  8704. this._fieldsByName[child.name] = child;
  8705. else if (child instanceof Message.OneOf) {
  8706. this._oneofsByName[child.name] = child;
  8707. }
  8708. else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
  8709. throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
  8710. }
  8711. return this.clazz = clazz;
  8712. };
  8713. /**
  8714. * Encodes a runtime message's contents to the specified buffer.
  8715. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  8716. * @param {ByteBuffer} buffer ByteBuffer to write to
  8717. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  8718. * @return {ByteBuffer} The ByteBuffer for chaining
  8719. * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
  8720. * @expose
  8721. */
  8722. MessagePrototype.encode = function(message, buffer, noVerify) {
  8723. var fieldMissing = null,
  8724. field;
  8725. for (var i=0, k=this._fields.length, val; i<k; ++i) {
  8726. field = this._fields[i];
  8727. val = message[field.name];
  8728. if (field.required && val === null) {
  8729. if (fieldMissing === null)
  8730. fieldMissing = field;
  8731. } else
  8732. field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
  8733. }
  8734. if (fieldMissing !== null) {
  8735. var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
  8736. err["encoded"] = buffer; // Still expose what we got
  8737. throw(err);
  8738. }
  8739. return buffer;
  8740. };
  8741. /**
  8742. * Calculates a runtime message's byte length.
  8743. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  8744. * @returns {number} Byte length
  8745. * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
  8746. * @expose
  8747. */
  8748. MessagePrototype.calculate = function(message) {
  8749. for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
  8750. field = this._fields[i];
  8751. val = message[field.name];
  8752. if (field.required && val === null)
  8753. throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
  8754. else
  8755. n += field.calculate(val, message);
  8756. }
  8757. return n;
  8758. };
  8759. /**
  8760. * Skips all data until the end of the specified group has been reached.
  8761. * @param {number} expectedId Expected GROUPEND id
  8762. * @param {!ByteBuffer} buf ByteBuffer
  8763. * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
  8764. * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
  8765. * @inner
  8766. */
  8767. function skipTillGroupEnd(expectedId, buf) {
  8768. var tag = buf.readVarint32(), // Throws on OOB
  8769. wireType = tag & 0x07,
  8770. id = tag >>> 3;
  8771. switch (wireType) {
  8772. case ProtoBuf.WIRE_TYPES.VARINT:
  8773. do tag = buf.readUint8();
  8774. while ((tag & 0x80) === 0x80);
  8775. break;
  8776. case ProtoBuf.WIRE_TYPES.BITS64:
  8777. buf.offset += 8;
  8778. break;
  8779. case ProtoBuf.WIRE_TYPES.LDELIM:
  8780. tag = buf.readVarint32(); // reads the varint
  8781. buf.offset += tag; // skips n bytes
  8782. break;
  8783. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  8784. skipTillGroupEnd(id, buf);
  8785. break;
  8786. case ProtoBuf.WIRE_TYPES.ENDGROUP:
  8787. if (id === expectedId)
  8788. return false;
  8789. else
  8790. throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
  8791. case ProtoBuf.WIRE_TYPES.BITS32:
  8792. buf.offset += 4;
  8793. break;
  8794. default:
  8795. throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
  8796. }
  8797. return true;
  8798. }
  8799. /**
  8800. * Decodes an encoded message and returns the decoded message.
  8801. * @param {ByteBuffer} buffer ByteBuffer to decode from
  8802. * @param {number=} length Message length. Defaults to decode all remaining data.
  8803. * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
  8804. * @return {ProtoBuf.Builder.Message} Decoded message
  8805. * @throws {Error} If the message cannot be decoded
  8806. * @expose
  8807. */
  8808. MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
  8809. if (typeof length !== 'number')
  8810. length = -1;
  8811. var start = buffer.offset,
  8812. msg = new (this.clazz)(),
  8813. tag, wireType, id, field;
  8814. while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
  8815. tag = buffer.readVarint32();
  8816. wireType = tag & 0x07;
  8817. id = tag >>> 3;
  8818. if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
  8819. if (id !== expectedGroupEndId)
  8820. throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
  8821. break;
  8822. }
  8823. if (!(field = this._fieldsById[id])) {
  8824. // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
  8825. switch (wireType) {
  8826. case ProtoBuf.WIRE_TYPES.VARINT:
  8827. buffer.readVarint32();
  8828. break;
  8829. case ProtoBuf.WIRE_TYPES.BITS32:
  8830. buffer.offset += 4;
  8831. break;
  8832. case ProtoBuf.WIRE_TYPES.BITS64:
  8833. buffer.offset += 8;
  8834. break;
  8835. case ProtoBuf.WIRE_TYPES.LDELIM:
  8836. var len = buffer.readVarint32();
  8837. buffer.offset += len;
  8838. break;
  8839. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  8840. while (skipTillGroupEnd(id, buffer)) {}
  8841. break;
  8842. default:
  8843. throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
  8844. }
  8845. continue;
  8846. }
  8847. if (field.repeated && !field.options["packed"]) {
  8848. msg[field.name].push(field.decode(wireType, buffer));
  8849. } else if (field.map) {
  8850. var keyval = field.decode(wireType, buffer);
  8851. msg[field.name].set(keyval[0], keyval[1]);
  8852. } else {
  8853. msg[field.name] = field.decode(wireType, buffer);
  8854. if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  8855. var currentField = msg[field.oneof.name]; // Virtual field references currently set field
  8856. if (currentField !== null && currentField !== field.name)
  8857. msg[currentField] = null; // Clear currently set field
  8858. msg[field.oneof.name] = field.name; // Point virtual field at this field
  8859. }
  8860. }
  8861. }
  8862. // Check if all required fields are present and set default values for optional fields that are not
  8863. for (var i=0, k=this._fields.length; i<k; ++i) {
  8864. field = this._fields[i];
  8865. if (msg[field.name] === null) {
  8866. if (this.syntax === "proto3") { // Proto3 sets default values by specification
  8867. msg[field.name] = field.defaultValue;
  8868. } else if (field.required) {
  8869. var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
  8870. err["decoded"] = msg; // Still expose what we got
  8871. throw(err);
  8872. } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
  8873. msg[field.name] = field.defaultValue;
  8874. }
  8875. }
  8876. return msg;
  8877. };
  8878. /**
  8879. * @alias ProtoBuf.Reflect.Message
  8880. * @expose
  8881. */
  8882. Reflect.Message = Message;
  8883. /**
  8884. * Constructs a new Message Field.
  8885. * @exports ProtoBuf.Reflect.Message.Field
  8886. * @param {!ProtoBuf.Builder} builder Builder reference
  8887. * @param {!ProtoBuf.Reflect.Message} message Message reference
  8888. * @param {string} rule Rule, one of requried, optional, repeated
  8889. * @param {string?} keytype Key data type, if any.
  8890. * @param {string} type Data type, e.g. int32
  8891. * @param {string} name Field name
  8892. * @param {number} id Unique field id
  8893. * @param {Object.<string,*>=} options Options
  8894. * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
  8895. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  8896. * @constructor
  8897. * @extends ProtoBuf.Reflect.T
  8898. */
  8899. var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
  8900. T.call(this, builder, message, name);
  8901. /**
  8902. * @override
  8903. */
  8904. this.className = "Message.Field";
  8905. /**
  8906. * Message field required flag.
  8907. * @type {boolean}
  8908. * @expose
  8909. */
  8910. this.required = rule === "required";
  8911. /**
  8912. * Message field repeated flag.
  8913. * @type {boolean}
  8914. * @expose
  8915. */
  8916. this.repeated = rule === "repeated";
  8917. /**
  8918. * Message field map flag.
  8919. * @type {boolean}
  8920. * @expose
  8921. */
  8922. this.map = rule === "map";
  8923. /**
  8924. * Message field key type. Type reference string if unresolved, protobuf
  8925. * type if resolved. Valid only if this.map === true, null otherwise.
  8926. * @type {string|{name: string, wireType: number}|null}
  8927. * @expose
  8928. */
  8929. this.keyType = keytype || null;
  8930. /**
  8931. * Message field type. Type reference string if unresolved, protobuf type if
  8932. * resolved. In a map field, this is the value type.
  8933. * @type {string|{name: string, wireType: number}}
  8934. * @expose
  8935. */
  8936. this.type = type;
  8937. /**
  8938. * Resolved type reference inside the global namespace.
  8939. * @type {ProtoBuf.Reflect.T|null}
  8940. * @expose
  8941. */
  8942. this.resolvedType = null;
  8943. /**
  8944. * Unique message field id.
  8945. * @type {number}
  8946. * @expose
  8947. */
  8948. this.id = id;
  8949. /**
  8950. * Message field options.
  8951. * @type {!Object.<string,*>}
  8952. * @dict
  8953. * @expose
  8954. */
  8955. this.options = options || {};
  8956. /**
  8957. * Default value.
  8958. * @type {*}
  8959. * @expose
  8960. */
  8961. this.defaultValue = null;
  8962. /**
  8963. * Enclosing OneOf.
  8964. * @type {?ProtoBuf.Reflect.Message.OneOf}
  8965. * @expose
  8966. */
  8967. this.oneof = oneof || null;
  8968. /**
  8969. * Syntax level of this definition (e.g., proto3).
  8970. * @type {string}
  8971. * @expose
  8972. */
  8973. this.syntax = syntax || 'proto2';
  8974. /**
  8975. * Original field name.
  8976. * @type {string}
  8977. * @expose
  8978. */
  8979. this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
  8980. /**
  8981. * Element implementation. Created in build() after types are resolved.
  8982. * @type {ProtoBuf.Element}
  8983. * @expose
  8984. */
  8985. this.element = null;
  8986. /**
  8987. * Key element implementation, for map fields. Created in build() after
  8988. * types are resolved.
  8989. * @type {ProtoBuf.Element}
  8990. * @expose
  8991. */
  8992. this.keyElement = null;
  8993. // Convert field names to camel case notation if the override is set
  8994. if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
  8995. this.name = ProtoBuf.Util.toCamelCase(this.name);
  8996. };
  8997. /**
  8998. * @alias ProtoBuf.Reflect.Message.Field.prototype
  8999. * @inner
  9000. */
  9001. var FieldPrototype = Field.prototype = Object.create(T.prototype);
  9002. /**
  9003. * Builds the field.
  9004. * @override
  9005. * @expose
  9006. */
  9007. FieldPrototype.build = function() {
  9008. this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
  9009. if (this.map)
  9010. this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
  9011. // In proto3, fields do not have field presence, and every field is set to
  9012. // its type's default value ("", 0, 0.0, or false).
  9013. if (this.syntax === 'proto3' && !this.repeated && !this.map)
  9014. this.defaultValue = Element.defaultFieldValue(this.type);
  9015. // Otherwise, default values are present when explicitly specified
  9016. else if (typeof this.options['default'] !== 'undefined')
  9017. this.defaultValue = this.verifyValue(this.options['default']);
  9018. };
  9019. /**
  9020. * Checks if the given value can be set for this field.
  9021. * @param {*} value Value to check
  9022. * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
  9023. * @return {*} Verified, maybe adjusted, value
  9024. * @throws {Error} If the value cannot be set for this field
  9025. * @expose
  9026. */
  9027. FieldPrototype.verifyValue = function(value, skipRepeated) {
  9028. skipRepeated = skipRepeated || false;
  9029. var self = this;
  9030. function fail(val, msg) {
  9031. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  9032. }
  9033. if (value === null) { // NULL values for optional fields
  9034. if (this.required)
  9035. fail(typeof value, "required");
  9036. if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
  9037. fail(typeof value, "proto3 field without field presence cannot be null");
  9038. return null;
  9039. }
  9040. var i;
  9041. if (this.repeated && !skipRepeated) { // Repeated values as arrays
  9042. if (!Array.isArray(value))
  9043. value = [value];
  9044. var res = [];
  9045. for (i=0; i<value.length; i++)
  9046. res.push(this.element.verifyValue(value[i]));
  9047. return res;
  9048. }
  9049. if (this.map && !skipRepeated) { // Map values as objects
  9050. if (!(value instanceof ProtoBuf.Map)) {
  9051. // If not already a Map, attempt to convert.
  9052. if (!(value instanceof Object)) {
  9053. fail(typeof value,
  9054. "expected ProtoBuf.Map or raw object for map field");
  9055. }
  9056. return new ProtoBuf.Map(this, value);
  9057. } else {
  9058. return value;
  9059. }
  9060. }
  9061. // All non-repeated fields expect no array
  9062. if (!this.repeated && Array.isArray(value))
  9063. fail(typeof value, "no array expected");
  9064. return this.element.verifyValue(value);
  9065. };
  9066. /**
  9067. * Determines whether the field will have a presence on the wire given its
  9068. * value.
  9069. * @param {*} value Verified field value
  9070. * @param {!ProtoBuf.Builder.Message} message Runtime message
  9071. * @return {boolean} Whether the field will be present on the wire
  9072. */
  9073. FieldPrototype.hasWirePresence = function(value, message) {
  9074. if (this.syntax !== 'proto3')
  9075. return (value !== null);
  9076. if (this.oneof && message[this.oneof.name] === this.name)
  9077. return true;
  9078. switch (this.type) {
  9079. case ProtoBuf.TYPES["int32"]:
  9080. case ProtoBuf.TYPES["sint32"]:
  9081. case ProtoBuf.TYPES["sfixed32"]:
  9082. case ProtoBuf.TYPES["uint32"]:
  9083. case ProtoBuf.TYPES["fixed32"]:
  9084. return value !== 0;
  9085. case ProtoBuf.TYPES["int64"]:
  9086. case ProtoBuf.TYPES["sint64"]:
  9087. case ProtoBuf.TYPES["sfixed64"]:
  9088. case ProtoBuf.TYPES["uint64"]:
  9089. case ProtoBuf.TYPES["fixed64"]:
  9090. return value.low !== 0 || value.high !== 0;
  9091. case ProtoBuf.TYPES["bool"]:
  9092. return value;
  9093. case ProtoBuf.TYPES["float"]:
  9094. case ProtoBuf.TYPES["double"]:
  9095. return value !== 0.0;
  9096. case ProtoBuf.TYPES["string"]:
  9097. return value.length > 0;
  9098. case ProtoBuf.TYPES["bytes"]:
  9099. return value.remaining() > 0;
  9100. case ProtoBuf.TYPES["enum"]:
  9101. return value !== 0;
  9102. case ProtoBuf.TYPES["message"]:
  9103. return value !== null;
  9104. default:
  9105. return true;
  9106. }
  9107. };
  9108. /**
  9109. * Encodes the specified field value to the specified buffer.
  9110. * @param {*} value Verified field value
  9111. * @param {ByteBuffer} buffer ByteBuffer to encode to
  9112. * @param {!ProtoBuf.Builder.Message} message Runtime message
  9113. * @return {ByteBuffer} The ByteBuffer for chaining
  9114. * @throws {Error} If the field cannot be encoded
  9115. * @expose
  9116. */
  9117. FieldPrototype.encode = function(value, buffer, message) {
  9118. if (this.type === null || typeof this.type !== 'object')
  9119. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  9120. if (value === null || (this.repeated && value.length == 0))
  9121. return buffer; // Optional omitted
  9122. try {
  9123. if (this.repeated) {
  9124. var i;
  9125. // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
  9126. // types) can be declared 'packed'."
  9127. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  9128. // "All of the elements of the field are packed into a single key-value pair with wire type 2
  9129. // (length-delimited). Each element is encoded the same way it would be normally, except without a
  9130. // tag preceding it."
  9131. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  9132. buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
  9133. var start = buffer.offset; // Remember where the contents begin
  9134. for (i=0; i<value.length; i++)
  9135. this.element.encodeValue(this.id, value[i], buffer);
  9136. var len = buffer.offset-start,
  9137. varintLen = ByteBuffer.calculateVarint32(len);
  9138. if (varintLen > 1) { // We need to move the contents
  9139. var contents = buffer.slice(start, buffer.offset);
  9140. start += varintLen-1;
  9141. buffer.offset = start;
  9142. buffer.append(contents);
  9143. }
  9144. buffer.writeVarint32(len, start-varintLen);
  9145. } else {
  9146. // "If your message definition has repeated elements (without the [packed=true] option), the encoded
  9147. // message has zero or more key-value pairs with the same tag number"
  9148. for (i=0; i<value.length; i++)
  9149. buffer.writeVarint32((this.id << 3) | this.type.wireType),
  9150. this.element.encodeValue(this.id, value[i], buffer);
  9151. }
  9152. } else if (this.map) {
  9153. // Write out each map entry as a submessage.
  9154. value.forEach(function(val, key, m) {
  9155. // Compute the length of the submessage (key, val) pair.
  9156. var length =
  9157. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  9158. this.keyElement.calculateLength(1, key) +
  9159. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  9160. this.element.calculateLength(2, val);
  9161. // Submessage with wire type of length-delimited.
  9162. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  9163. buffer.writeVarint32(length);
  9164. // Write out the key and val.
  9165. buffer.writeVarint32((1 << 3) | this.keyType.wireType);
  9166. this.keyElement.encodeValue(1, key, buffer);
  9167. buffer.writeVarint32((2 << 3) | this.type.wireType);
  9168. this.element.encodeValue(2, val, buffer);
  9169. }, this);
  9170. } else {
  9171. if (this.hasWirePresence(value, message)) {
  9172. buffer.writeVarint32((this.id << 3) | this.type.wireType);
  9173. this.element.encodeValue(this.id, value, buffer);
  9174. }
  9175. }
  9176. } catch (e) {
  9177. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  9178. }
  9179. return buffer;
  9180. };
  9181. /**
  9182. * Calculates the length of this field's value on the network level.
  9183. * @param {*} value Field value
  9184. * @param {!ProtoBuf.Builder.Message} message Runtime message
  9185. * @returns {number} Byte length
  9186. * @expose
  9187. */
  9188. FieldPrototype.calculate = function(value, message) {
  9189. value = this.verifyValue(value); // May throw
  9190. if (this.type === null || typeof this.type !== 'object')
  9191. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  9192. if (value === null || (this.repeated && value.length == 0))
  9193. return 0; // Optional omitted
  9194. var n = 0;
  9195. try {
  9196. if (this.repeated) {
  9197. var i, ni;
  9198. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  9199. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  9200. ni = 0;
  9201. for (i=0; i<value.length; i++)
  9202. ni += this.element.calculateLength(this.id, value[i]);
  9203. n += ByteBuffer.calculateVarint32(ni);
  9204. n += ni;
  9205. } else {
  9206. for (i=0; i<value.length; i++)
  9207. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
  9208. n += this.element.calculateLength(this.id, value[i]);
  9209. }
  9210. } else if (this.map) {
  9211. // Each map entry becomes a submessage.
  9212. value.forEach(function(val, key, m) {
  9213. // Compute the length of the submessage (key, val) pair.
  9214. var length =
  9215. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  9216. this.keyElement.calculateLength(1, key) +
  9217. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  9218. this.element.calculateLength(2, val);
  9219. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  9220. n += ByteBuffer.calculateVarint32(length);
  9221. n += length;
  9222. }, this);
  9223. } else {
  9224. if (this.hasWirePresence(value, message)) {
  9225. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
  9226. n += this.element.calculateLength(this.id, value);
  9227. }
  9228. }
  9229. } catch (e) {
  9230. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  9231. }
  9232. return n;
  9233. };
  9234. /**
  9235. * Decode the field value from the specified buffer.
  9236. * @param {number} wireType Leading wire type
  9237. * @param {ByteBuffer} buffer ByteBuffer to decode from
  9238. * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
  9239. * @return {*} Decoded value: array for packed repeated fields, [key, value] for
  9240. * map fields, or an individual value otherwise.
  9241. * @throws {Error} If the field cannot be decoded
  9242. * @expose
  9243. */
  9244. FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
  9245. var value, nBytes;
  9246. // We expect wireType to match the underlying type's wireType unless we see
  9247. // a packed repeated field, or unless this is a map field.
  9248. var wireTypeOK =
  9249. (!this.map && wireType == this.type.wireType) ||
  9250. (!skipRepeated && this.repeated && this.options["packed"] &&
  9251. wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
  9252. (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
  9253. if (!wireTypeOK)
  9254. throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
  9255. // Handle packed repeated fields.
  9256. if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  9257. if (!skipRepeated) {
  9258. nBytes = buffer.readVarint32();
  9259. nBytes = buffer.offset + nBytes; // Limit
  9260. var values = [];
  9261. while (buffer.offset < nBytes)
  9262. values.push(this.decode(this.type.wireType, buffer, true));
  9263. return values;
  9264. }
  9265. // Read the next value otherwise...
  9266. }
  9267. // Handle maps.
  9268. if (this.map) {
  9269. // Read one (key, value) submessage, and return [key, value]
  9270. var key = Element.defaultFieldValue(this.keyType);
  9271. value = Element.defaultFieldValue(this.type);
  9272. // Read the length
  9273. nBytes = buffer.readVarint32();
  9274. if (buffer.remaining() < nBytes)
  9275. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  9276. // Get a sub-buffer of this key/value submessage
  9277. var msgbuf = buffer.clone();
  9278. msgbuf.limit = msgbuf.offset + nBytes;
  9279. buffer.offset += nBytes;
  9280. while (msgbuf.remaining() > 0) {
  9281. var tag = msgbuf.readVarint32();
  9282. wireType = tag & 0x07;
  9283. var id = tag >>> 3;
  9284. if (id === 1) {
  9285. key = this.keyElement.decode(msgbuf, wireType, id);
  9286. } else if (id === 2) {
  9287. value = this.element.decode(msgbuf, wireType, id);
  9288. } else {
  9289. throw Error("Unexpected tag in map field key/value submessage");
  9290. }
  9291. }
  9292. return [key, value];
  9293. }
  9294. // Handle singular and non-packed repeated field values.
  9295. return this.element.decode(buffer, wireType, this.id);
  9296. };
  9297. /**
  9298. * @alias ProtoBuf.Reflect.Message.Field
  9299. * @expose
  9300. */
  9301. Reflect.Message.Field = Field;
  9302. /**
  9303. * Constructs a new Message ExtensionField.
  9304. * @exports ProtoBuf.Reflect.Message.ExtensionField
  9305. * @param {!ProtoBuf.Builder} builder Builder reference
  9306. * @param {!ProtoBuf.Reflect.Message} message Message reference
  9307. * @param {string} rule Rule, one of requried, optional, repeated
  9308. * @param {string} type Data type, e.g. int32
  9309. * @param {string} name Field name
  9310. * @param {number} id Unique field id
  9311. * @param {!Object.<string,*>=} options Options
  9312. * @constructor
  9313. * @extends ProtoBuf.Reflect.Message.Field
  9314. */
  9315. var ExtensionField = function(builder, message, rule, type, name, id, options) {
  9316. Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
  9317. /**
  9318. * Extension reference.
  9319. * @type {!ProtoBuf.Reflect.Extension}
  9320. * @expose
  9321. */
  9322. this.extension;
  9323. };
  9324. // Extends Field
  9325. ExtensionField.prototype = Object.create(Field.prototype);
  9326. /**
  9327. * @alias ProtoBuf.Reflect.Message.ExtensionField
  9328. * @expose
  9329. */
  9330. Reflect.Message.ExtensionField = ExtensionField;
  9331. /**
  9332. * Constructs a new Message OneOf.
  9333. * @exports ProtoBuf.Reflect.Message.OneOf
  9334. * @param {!ProtoBuf.Builder} builder Builder reference
  9335. * @param {!ProtoBuf.Reflect.Message} message Message reference
  9336. * @param {string} name OneOf name
  9337. * @constructor
  9338. * @extends ProtoBuf.Reflect.T
  9339. */
  9340. var OneOf = function(builder, message, name) {
  9341. T.call(this, builder, message, name);
  9342. /**
  9343. * Enclosed fields.
  9344. * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
  9345. * @expose
  9346. */
  9347. this.fields = [];
  9348. };
  9349. /**
  9350. * @alias ProtoBuf.Reflect.Message.OneOf
  9351. * @expose
  9352. */
  9353. Reflect.Message.OneOf = OneOf;
  9354. /**
  9355. * Constructs a new Enum.
  9356. * @exports ProtoBuf.Reflect.Enum
  9357. * @param {!ProtoBuf.Builder} builder Builder reference
  9358. * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
  9359. * @param {string} name Enum name
  9360. * @param {Object.<string,*>=} options Enum options
  9361. * @param {string?} syntax The syntax level (e.g., proto3)
  9362. * @constructor
  9363. * @extends ProtoBuf.Reflect.Namespace
  9364. */
  9365. var Enum = function(builder, parent, name, options, syntax) {
  9366. Namespace.call(this, builder, parent, name, options, syntax);
  9367. /**
  9368. * @override
  9369. */
  9370. this.className = "Enum";
  9371. /**
  9372. * Runtime enum object.
  9373. * @type {Object.<string,number>|null}
  9374. * @expose
  9375. */
  9376. this.object = null;
  9377. };
  9378. /**
  9379. * Gets the string name of an enum value.
  9380. * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
  9381. * @param {number} value Enum value
  9382. * @returns {?string} Name or `null` if not present
  9383. * @expose
  9384. */
  9385. Enum.getName = function(enm, value) {
  9386. var keys = Object.keys(enm);
  9387. for (var i=0, key; i<keys.length; ++i)
  9388. if (enm[key = keys[i]] === value)
  9389. return key;
  9390. return null;
  9391. };
  9392. /**
  9393. * @alias ProtoBuf.Reflect.Enum.prototype
  9394. * @inner
  9395. */
  9396. var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
  9397. /**
  9398. * Builds this enum and returns the runtime counterpart.
  9399. * @param {boolean} rebuild Whether to rebuild or not, defaults to false
  9400. * @returns {!Object.<string,number>}
  9401. * @expose
  9402. */
  9403. EnumPrototype.build = function(rebuild) {
  9404. if (this.object && !rebuild)
  9405. return this.object;
  9406. var enm = new ProtoBuf.Builder.Enum(),
  9407. values = this.getChildren(Enum.Value);
  9408. for (var i=0, k=values.length; i<k; ++i)
  9409. enm[values[i]['name']] = values[i]['id'];
  9410. if (Object.defineProperty)
  9411. Object.defineProperty(enm, '$options', {
  9412. "value": this.buildOpt(),
  9413. "enumerable": false
  9414. });
  9415. return this.object = enm;
  9416. };
  9417. /**
  9418. * @alias ProtoBuf.Reflect.Enum
  9419. * @expose
  9420. */
  9421. Reflect.Enum = Enum;
  9422. /**
  9423. * Constructs a new Enum Value.
  9424. * @exports ProtoBuf.Reflect.Enum.Value
  9425. * @param {!ProtoBuf.Builder} builder Builder reference
  9426. * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
  9427. * @param {string} name Field name
  9428. * @param {number} id Unique field id
  9429. * @constructor
  9430. * @extends ProtoBuf.Reflect.T
  9431. */
  9432. var Value = function(builder, enm, name, id) {
  9433. T.call(this, builder, enm, name);
  9434. /**
  9435. * @override
  9436. */
  9437. this.className = "Enum.Value";
  9438. /**
  9439. * Unique enum value id.
  9440. * @type {number}
  9441. * @expose
  9442. */
  9443. this.id = id;
  9444. };
  9445. // Extends T
  9446. Value.prototype = Object.create(T.prototype);
  9447. /**
  9448. * @alias ProtoBuf.Reflect.Enum.Value
  9449. * @expose
  9450. */
  9451. Reflect.Enum.Value = Value;
  9452. /**
  9453. * An extension (field).
  9454. * @exports ProtoBuf.Reflect.Extension
  9455. * @constructor
  9456. * @param {!ProtoBuf.Builder} builder Builder reference
  9457. * @param {!ProtoBuf.Reflect.T} parent Parent object
  9458. * @param {string} name Object name
  9459. * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
  9460. */
  9461. var Extension = function(builder, parent, name, field) {
  9462. T.call(this, builder, parent, name);
  9463. /**
  9464. * Extended message field.
  9465. * @type {!ProtoBuf.Reflect.Message.Field}
  9466. * @expose
  9467. */
  9468. this.field = field;
  9469. };
  9470. // Extends T
  9471. Extension.prototype = Object.create(T.prototype);
  9472. /**
  9473. * @alias ProtoBuf.Reflect.Extension
  9474. * @expose
  9475. */
  9476. Reflect.Extension = Extension;
  9477. /**
  9478. * Constructs a new Service.
  9479. * @exports ProtoBuf.Reflect.Service
  9480. * @param {!ProtoBuf.Builder} builder Builder reference
  9481. * @param {!ProtoBuf.Reflect.Namespace} root Root
  9482. * @param {string} name Service name
  9483. * @param {Object.<string,*>=} options Options
  9484. * @constructor
  9485. * @extends ProtoBuf.Reflect.Namespace
  9486. */
  9487. var Service = function(builder, root, name, options) {
  9488. Namespace.call(this, builder, root, name, options);
  9489. /**
  9490. * @override
  9491. */
  9492. this.className = "Service";
  9493. /**
  9494. * Built runtime service class.
  9495. * @type {?function(new:ProtoBuf.Builder.Service)}
  9496. */
  9497. this.clazz = null;
  9498. };
  9499. /**
  9500. * @alias ProtoBuf.Reflect.Service.prototype
  9501. * @inner
  9502. */
  9503. var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
  9504. /**
  9505. * Builds the service and returns the runtime counterpart, which is a fully functional class.
  9506. * @see ProtoBuf.Builder.Service
  9507. * @param {boolean=} rebuild Whether to rebuild or not
  9508. * @return {Function} Service class
  9509. * @throws {Error} If the message cannot be built
  9510. * @expose
  9511. */
  9512. ServicePrototype.build = function(rebuild) {
  9513. if (this.clazz && !rebuild)
  9514. return this.clazz;
  9515. // Create the runtime Service class in its own scope
  9516. return this.clazz = (function(ProtoBuf, T) {
  9517. /**
  9518. * Constructs a new runtime Service.
  9519. * @name ProtoBuf.Builder.Service
  9520. * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
  9521. * @class Barebone of all runtime services.
  9522. * @constructor
  9523. * @throws {Error} If the service cannot be created
  9524. */
  9525. var Service = function(rpcImpl) {
  9526. ProtoBuf.Builder.Service.call(this);
  9527. /**
  9528. * Service implementation.
  9529. * @name ProtoBuf.Builder.Service#rpcImpl
  9530. * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
  9531. * @expose
  9532. */
  9533. this.rpcImpl = rpcImpl || function(name, msg, callback) {
  9534. // This is what a user has to implement: A function receiving the method name, the actual message to
  9535. // send (type checked) and the callback that's either provided with the error as its first
  9536. // argument or null and the actual response message.
  9537. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
  9538. };
  9539. };
  9540. /**
  9541. * @alias ProtoBuf.Builder.Service.prototype
  9542. * @inner
  9543. */
  9544. var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
  9545. /**
  9546. * Asynchronously performs an RPC call using the given RPC implementation.
  9547. * @name ProtoBuf.Builder.Service.[Method]
  9548. * @function
  9549. * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
  9550. * @param {ProtoBuf.Builder.Message} req Request
  9551. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  9552. * the error if any and the response either as a pre-parsed message or as its raw bytes
  9553. * @abstract
  9554. */
  9555. /**
  9556. * Asynchronously performs an RPC call using the instance's RPC implementation.
  9557. * @name ProtoBuf.Builder.Service#[Method]
  9558. * @function
  9559. * @param {ProtoBuf.Builder.Message} req Request
  9560. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  9561. * the error if any and the response either as a pre-parsed message or as its raw bytes
  9562. * @abstract
  9563. */
  9564. var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
  9565. for (var i=0; i<rpc.length; i++) {
  9566. (function(method) {
  9567. // service#Method(message, callback)
  9568. ServicePrototype[method.name] = function(req, callback) {
  9569. try {
  9570. try {
  9571. // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
  9572. req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
  9573. } catch (err) {
  9574. if (!(err instanceof TypeError))
  9575. throw err;
  9576. }
  9577. if (req === null || typeof req !== 'object')
  9578. throw Error("Illegal arguments");
  9579. if (!(req instanceof method.resolvedRequestType.clazz))
  9580. req = new method.resolvedRequestType.clazz(req);
  9581. this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
  9582. if (err) {
  9583. callback(err);
  9584. return;
  9585. }
  9586. // Coalesce to empty string when service response has empty content
  9587. if (res === null)
  9588. res = '';
  9589. try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
  9590. if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
  9591. callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
  9592. return;
  9593. }
  9594. callback(null, res);
  9595. });
  9596. } catch (err) {
  9597. setTimeout(callback.bind(this, err), 0);
  9598. }
  9599. };
  9600. // Service.Method(rpcImpl, message, callback)
  9601. Service[method.name] = function(rpcImpl, req, callback) {
  9602. new Service(rpcImpl)[method.name](req, callback);
  9603. };
  9604. if (Object.defineProperty)
  9605. Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
  9606. Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
  9607. })(rpc[i]);
  9608. }
  9609. if (Object.defineProperty)
  9610. Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
  9611. Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
  9612. Object.defineProperty(Service, "$type", { "value": T }),
  9613. Object.defineProperty(ServicePrototype, "$type", { "value": T });
  9614. return Service;
  9615. })(ProtoBuf, this);
  9616. };
  9617. /**
  9618. * @alias ProtoBuf.Reflect.Service
  9619. * @expose
  9620. */
  9621. Reflect.Service = Service;
  9622. /**
  9623. * Abstract service method.
  9624. * @exports ProtoBuf.Reflect.Service.Method
  9625. * @param {!ProtoBuf.Builder} builder Builder reference
  9626. * @param {!ProtoBuf.Reflect.Service} svc Service
  9627. * @param {string} name Method name
  9628. * @param {Object.<string,*>=} options Options
  9629. * @constructor
  9630. * @extends ProtoBuf.Reflect.T
  9631. */
  9632. var Method = function(builder, svc, name, options) {
  9633. T.call(this, builder, svc, name);
  9634. /**
  9635. * @override
  9636. */
  9637. this.className = "Service.Method";
  9638. /**
  9639. * Options.
  9640. * @type {Object.<string, *>}
  9641. * @expose
  9642. */
  9643. this.options = options || {};
  9644. };
  9645. /**
  9646. * @alias ProtoBuf.Reflect.Service.Method.prototype
  9647. * @inner
  9648. */
  9649. var MethodPrototype = Method.prototype = Object.create(T.prototype);
  9650. /**
  9651. * Builds the method's '$options' property.
  9652. * @name ProtoBuf.Reflect.Service.Method#buildOpt
  9653. * @function
  9654. * @return {Object.<string,*>}
  9655. */
  9656. MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
  9657. /**
  9658. * @alias ProtoBuf.Reflect.Service.Method
  9659. * @expose
  9660. */
  9661. Reflect.Service.Method = Method;
  9662. /**
  9663. * RPC service method.
  9664. * @exports ProtoBuf.Reflect.Service.RPCMethod
  9665. * @param {!ProtoBuf.Builder} builder Builder reference
  9666. * @param {!ProtoBuf.Reflect.Service} svc Service
  9667. * @param {string} name Method name
  9668. * @param {string} request Request message name
  9669. * @param {string} response Response message name
  9670. * @param {boolean} request_stream Whether requests are streamed
  9671. * @param {boolean} response_stream Whether responses are streamed
  9672. * @param {Object.<string,*>=} options Options
  9673. * @constructor
  9674. * @extends ProtoBuf.Reflect.Service.Method
  9675. */
  9676. var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
  9677. Method.call(this, builder, svc, name, options);
  9678. /**
  9679. * @override
  9680. */
  9681. this.className = "Service.RPCMethod";
  9682. /**
  9683. * Request message name.
  9684. * @type {string}
  9685. * @expose
  9686. */
  9687. this.requestName = request;
  9688. /**
  9689. * Response message name.
  9690. * @type {string}
  9691. * @expose
  9692. */
  9693. this.responseName = response;
  9694. /**
  9695. * Whether requests are streamed
  9696. * @type {bool}
  9697. * @expose
  9698. */
  9699. this.requestStream = request_stream;
  9700. /**
  9701. * Whether responses are streamed
  9702. * @type {bool}
  9703. * @expose
  9704. */
  9705. this.responseStream = response_stream;
  9706. /**
  9707. * Resolved request message type.
  9708. * @type {ProtoBuf.Reflect.Message}
  9709. * @expose
  9710. */
  9711. this.resolvedRequestType = null;
  9712. /**
  9713. * Resolved response message type.
  9714. * @type {ProtoBuf.Reflect.Message}
  9715. * @expose
  9716. */
  9717. this.resolvedResponseType = null;
  9718. };
  9719. // Extends Method
  9720. RPCMethod.prototype = Object.create(Method.prototype);
  9721. /**
  9722. * @alias ProtoBuf.Reflect.Service.RPCMethod
  9723. * @expose
  9724. */
  9725. Reflect.Service.RPCMethod = RPCMethod;
  9726. return Reflect;
  9727. })(ProtoBuf);
  9728. /**
  9729. * @alias ProtoBuf.Builder
  9730. * @expose
  9731. */
  9732. ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
  9733. /**
  9734. * Constructs a new Builder.
  9735. * @exports ProtoBuf.Builder
  9736. * @class Provides the functionality to build protocol messages.
  9737. * @param {Object.<string,*>=} options Options
  9738. * @constructor
  9739. */
  9740. var Builder = function(options) {
  9741. /**
  9742. * Namespace.
  9743. * @type {ProtoBuf.Reflect.Namespace}
  9744. * @expose
  9745. */
  9746. this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
  9747. /**
  9748. * Namespace pointer.
  9749. * @type {ProtoBuf.Reflect.T}
  9750. * @expose
  9751. */
  9752. this.ptr = this.ns;
  9753. /**
  9754. * Resolved flag.
  9755. * @type {boolean}
  9756. * @expose
  9757. */
  9758. this.resolved = false;
  9759. /**
  9760. * The current building result.
  9761. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
  9762. * @expose
  9763. */
  9764. this.result = null;
  9765. /**
  9766. * Imported files.
  9767. * @type {Array.<string>}
  9768. * @expose
  9769. */
  9770. this.files = {};
  9771. /**
  9772. * Import root override.
  9773. * @type {?string}
  9774. * @expose
  9775. */
  9776. this.importRoot = null;
  9777. /**
  9778. * Options.
  9779. * @type {!Object.<string, *>}
  9780. * @expose
  9781. */
  9782. this.options = options || {};
  9783. };
  9784. /**
  9785. * @alias ProtoBuf.Builder.prototype
  9786. * @inner
  9787. */
  9788. var BuilderPrototype = Builder.prototype;
  9789. // ----- Definition tests -----
  9790. /**
  9791. * Tests if a definition most likely describes a message.
  9792. * @param {!Object} def
  9793. * @returns {boolean}
  9794. * @expose
  9795. */
  9796. Builder.isMessage = function(def) {
  9797. // Messages require a string name
  9798. if (typeof def["name"] !== 'string')
  9799. return false;
  9800. // Messages do not contain values (enum) or rpc methods (service)
  9801. if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
  9802. return false;
  9803. return true;
  9804. };
  9805. /**
  9806. * Tests if a definition most likely describes a message field.
  9807. * @param {!Object} def
  9808. * @returns {boolean}
  9809. * @expose
  9810. */
  9811. Builder.isMessageField = function(def) {
  9812. // Message fields require a string rule, name and type and an id
  9813. if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
  9814. return false;
  9815. return true;
  9816. };
  9817. /**
  9818. * Tests if a definition most likely describes an enum.
  9819. * @param {!Object} def
  9820. * @returns {boolean}
  9821. * @expose
  9822. */
  9823. Builder.isEnum = function(def) {
  9824. // Enums require a string name
  9825. if (typeof def["name"] !== 'string')
  9826. return false;
  9827. // Enums require at least one value
  9828. if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
  9829. return false;
  9830. return true;
  9831. };
  9832. /**
  9833. * Tests if a definition most likely describes a service.
  9834. * @param {!Object} def
  9835. * @returns {boolean}
  9836. * @expose
  9837. */
  9838. Builder.isService = function(def) {
  9839. // Services require a string name and an rpc object
  9840. if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
  9841. return false;
  9842. return true;
  9843. };
  9844. /**
  9845. * Tests if a definition most likely describes an extended message
  9846. * @param {!Object} def
  9847. * @returns {boolean}
  9848. * @expose
  9849. */
  9850. Builder.isExtend = function(def) {
  9851. // Extends rquire a string ref
  9852. if (typeof def["ref"] !== 'string')
  9853. return false;
  9854. return true;
  9855. };
  9856. // ----- Building -----
  9857. /**
  9858. * Resets the pointer to the root namespace.
  9859. * @returns {!ProtoBuf.Builder} this
  9860. * @expose
  9861. */
  9862. BuilderPrototype.reset = function() {
  9863. this.ptr = this.ns;
  9864. return this;
  9865. };
  9866. /**
  9867. * Defines a namespace on top of the current pointer position and places the pointer on it.
  9868. * @param {string} namespace
  9869. * @return {!ProtoBuf.Builder} this
  9870. * @expose
  9871. */
  9872. BuilderPrototype.define = function(namespace) {
  9873. if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
  9874. throw Error("illegal namespace: "+namespace);
  9875. namespace.split(".").forEach(function(part) {
  9876. var ns = this.ptr.getChild(part);
  9877. if (ns === null) // Keep existing
  9878. this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
  9879. this.ptr = ns;
  9880. }, this);
  9881. return this;
  9882. };
  9883. /**
  9884. * Creates the specified definitions at the current pointer position.
  9885. * @param {!Array.<!Object>} defs Messages, enums or services to create
  9886. * @returns {!ProtoBuf.Builder} this
  9887. * @throws {Error} If a message definition is invalid
  9888. * @expose
  9889. */
  9890. BuilderPrototype.create = function(defs) {
  9891. if (!defs)
  9892. return this; // Nothing to create
  9893. if (!Array.isArray(defs))
  9894. defs = [defs];
  9895. else {
  9896. if (defs.length === 0)
  9897. return this;
  9898. defs = defs.slice();
  9899. }
  9900. // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
  9901. var stack = [defs];
  9902. while (stack.length > 0) {
  9903. defs = stack.pop();
  9904. if (!Array.isArray(defs)) // Stack always contains entire namespaces
  9905. throw Error("not a valid namespace: "+JSON.stringify(defs));
  9906. while (defs.length > 0) {
  9907. var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
  9908. if (Builder.isMessage(def)) {
  9909. var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
  9910. // Create OneOfs
  9911. var oneofs = {};
  9912. if (def["oneofs"])
  9913. Object.keys(def["oneofs"]).forEach(function(name) {
  9914. obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
  9915. }, this);
  9916. // Create fields
  9917. if (def["fields"])
  9918. def["fields"].forEach(function(fld) {
  9919. if (obj.getChild(fld["id"]|0) !== null)
  9920. throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
  9921. if (fld["options"] && typeof fld["options"] !== 'object')
  9922. throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
  9923. var oneof = null;
  9924. if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
  9925. throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
  9926. fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
  9927. if (oneof)
  9928. oneof.fields.push(fld);
  9929. obj.addChild(fld);
  9930. }, this);
  9931. // Push children to stack
  9932. var subObj = [];
  9933. if (def["enums"])
  9934. def["enums"].forEach(function(enm) {
  9935. subObj.push(enm);
  9936. });
  9937. if (def["messages"])
  9938. def["messages"].forEach(function(msg) {
  9939. subObj.push(msg);
  9940. });
  9941. if (def["services"])
  9942. def["services"].forEach(function(svc) {
  9943. subObj.push(svc);
  9944. });
  9945. // Set extension ranges
  9946. if (def["extensions"]) {
  9947. if (typeof def["extensions"][0] === 'number') // pre 5.0.1
  9948. obj.extensions = [ def["extensions"] ];
  9949. else
  9950. obj.extensions = def["extensions"];
  9951. }
  9952. // Create on top of current namespace
  9953. this.ptr.addChild(obj);
  9954. if (subObj.length > 0) {
  9955. stack.push(defs); // Push the current level back
  9956. defs = subObj; // Continue processing sub level
  9957. subObj = null;
  9958. this.ptr = obj; // And move the pointer to this namespace
  9959. obj = null;
  9960. continue;
  9961. }
  9962. subObj = null;
  9963. } else if (Builder.isEnum(def)) {
  9964. obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
  9965. def["values"].forEach(function(val) {
  9966. obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
  9967. }, this);
  9968. this.ptr.addChild(obj);
  9969. } else if (Builder.isService(def)) {
  9970. obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
  9971. Object.keys(def["rpc"]).forEach(function(name) {
  9972. var mtd = def["rpc"][name];
  9973. obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
  9974. }, this);
  9975. this.ptr.addChild(obj);
  9976. } else if (Builder.isExtend(def)) {
  9977. obj = this.ptr.resolve(def["ref"], true);
  9978. if (obj) {
  9979. def["fields"].forEach(function(fld) {
  9980. if (obj.getChild(fld['id']|0) !== null)
  9981. throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
  9982. // Check if field id is allowed to be extended
  9983. if (obj.extensions) {
  9984. var valid = false;
  9985. obj.extensions.forEach(function(range) {
  9986. if (fld["id"] >= range[0] && fld["id"] <= range[1])
  9987. valid = true;
  9988. });
  9989. if (!valid)
  9990. throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
  9991. }
  9992. // Convert extension field names to camel case notation if the override is set
  9993. var name = fld["name"];
  9994. if (this.options['convertFieldsToCamelCase'])
  9995. name = ProtoBuf.Util.toCamelCase(name);
  9996. // see #161: Extensions use their fully qualified name as their runtime key and...
  9997. var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
  9998. // ...are added on top of the current namespace as an extension which is used for
  9999. // resolving their type later on (the extension always keeps the original name to
  10000. // prevent naming collisions)
  10001. var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
  10002. field.extension = ext;
  10003. this.ptr.addChild(ext);
  10004. obj.addChild(field);
  10005. }, this);
  10006. } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
  10007. throw Error("extended message "+def["ref"]+" is not defined");
  10008. } else
  10009. throw Error("not a valid definition: "+JSON.stringify(def));
  10010. def = null;
  10011. obj = null;
  10012. }
  10013. // Break goes here
  10014. defs = null;
  10015. this.ptr = this.ptr.parent; // Namespace done, continue at parent
  10016. }
  10017. this.resolved = false; // Require re-resolve
  10018. this.result = null; // Require re-build
  10019. return this;
  10020. };
  10021. /**
  10022. * Propagates syntax to all children.
  10023. * @param {!Object} parent
  10024. * @inner
  10025. */
  10026. function propagateSyntax(parent) {
  10027. if (parent['messages']) {
  10028. parent['messages'].forEach(function(child) {
  10029. child["syntax"] = parent["syntax"];
  10030. propagateSyntax(child);
  10031. });
  10032. }
  10033. if (parent['enums']) {
  10034. parent['enums'].forEach(function(child) {
  10035. child["syntax"] = parent["syntax"];
  10036. });
  10037. }
  10038. }
  10039. /**
  10040. * Imports another definition into this builder.
  10041. * @param {Object.<string,*>} json Parsed import
  10042. * @param {(string|{root: string, file: string})=} filename Imported file name
  10043. * @returns {!ProtoBuf.Builder} this
  10044. * @throws {Error} If the definition or file cannot be imported
  10045. * @expose
  10046. */
  10047. BuilderPrototype["import"] = function(json, filename) {
  10048. var delim = '/';
  10049. // Make sure to skip duplicate imports
  10050. if (typeof filename === 'string') {
  10051. if (ProtoBuf.Util.IS_NODE)
  10052. filename = require$$2['resolve'](filename);
  10053. if (this.files[filename] === true)
  10054. return this.reset();
  10055. this.files[filename] = true;
  10056. } else if (typeof filename === 'object') { // Object with root, file.
  10057. var root = filename.root;
  10058. if (ProtoBuf.Util.IS_NODE)
  10059. root = require$$2['resolve'](root);
  10060. if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
  10061. delim = '\\';
  10062. var fname;
  10063. if (ProtoBuf.Util.IS_NODE)
  10064. fname = require$$2['join'](root, filename.file);
  10065. else
  10066. fname = root + delim + filename.file;
  10067. if (this.files[fname] === true)
  10068. return this.reset();
  10069. this.files[fname] = true;
  10070. }
  10071. // Import imports
  10072. if (json['imports'] && json['imports'].length > 0) {
  10073. var importRoot,
  10074. resetRoot = false;
  10075. if (typeof filename === 'object') { // If an import root is specified, override
  10076. this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
  10077. importRoot = this.importRoot;
  10078. filename = filename["file"];
  10079. if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
  10080. delim = '\\';
  10081. } else if (typeof filename === 'string') {
  10082. if (this.importRoot) // If import root is overridden, use it
  10083. importRoot = this.importRoot;
  10084. else { // Otherwise compute from filename
  10085. if (filename.indexOf("/") >= 0) { // Unix
  10086. importRoot = filename.replace(/\/[^\/]*$/, "");
  10087. if (/* /file.proto */ importRoot === "")
  10088. importRoot = "/";
  10089. } else if (filename.indexOf("\\") >= 0) { // Windows
  10090. importRoot = filename.replace(/\\[^\\]*$/, "");
  10091. delim = '\\';
  10092. } else
  10093. importRoot = ".";
  10094. }
  10095. } else
  10096. importRoot = null;
  10097. for (var i=0; i<json['imports'].length; i++) {
  10098. if (typeof json['imports'][i] === 'string') { // Import file
  10099. if (!importRoot)
  10100. throw Error("cannot determine import root");
  10101. var importFilename = json['imports'][i];
  10102. if (importFilename === "google/protobuf/descriptor.proto")
  10103. continue; // Not needed and therefore not used
  10104. if (ProtoBuf.Util.IS_NODE)
  10105. importFilename = require$$2['join'](importRoot, importFilename);
  10106. else
  10107. importFilename = importRoot + delim + importFilename;
  10108. if (this.files[importFilename] === true)
  10109. continue; // Already imported
  10110. if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
  10111. importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
  10112. var contents = ProtoBuf.Util.fetch(importFilename);
  10113. if (contents === null)
  10114. throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
  10115. if (/\.json$/i.test(importFilename)) // Always possible
  10116. this["import"](JSON.parse(contents+""), importFilename); // May throw
  10117. else
  10118. this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
  10119. } else // Import structure
  10120. if (!filename)
  10121. this["import"](json['imports'][i]);
  10122. else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
  10123. this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
  10124. else // Without extension: Append _importN to make it unique
  10125. this["import"](json['imports'][i], filename+"_import"+i);
  10126. }
  10127. if (resetRoot) // Reset import root override when all imports are done
  10128. this.importRoot = null;
  10129. }
  10130. // Import structures
  10131. if (json['package'])
  10132. this.define(json['package']);
  10133. if (json['syntax'])
  10134. propagateSyntax(json);
  10135. var base = this.ptr;
  10136. if (json['options'])
  10137. Object.keys(json['options']).forEach(function(key) {
  10138. base.options[key] = json['options'][key];
  10139. });
  10140. if (json['messages'])
  10141. this.create(json['messages']),
  10142. this.ptr = base;
  10143. if (json['enums'])
  10144. this.create(json['enums']),
  10145. this.ptr = base;
  10146. if (json['services'])
  10147. this.create(json['services']),
  10148. this.ptr = base;
  10149. if (json['extends'])
  10150. this.create(json['extends']);
  10151. return this.reset();
  10152. };
  10153. /**
  10154. * Resolves all namespace objects.
  10155. * @throws {Error} If a type cannot be resolved
  10156. * @returns {!ProtoBuf.Builder} this
  10157. * @expose
  10158. */
  10159. BuilderPrototype.resolveAll = function() {
  10160. // Resolve all reflected objects
  10161. var res;
  10162. if (this.ptr == null || typeof this.ptr.type === 'object')
  10163. return this; // Done (already resolved)
  10164. if (this.ptr instanceof Reflect.Namespace) { // Resolve children
  10165. this.ptr.children.forEach(function(child) {
  10166. this.ptr = child;
  10167. this.resolveAll();
  10168. }, this);
  10169. } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
  10170. if (!Lang.TYPE.test(this.ptr.type)) {
  10171. if (!Lang.TYPEREF.test(this.ptr.type))
  10172. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  10173. res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
  10174. if (!res)
  10175. throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  10176. this.ptr.resolvedType = res;
  10177. if (res instanceof Reflect.Enum) {
  10178. this.ptr.type = ProtoBuf.TYPES["enum"];
  10179. if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
  10180. throw Error("proto3 message cannot reference proto2 enum");
  10181. }
  10182. else if (res instanceof Reflect.Message)
  10183. this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
  10184. else
  10185. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  10186. } else
  10187. this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
  10188. // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
  10189. // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
  10190. if (this.ptr.map) {
  10191. if (!Lang.TYPE.test(this.ptr.keyType))
  10192. throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
  10193. this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
  10194. }
  10195. // If it's a repeated and packable field then proto3 mandates it should be packed by
  10196. // default
  10197. if (
  10198. this.ptr.syntax === 'proto3' &&
  10199. this.ptr.repeated && this.ptr.options.packed === undefined &&
  10200. ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
  10201. ) {
  10202. this.ptr.options.packed = true;
  10203. }
  10204. } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
  10205. if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
  10206. res = this.ptr.parent.resolve(this.ptr.requestName, true);
  10207. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  10208. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
  10209. this.ptr.resolvedRequestType = res;
  10210. res = this.ptr.parent.resolve(this.ptr.responseName, true);
  10211. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  10212. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
  10213. this.ptr.resolvedResponseType = res;
  10214. } else // Should not happen as nothing else is implemented
  10215. throw Error("illegal service type in "+this.ptr.toString(true));
  10216. } else if (
  10217. !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
  10218. !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
  10219. !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
  10220. )
  10221. throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
  10222. return this.reset();
  10223. };
  10224. /**
  10225. * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
  10226. * return the built package.
  10227. * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
  10228. * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
  10229. * @throws {Error} If a type could not be resolved
  10230. * @expose
  10231. */
  10232. BuilderPrototype.build = function(path) {
  10233. this.reset();
  10234. if (!this.resolved)
  10235. this.resolveAll(),
  10236. this.resolved = true,
  10237. this.result = null; // Require re-build
  10238. if (this.result === null) // (Re-)Build
  10239. this.result = this.ns.build();
  10240. if (!path)
  10241. return this.result;
  10242. var part = typeof path === 'string' ? path.split(".") : path,
  10243. ptr = this.result; // Build namespace pointer (no hasChild etc.)
  10244. for (var i=0; i<part.length; i++)
  10245. if (ptr[part[i]])
  10246. ptr = ptr[part[i]];
  10247. else {
  10248. ptr = null;
  10249. break;
  10250. }
  10251. return ptr;
  10252. };
  10253. /**
  10254. * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
  10255. * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
  10256. * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
  10257. * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
  10258. */
  10259. BuilderPrototype.lookup = function(path, excludeNonNamespace) {
  10260. return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
  10261. };
  10262. /**
  10263. * Returns a string representation of this object.
  10264. * @return {string} String representation as of "Builder"
  10265. * @expose
  10266. */
  10267. BuilderPrototype.toString = function() {
  10268. return "Builder";
  10269. };
  10270. // ----- Base classes -----
  10271. // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
  10272. /**
  10273. * @alias ProtoBuf.Builder.Message
  10274. */
  10275. Builder.Message = function() {};
  10276. /**
  10277. * @alias ProtoBuf.Builder.Enum
  10278. */
  10279. Builder.Enum = function() {};
  10280. /**
  10281. * @alias ProtoBuf.Builder.Message
  10282. */
  10283. Builder.Service = function() {};
  10284. return Builder;
  10285. })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
  10286. /**
  10287. * @alias ProtoBuf.Map
  10288. * @expose
  10289. */
  10290. ProtoBuf.Map = (function(ProtoBuf, Reflect) {
  10291. /**
  10292. * Constructs a new Map. A Map is a container that is used to implement map
  10293. * fields on message objects. It closely follows the ES6 Map API; however,
  10294. * it is distinct because we do not want to depend on external polyfills or
  10295. * on ES6 itself.
  10296. *
  10297. * @exports ProtoBuf.Map
  10298. * @param {!ProtoBuf.Reflect.Field} field Map field
  10299. * @param {Object.<string,*>=} contents Initial contents
  10300. * @constructor
  10301. */
  10302. var Map = function(field, contents) {
  10303. if (!field.map)
  10304. throw Error("field is not a map");
  10305. /**
  10306. * The field corresponding to this map.
  10307. * @type {!ProtoBuf.Reflect.Field}
  10308. */
  10309. this.field = field;
  10310. /**
  10311. * Element instance corresponding to key type.
  10312. * @type {!ProtoBuf.Reflect.Element}
  10313. */
  10314. this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
  10315. /**
  10316. * Element instance corresponding to value type.
  10317. * @type {!ProtoBuf.Reflect.Element}
  10318. */
  10319. this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
  10320. /**
  10321. * Internal map: stores mapping of (string form of key) -> (key, value)
  10322. * pair.
  10323. *
  10324. * We provide map semantics for arbitrary key types, but we build on top
  10325. * of an Object, which has only string keys. In order to avoid the need
  10326. * to convert a string key back to its native type in many situations,
  10327. * we store the native key value alongside the value. Thus, we only need
  10328. * a one-way mapping from a key type to its string form that guarantees
  10329. * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
  10330. * === K2).
  10331. *
  10332. * @type {!Object<string, {key: *, value: *}>}
  10333. */
  10334. this.map = {};
  10335. /**
  10336. * Returns the number of elements in the map.
  10337. */
  10338. Object.defineProperty(this, "size", {
  10339. get: function() { return Object.keys(this.map).length; }
  10340. });
  10341. // Fill initial contents from a raw object.
  10342. if (contents) {
  10343. var keys = Object.keys(contents);
  10344. for (var i = 0; i < keys.length; i++) {
  10345. var key = this.keyElem.valueFromString(keys[i]);
  10346. var val = this.valueElem.verifyValue(contents[keys[i]]);
  10347. this.map[this.keyElem.valueToString(key)] =
  10348. { key: key, value: val };
  10349. }
  10350. }
  10351. };
  10352. var MapPrototype = Map.prototype;
  10353. /**
  10354. * Helper: return an iterator over an array.
  10355. * @param {!Array<*>} arr the array
  10356. * @returns {!Object} an iterator
  10357. * @inner
  10358. */
  10359. function arrayIterator(arr) {
  10360. var idx = 0;
  10361. return {
  10362. next: function() {
  10363. if (idx < arr.length)
  10364. return { done: false, value: arr[idx++] };
  10365. return { done: true };
  10366. }
  10367. }
  10368. }
  10369. /**
  10370. * Clears the map.
  10371. */
  10372. MapPrototype.clear = function() {
  10373. this.map = {};
  10374. };
  10375. /**
  10376. * Deletes a particular key from the map.
  10377. * @returns {boolean} Whether any entry with this key was deleted.
  10378. */
  10379. MapPrototype["delete"] = function(key) {
  10380. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  10381. var hadKey = keyValue in this.map;
  10382. delete this.map[keyValue];
  10383. return hadKey;
  10384. };
  10385. /**
  10386. * Returns an iterator over [key, value] pairs in the map.
  10387. * @returns {Object} The iterator
  10388. */
  10389. MapPrototype.entries = function() {
  10390. var entries = [];
  10391. var strKeys = Object.keys(this.map);
  10392. for (var i = 0, entry; i < strKeys.length; i++)
  10393. entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
  10394. return arrayIterator(entries);
  10395. };
  10396. /**
  10397. * Returns an iterator over keys in the map.
  10398. * @returns {Object} The iterator
  10399. */
  10400. MapPrototype.keys = function() {
  10401. var keys = [];
  10402. var strKeys = Object.keys(this.map);
  10403. for (var i = 0; i < strKeys.length; i++)
  10404. keys.push(this.map[strKeys[i]].key);
  10405. return arrayIterator(keys);
  10406. };
  10407. /**
  10408. * Returns an iterator over values in the map.
  10409. * @returns {!Object} The iterator
  10410. */
  10411. MapPrototype.values = function() {
  10412. var values = [];
  10413. var strKeys = Object.keys(this.map);
  10414. for (var i = 0; i < strKeys.length; i++)
  10415. values.push(this.map[strKeys[i]].value);
  10416. return arrayIterator(values);
  10417. };
  10418. /**
  10419. * Iterates over entries in the map, calling a function on each.
  10420. * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
  10421. * @param {Object=} thisArg The `this` value for the callback
  10422. */
  10423. MapPrototype.forEach = function(cb, thisArg) {
  10424. var strKeys = Object.keys(this.map);
  10425. for (var i = 0, entry; i < strKeys.length; i++)
  10426. cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
  10427. };
  10428. /**
  10429. * Sets a key in the map to the given value.
  10430. * @param {*} key The key
  10431. * @param {*} value The value
  10432. * @returns {!ProtoBuf.Map} The map instance
  10433. */
  10434. MapPrototype.set = function(key, value) {
  10435. var keyValue = this.keyElem.verifyValue(key);
  10436. var valValue = this.valueElem.verifyValue(value);
  10437. this.map[this.keyElem.valueToString(keyValue)] =
  10438. { key: keyValue, value: valValue };
  10439. return this;
  10440. };
  10441. /**
  10442. * Gets the value corresponding to a key in the map.
  10443. * @param {*} key The key
  10444. * @returns {*|undefined} The value, or `undefined` if key not present
  10445. */
  10446. MapPrototype.get = function(key) {
  10447. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  10448. if (!(keyValue in this.map))
  10449. return undefined;
  10450. return this.map[keyValue].value;
  10451. };
  10452. /**
  10453. * Determines whether the given key is present in the map.
  10454. * @param {*} key The key
  10455. * @returns {boolean} `true` if the key is present
  10456. */
  10457. MapPrototype.has = function(key) {
  10458. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  10459. return (keyValue in this.map);
  10460. };
  10461. return Map;
  10462. })(ProtoBuf, ProtoBuf.Reflect);
  10463. /**
  10464. * Constructs a new empty Builder.
  10465. * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
  10466. * @return {!ProtoBuf.Builder} Builder
  10467. * @expose
  10468. */
  10469. ProtoBuf.newBuilder = function(options) {
  10470. options = options || {};
  10471. if (typeof options['convertFieldsToCamelCase'] === 'undefined')
  10472. options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
  10473. if (typeof options['populateAccessors'] === 'undefined')
  10474. options['populateAccessors'] = ProtoBuf.populateAccessors;
  10475. return new ProtoBuf.Builder(options);
  10476. };
  10477. /**
  10478. * Loads a .json definition and returns the Builder.
  10479. * @param {!*|string} json JSON definition
  10480. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  10481. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  10482. * @return {ProtoBuf.Builder} Builder to create new messages
  10483. * @throws {Error} If the definition cannot be parsed or built
  10484. * @expose
  10485. */
  10486. ProtoBuf.loadJson = function(json, builder, filename) {
  10487. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  10488. filename = builder,
  10489. builder = null;
  10490. if (!builder || typeof builder !== 'object')
  10491. builder = ProtoBuf.newBuilder();
  10492. if (typeof json === 'string')
  10493. json = JSON.parse(json);
  10494. builder["import"](json, filename);
  10495. builder.resolveAll();
  10496. return builder;
  10497. };
  10498. /**
  10499. * Loads a .json file and returns the Builder.
  10500. * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
  10501. * an overridden 'root' path for all imported files.
  10502. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  10503. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  10504. * file will be read synchronously and this function will return the Builder.
  10505. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  10506. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  10507. * request has failed), else undefined
  10508. * @expose
  10509. */
  10510. ProtoBuf.loadJsonFile = function(filename, callback, builder) {
  10511. if (callback && typeof callback === 'object')
  10512. builder = callback,
  10513. callback = null;
  10514. else if (!callback || typeof callback !== 'function')
  10515. callback = null;
  10516. if (callback)
  10517. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  10518. if (contents === null) {
  10519. callback(Error("Failed to fetch file"));
  10520. return;
  10521. }
  10522. try {
  10523. callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
  10524. } catch (e) {
  10525. callback(e);
  10526. }
  10527. });
  10528. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  10529. return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
  10530. };
  10531. return ProtoBuf;
  10532. });
  10533. });
  10534. var messageCompiled = protobufLight.newBuilder({})['import']({
  10535. "package": 'push_server.messages2',
  10536. syntax: 'proto2',
  10537. options: {
  10538. objc_class_prefix: 'AVIM'
  10539. },
  10540. messages: [{
  10541. name: 'JsonObjectMessage',
  10542. syntax: 'proto2',
  10543. fields: [{
  10544. rule: 'required',
  10545. type: 'string',
  10546. name: 'data',
  10547. id: 1
  10548. }]
  10549. }, {
  10550. name: 'UnreadTuple',
  10551. syntax: 'proto2',
  10552. fields: [{
  10553. rule: 'required',
  10554. type: 'string',
  10555. name: 'cid',
  10556. id: 1
  10557. }, {
  10558. rule: 'required',
  10559. type: 'int32',
  10560. name: 'unread',
  10561. id: 2
  10562. }, {
  10563. rule: 'optional',
  10564. type: 'string',
  10565. name: 'mid',
  10566. id: 3
  10567. }, {
  10568. rule: 'optional',
  10569. type: 'int64',
  10570. name: 'timestamp',
  10571. id: 4
  10572. }, {
  10573. rule: 'optional',
  10574. type: 'string',
  10575. name: 'from',
  10576. id: 5
  10577. }, {
  10578. rule: 'optional',
  10579. type: 'string',
  10580. name: 'data',
  10581. id: 6
  10582. }, {
  10583. rule: 'optional',
  10584. type: 'int64',
  10585. name: 'patchTimestamp',
  10586. id: 7
  10587. }, {
  10588. rule: 'optional',
  10589. type: 'bool',
  10590. name: 'mentioned',
  10591. id: 8
  10592. }, {
  10593. rule: 'optional',
  10594. type: 'bytes',
  10595. name: 'binaryMsg',
  10596. id: 9
  10597. }, {
  10598. rule: 'optional',
  10599. type: 'int32',
  10600. name: 'convType',
  10601. id: 10
  10602. }]
  10603. }, {
  10604. name: 'LogItem',
  10605. syntax: 'proto2',
  10606. fields: [{
  10607. rule: 'optional',
  10608. type: 'string',
  10609. name: 'from',
  10610. id: 1
  10611. }, {
  10612. rule: 'optional',
  10613. type: 'string',
  10614. name: 'data',
  10615. id: 2
  10616. }, {
  10617. rule: 'optional',
  10618. type: 'int64',
  10619. name: 'timestamp',
  10620. id: 3
  10621. }, {
  10622. rule: 'optional',
  10623. type: 'string',
  10624. name: 'msgId',
  10625. id: 4
  10626. }, {
  10627. rule: 'optional',
  10628. type: 'int64',
  10629. name: 'ackAt',
  10630. id: 5
  10631. }, {
  10632. rule: 'optional',
  10633. type: 'int64',
  10634. name: 'readAt',
  10635. id: 6
  10636. }, {
  10637. rule: 'optional',
  10638. type: 'int64',
  10639. name: 'patchTimestamp',
  10640. id: 7
  10641. }, {
  10642. rule: 'optional',
  10643. type: 'bool',
  10644. name: 'mentionAll',
  10645. id: 8
  10646. }, {
  10647. rule: 'repeated',
  10648. type: 'string',
  10649. name: 'mentionPids',
  10650. id: 9
  10651. }, {
  10652. rule: 'optional',
  10653. type: 'bool',
  10654. name: 'bin',
  10655. id: 10
  10656. }, {
  10657. rule: 'optional',
  10658. type: 'int32',
  10659. name: 'convType',
  10660. id: 11
  10661. }]
  10662. }, {
  10663. name: 'ConvMemberInfo',
  10664. syntax: 'proto2',
  10665. fields: [{
  10666. rule: 'optional',
  10667. type: 'string',
  10668. name: 'pid',
  10669. id: 1
  10670. }, {
  10671. rule: 'optional',
  10672. type: 'string',
  10673. name: 'role',
  10674. id: 2
  10675. }, {
  10676. rule: 'optional',
  10677. type: 'string',
  10678. name: 'infoId',
  10679. id: 3
  10680. }]
  10681. }, {
  10682. name: 'DataCommand',
  10683. syntax: 'proto2',
  10684. fields: [{
  10685. rule: 'repeated',
  10686. type: 'string',
  10687. name: 'ids',
  10688. id: 1
  10689. }, {
  10690. rule: 'repeated',
  10691. type: 'JsonObjectMessage',
  10692. name: 'msg',
  10693. id: 2
  10694. }, {
  10695. rule: 'optional',
  10696. type: 'bool',
  10697. name: 'offline',
  10698. id: 3
  10699. }]
  10700. }, {
  10701. name: 'SessionCommand',
  10702. syntax: 'proto2',
  10703. fields: [{
  10704. rule: 'optional',
  10705. type: 'int64',
  10706. name: 't',
  10707. id: 1
  10708. }, {
  10709. rule: 'optional',
  10710. type: 'string',
  10711. name: 'n',
  10712. id: 2
  10713. }, {
  10714. rule: 'optional',
  10715. type: 'string',
  10716. name: 's',
  10717. id: 3
  10718. }, {
  10719. rule: 'optional',
  10720. type: 'string',
  10721. name: 'ua',
  10722. id: 4
  10723. }, {
  10724. rule: 'optional',
  10725. type: 'bool',
  10726. name: 'r',
  10727. id: 5
  10728. }, {
  10729. rule: 'optional',
  10730. type: 'string',
  10731. name: 'tag',
  10732. id: 6
  10733. }, {
  10734. rule: 'optional',
  10735. type: 'string',
  10736. name: 'deviceId',
  10737. id: 7
  10738. }, {
  10739. rule: 'repeated',
  10740. type: 'string',
  10741. name: 'sessionPeerIds',
  10742. id: 8
  10743. }, {
  10744. rule: 'repeated',
  10745. type: 'string',
  10746. name: 'onlineSessionPeerIds',
  10747. id: 9
  10748. }, {
  10749. rule: 'optional',
  10750. type: 'string',
  10751. name: 'st',
  10752. id: 10
  10753. }, {
  10754. rule: 'optional',
  10755. type: 'int32',
  10756. name: 'stTtl',
  10757. id: 11
  10758. }, {
  10759. rule: 'optional',
  10760. type: 'int32',
  10761. name: 'code',
  10762. id: 12
  10763. }, {
  10764. rule: 'optional',
  10765. type: 'string',
  10766. name: 'reason',
  10767. id: 13
  10768. }, {
  10769. rule: 'optional',
  10770. type: 'string',
  10771. name: 'deviceToken',
  10772. id: 14
  10773. }, {
  10774. rule: 'optional',
  10775. type: 'bool',
  10776. name: 'sp',
  10777. id: 15
  10778. }, {
  10779. rule: 'optional',
  10780. type: 'string',
  10781. name: 'detail',
  10782. id: 16
  10783. }, {
  10784. rule: 'optional',
  10785. type: 'int64',
  10786. name: 'lastUnreadNotifTime',
  10787. id: 17
  10788. }, {
  10789. rule: 'optional',
  10790. type: 'int64',
  10791. name: 'lastPatchTime',
  10792. id: 18
  10793. }, {
  10794. rule: 'optional',
  10795. type: 'int64',
  10796. name: 'configBitmap',
  10797. id: 19
  10798. }]
  10799. }, {
  10800. name: 'ErrorCommand',
  10801. syntax: 'proto2',
  10802. fields: [{
  10803. rule: 'required',
  10804. type: 'int32',
  10805. name: 'code',
  10806. id: 1
  10807. }, {
  10808. rule: 'required',
  10809. type: 'string',
  10810. name: 'reason',
  10811. id: 2
  10812. }, {
  10813. rule: 'optional',
  10814. type: 'int32',
  10815. name: 'appCode',
  10816. id: 3
  10817. }, {
  10818. rule: 'optional',
  10819. type: 'string',
  10820. name: 'detail',
  10821. id: 4
  10822. }, {
  10823. rule: 'repeated',
  10824. type: 'string',
  10825. name: 'pids',
  10826. id: 5
  10827. }, {
  10828. rule: 'optional',
  10829. type: 'string',
  10830. name: 'appMsg',
  10831. id: 6
  10832. }]
  10833. }, {
  10834. name: 'DirectCommand',
  10835. syntax: 'proto2',
  10836. fields: [{
  10837. rule: 'optional',
  10838. type: 'string',
  10839. name: 'msg',
  10840. id: 1
  10841. }, {
  10842. rule: 'optional',
  10843. type: 'string',
  10844. name: 'uid',
  10845. id: 2
  10846. }, {
  10847. rule: 'optional',
  10848. type: 'string',
  10849. name: 'fromPeerId',
  10850. id: 3
  10851. }, {
  10852. rule: 'optional',
  10853. type: 'int64',
  10854. name: 'timestamp',
  10855. id: 4
  10856. }, {
  10857. rule: 'optional',
  10858. type: 'bool',
  10859. name: 'offline',
  10860. id: 5
  10861. }, {
  10862. rule: 'optional',
  10863. type: 'bool',
  10864. name: 'hasMore',
  10865. id: 6
  10866. }, {
  10867. rule: 'repeated',
  10868. type: 'string',
  10869. name: 'toPeerIds',
  10870. id: 7
  10871. }, {
  10872. rule: 'optional',
  10873. type: 'bool',
  10874. name: 'r',
  10875. id: 10
  10876. }, {
  10877. rule: 'optional',
  10878. type: 'string',
  10879. name: 'cid',
  10880. id: 11
  10881. }, {
  10882. rule: 'optional',
  10883. type: 'string',
  10884. name: 'id',
  10885. id: 12
  10886. }, {
  10887. rule: 'optional',
  10888. type: 'bool',
  10889. name: 'transient',
  10890. id: 13
  10891. }, {
  10892. rule: 'optional',
  10893. type: 'string',
  10894. name: 'dt',
  10895. id: 14
  10896. }, {
  10897. rule: 'optional',
  10898. type: 'string',
  10899. name: 'roomId',
  10900. id: 15
  10901. }, {
  10902. rule: 'optional',
  10903. type: 'string',
  10904. name: 'pushData',
  10905. id: 16
  10906. }, {
  10907. rule: 'optional',
  10908. type: 'bool',
  10909. name: 'will',
  10910. id: 17
  10911. }, {
  10912. rule: 'optional',
  10913. type: 'int64',
  10914. name: 'patchTimestamp',
  10915. id: 18
  10916. }, {
  10917. rule: 'optional',
  10918. type: 'bytes',
  10919. name: 'binaryMsg',
  10920. id: 19
  10921. }, {
  10922. rule: 'repeated',
  10923. type: 'string',
  10924. name: 'mentionPids',
  10925. id: 20
  10926. }, {
  10927. rule: 'optional',
  10928. type: 'bool',
  10929. name: 'mentionAll',
  10930. id: 21
  10931. }, {
  10932. rule: 'optional',
  10933. type: 'int32',
  10934. name: 'convType',
  10935. id: 22
  10936. }]
  10937. }, {
  10938. name: 'AckCommand',
  10939. syntax: 'proto2',
  10940. fields: [{
  10941. rule: 'optional',
  10942. type: 'int32',
  10943. name: 'code',
  10944. id: 1
  10945. }, {
  10946. rule: 'optional',
  10947. type: 'string',
  10948. name: 'reason',
  10949. id: 2
  10950. }, {
  10951. rule: 'optional',
  10952. type: 'string',
  10953. name: 'mid',
  10954. id: 3
  10955. }, {
  10956. rule: 'optional',
  10957. type: 'string',
  10958. name: 'cid',
  10959. id: 4
  10960. }, {
  10961. rule: 'optional',
  10962. type: 'int64',
  10963. name: 't',
  10964. id: 5
  10965. }, {
  10966. rule: 'optional',
  10967. type: 'string',
  10968. name: 'uid',
  10969. id: 6
  10970. }, {
  10971. rule: 'optional',
  10972. type: 'int64',
  10973. name: 'fromts',
  10974. id: 7
  10975. }, {
  10976. rule: 'optional',
  10977. type: 'int64',
  10978. name: 'tots',
  10979. id: 8
  10980. }, {
  10981. rule: 'optional',
  10982. type: 'string',
  10983. name: 'type',
  10984. id: 9
  10985. }, {
  10986. rule: 'repeated',
  10987. type: 'string',
  10988. name: 'ids',
  10989. id: 10
  10990. }, {
  10991. rule: 'optional',
  10992. type: 'int32',
  10993. name: 'appCode',
  10994. id: 11
  10995. }, {
  10996. rule: 'optional',
  10997. type: 'string',
  10998. name: 'appMsg',
  10999. id: 12
  11000. }]
  11001. }, {
  11002. name: 'UnreadCommand',
  11003. syntax: 'proto2',
  11004. fields: [{
  11005. rule: 'repeated',
  11006. type: 'UnreadTuple',
  11007. name: 'convs',
  11008. id: 1
  11009. }, {
  11010. rule: 'optional',
  11011. type: 'int64',
  11012. name: 'notifTime',
  11013. id: 2
  11014. }]
  11015. }, {
  11016. name: 'ConvCommand',
  11017. syntax: 'proto2',
  11018. fields: [{
  11019. rule: 'repeated',
  11020. type: 'string',
  11021. name: 'm',
  11022. id: 1
  11023. }, {
  11024. rule: 'optional',
  11025. type: 'bool',
  11026. name: 'transient',
  11027. id: 2
  11028. }, {
  11029. rule: 'optional',
  11030. type: 'bool',
  11031. name: 'unique',
  11032. id: 3
  11033. }, {
  11034. rule: 'optional',
  11035. type: 'string',
  11036. name: 'cid',
  11037. id: 4
  11038. }, {
  11039. rule: 'optional',
  11040. type: 'string',
  11041. name: 'cdate',
  11042. id: 5
  11043. }, {
  11044. rule: 'optional',
  11045. type: 'string',
  11046. name: 'initBy',
  11047. id: 6
  11048. }, {
  11049. rule: 'optional',
  11050. type: 'string',
  11051. name: 'sort',
  11052. id: 7
  11053. }, {
  11054. rule: 'optional',
  11055. type: 'int32',
  11056. name: 'limit',
  11057. id: 8
  11058. }, {
  11059. rule: 'optional',
  11060. type: 'int32',
  11061. name: 'skip',
  11062. id: 9
  11063. }, {
  11064. rule: 'optional',
  11065. type: 'int32',
  11066. name: 'flag',
  11067. id: 10
  11068. }, {
  11069. rule: 'optional',
  11070. type: 'int32',
  11071. name: 'count',
  11072. id: 11
  11073. }, {
  11074. rule: 'optional',
  11075. type: 'string',
  11076. name: 'udate',
  11077. id: 12
  11078. }, {
  11079. rule: 'optional',
  11080. type: 'int64',
  11081. name: 't',
  11082. id: 13
  11083. }, {
  11084. rule: 'optional',
  11085. type: 'string',
  11086. name: 'n',
  11087. id: 14
  11088. }, {
  11089. rule: 'optional',
  11090. type: 'string',
  11091. name: 's',
  11092. id: 15
  11093. }, {
  11094. rule: 'optional',
  11095. type: 'bool',
  11096. name: 'statusSub',
  11097. id: 16
  11098. }, {
  11099. rule: 'optional',
  11100. type: 'bool',
  11101. name: 'statusPub',
  11102. id: 17
  11103. }, {
  11104. rule: 'optional',
  11105. type: 'int32',
  11106. name: 'statusTTL',
  11107. id: 18
  11108. }, {
  11109. rule: 'optional',
  11110. type: 'string',
  11111. name: 'uniqueId',
  11112. id: 19
  11113. }, {
  11114. rule: 'optional',
  11115. type: 'string',
  11116. name: 'targetClientId',
  11117. id: 20
  11118. }, {
  11119. rule: 'optional',
  11120. type: 'int64',
  11121. name: 'maxReadTimestamp',
  11122. id: 21
  11123. }, {
  11124. rule: 'optional',
  11125. type: 'int64',
  11126. name: 'maxAckTimestamp',
  11127. id: 22
  11128. }, {
  11129. rule: 'optional',
  11130. type: 'bool',
  11131. name: 'queryAllMembers',
  11132. id: 23
  11133. }, {
  11134. rule: 'repeated',
  11135. type: 'MaxReadTuple',
  11136. name: 'maxReadTuples',
  11137. id: 24
  11138. }, {
  11139. rule: 'repeated',
  11140. type: 'string',
  11141. name: 'cids',
  11142. id: 25
  11143. }, {
  11144. rule: 'optional',
  11145. type: 'ConvMemberInfo',
  11146. name: 'info',
  11147. id: 26
  11148. }, {
  11149. rule: 'optional',
  11150. type: 'bool',
  11151. name: 'tempConv',
  11152. id: 27
  11153. }, {
  11154. rule: 'optional',
  11155. type: 'int32',
  11156. name: 'tempConvTTL',
  11157. id: 28
  11158. }, {
  11159. rule: 'repeated',
  11160. type: 'string',
  11161. name: 'tempConvIds',
  11162. id: 29
  11163. }, {
  11164. rule: 'repeated',
  11165. type: 'string',
  11166. name: 'allowedPids',
  11167. id: 30
  11168. }, {
  11169. rule: 'repeated',
  11170. type: 'ErrorCommand',
  11171. name: 'failedPids',
  11172. id: 31
  11173. }, {
  11174. rule: 'optional',
  11175. type: 'string',
  11176. name: 'next',
  11177. id: 40
  11178. }, {
  11179. rule: 'optional',
  11180. type: 'JsonObjectMessage',
  11181. name: 'results',
  11182. id: 100
  11183. }, {
  11184. rule: 'optional',
  11185. type: 'JsonObjectMessage',
  11186. name: 'where',
  11187. id: 101
  11188. }, {
  11189. rule: 'optional',
  11190. type: 'JsonObjectMessage',
  11191. name: 'attr',
  11192. id: 103
  11193. }, {
  11194. rule: 'optional',
  11195. type: 'JsonObjectMessage',
  11196. name: 'attrModified',
  11197. id: 104
  11198. }]
  11199. }, {
  11200. name: 'RoomCommand',
  11201. syntax: 'proto2',
  11202. fields: [{
  11203. rule: 'optional',
  11204. type: 'string',
  11205. name: 'roomId',
  11206. id: 1
  11207. }, {
  11208. rule: 'optional',
  11209. type: 'string',
  11210. name: 's',
  11211. id: 2
  11212. }, {
  11213. rule: 'optional',
  11214. type: 'int64',
  11215. name: 't',
  11216. id: 3
  11217. }, {
  11218. rule: 'optional',
  11219. type: 'string',
  11220. name: 'n',
  11221. id: 4
  11222. }, {
  11223. rule: 'optional',
  11224. type: 'bool',
  11225. name: 'transient',
  11226. id: 5
  11227. }, {
  11228. rule: 'repeated',
  11229. type: 'string',
  11230. name: 'roomPeerIds',
  11231. id: 6
  11232. }, {
  11233. rule: 'optional',
  11234. type: 'string',
  11235. name: 'byPeerId',
  11236. id: 7
  11237. }]
  11238. }, {
  11239. name: 'LogsCommand',
  11240. syntax: 'proto2',
  11241. fields: [{
  11242. rule: 'optional',
  11243. type: 'string',
  11244. name: 'cid',
  11245. id: 1
  11246. }, {
  11247. rule: 'optional',
  11248. type: 'int32',
  11249. name: 'l',
  11250. id: 2
  11251. }, {
  11252. rule: 'optional',
  11253. type: 'int32',
  11254. name: 'limit',
  11255. id: 3
  11256. }, {
  11257. rule: 'optional',
  11258. type: 'int64',
  11259. name: 't',
  11260. id: 4
  11261. }, {
  11262. rule: 'optional',
  11263. type: 'int64',
  11264. name: 'tt',
  11265. id: 5
  11266. }, {
  11267. rule: 'optional',
  11268. type: 'string',
  11269. name: 'tmid',
  11270. id: 6
  11271. }, {
  11272. rule: 'optional',
  11273. type: 'string',
  11274. name: 'mid',
  11275. id: 7
  11276. }, {
  11277. rule: 'optional',
  11278. type: 'string',
  11279. name: 'checksum',
  11280. id: 8
  11281. }, {
  11282. rule: 'optional',
  11283. type: 'bool',
  11284. name: 'stored',
  11285. id: 9
  11286. }, {
  11287. rule: 'optional',
  11288. type: 'QueryDirection',
  11289. name: 'direction',
  11290. id: 10,
  11291. options: {
  11292. "default": 'OLD'
  11293. }
  11294. }, {
  11295. rule: 'optional',
  11296. type: 'bool',
  11297. name: 'tIncluded',
  11298. id: 11
  11299. }, {
  11300. rule: 'optional',
  11301. type: 'bool',
  11302. name: 'ttIncluded',
  11303. id: 12
  11304. }, {
  11305. rule: 'optional',
  11306. type: 'int32',
  11307. name: 'lctype',
  11308. id: 13
  11309. }, {
  11310. rule: 'repeated',
  11311. type: 'LogItem',
  11312. name: 'logs',
  11313. id: 105
  11314. }],
  11315. enums: [{
  11316. name: 'QueryDirection',
  11317. syntax: 'proto2',
  11318. values: [{
  11319. name: 'OLD',
  11320. id: 1
  11321. }, {
  11322. name: 'NEW',
  11323. id: 2
  11324. }]
  11325. }]
  11326. }, {
  11327. name: 'RcpCommand',
  11328. syntax: 'proto2',
  11329. fields: [{
  11330. rule: 'optional',
  11331. type: 'string',
  11332. name: 'id',
  11333. id: 1
  11334. }, {
  11335. rule: 'optional',
  11336. type: 'string',
  11337. name: 'cid',
  11338. id: 2
  11339. }, {
  11340. rule: 'optional',
  11341. type: 'int64',
  11342. name: 't',
  11343. id: 3
  11344. }, {
  11345. rule: 'optional',
  11346. type: 'bool',
  11347. name: 'read',
  11348. id: 4
  11349. }, {
  11350. rule: 'optional',
  11351. type: 'string',
  11352. name: 'from',
  11353. id: 5
  11354. }]
  11355. }, {
  11356. name: 'ReadTuple',
  11357. syntax: 'proto2',
  11358. fields: [{
  11359. rule: 'required',
  11360. type: 'string',
  11361. name: 'cid',
  11362. id: 1
  11363. }, {
  11364. rule: 'optional',
  11365. type: 'int64',
  11366. name: 'timestamp',
  11367. id: 2
  11368. }, {
  11369. rule: 'optional',
  11370. type: 'string',
  11371. name: 'mid',
  11372. id: 3
  11373. }]
  11374. }, {
  11375. name: 'MaxReadTuple',
  11376. syntax: 'proto2',
  11377. fields: [{
  11378. rule: 'optional',
  11379. type: 'string',
  11380. name: 'pid',
  11381. id: 1
  11382. }, {
  11383. rule: 'optional',
  11384. type: 'int64',
  11385. name: 'maxAckTimestamp',
  11386. id: 2
  11387. }, {
  11388. rule: 'optional',
  11389. type: 'int64',
  11390. name: 'maxReadTimestamp',
  11391. id: 3
  11392. }]
  11393. }, {
  11394. name: 'ReadCommand',
  11395. syntax: 'proto2',
  11396. fields: [{
  11397. rule: 'optional',
  11398. type: 'string',
  11399. name: 'cid',
  11400. id: 1
  11401. }, {
  11402. rule: 'repeated',
  11403. type: 'string',
  11404. name: 'cids',
  11405. id: 2
  11406. }, {
  11407. rule: 'repeated',
  11408. type: 'ReadTuple',
  11409. name: 'convs',
  11410. id: 3
  11411. }]
  11412. }, {
  11413. name: 'PresenceCommand',
  11414. syntax: 'proto2',
  11415. fields: [{
  11416. rule: 'optional',
  11417. type: 'StatusType',
  11418. name: 'status',
  11419. id: 1
  11420. }, {
  11421. rule: 'repeated',
  11422. type: 'string',
  11423. name: 'sessionPeerIds',
  11424. id: 2
  11425. }, {
  11426. rule: 'optional',
  11427. type: 'string',
  11428. name: 'cid',
  11429. id: 3
  11430. }]
  11431. }, {
  11432. name: 'ReportCommand',
  11433. syntax: 'proto2',
  11434. fields: [{
  11435. rule: 'optional',
  11436. type: 'bool',
  11437. name: 'initiative',
  11438. id: 1
  11439. }, {
  11440. rule: 'optional',
  11441. type: 'string',
  11442. name: 'type',
  11443. id: 2
  11444. }, {
  11445. rule: 'optional',
  11446. type: 'string',
  11447. name: 'data',
  11448. id: 3
  11449. }]
  11450. }, {
  11451. name: 'PatchItem',
  11452. syntax: 'proto2',
  11453. fields: [{
  11454. rule: 'optional',
  11455. type: 'string',
  11456. name: 'cid',
  11457. id: 1
  11458. }, {
  11459. rule: 'optional',
  11460. type: 'string',
  11461. name: 'mid',
  11462. id: 2
  11463. }, {
  11464. rule: 'optional',
  11465. type: 'int64',
  11466. name: 'timestamp',
  11467. id: 3
  11468. }, {
  11469. rule: 'optional',
  11470. type: 'bool',
  11471. name: 'recall',
  11472. id: 4
  11473. }, {
  11474. rule: 'optional',
  11475. type: 'string',
  11476. name: 'data',
  11477. id: 5
  11478. }, {
  11479. rule: 'optional',
  11480. type: 'int64',
  11481. name: 'patchTimestamp',
  11482. id: 6
  11483. }, {
  11484. rule: 'optional',
  11485. type: 'string',
  11486. name: 'from',
  11487. id: 7
  11488. }, {
  11489. rule: 'optional',
  11490. type: 'bytes',
  11491. name: 'binaryMsg',
  11492. id: 8
  11493. }, {
  11494. rule: 'optional',
  11495. type: 'bool',
  11496. name: 'mentionAll',
  11497. id: 9
  11498. }, {
  11499. rule: 'repeated',
  11500. type: 'string',
  11501. name: 'mentionPids',
  11502. id: 10
  11503. }, {
  11504. rule: 'optional',
  11505. type: 'int64',
  11506. name: 'patchCode',
  11507. id: 11
  11508. }, {
  11509. rule: 'optional',
  11510. type: 'string',
  11511. name: 'patchReason',
  11512. id: 12
  11513. }]
  11514. }, {
  11515. name: 'PatchCommand',
  11516. syntax: 'proto2',
  11517. fields: [{
  11518. rule: 'repeated',
  11519. type: 'PatchItem',
  11520. name: 'patches',
  11521. id: 1
  11522. }, {
  11523. rule: 'optional',
  11524. type: 'int64',
  11525. name: 'lastPatchTime',
  11526. id: 2
  11527. }]
  11528. }, {
  11529. name: 'PubsubCommand',
  11530. syntax: 'proto2',
  11531. fields: [{
  11532. rule: 'optional',
  11533. type: 'string',
  11534. name: 'cid',
  11535. id: 1
  11536. }, {
  11537. rule: 'repeated',
  11538. type: 'string',
  11539. name: 'cids',
  11540. id: 2
  11541. }, {
  11542. rule: 'optional',
  11543. type: 'string',
  11544. name: 'topic',
  11545. id: 3
  11546. }, {
  11547. rule: 'optional',
  11548. type: 'string',
  11549. name: 'subtopic',
  11550. id: 4
  11551. }, {
  11552. rule: 'repeated',
  11553. type: 'string',
  11554. name: 'topics',
  11555. id: 5
  11556. }, {
  11557. rule: 'repeated',
  11558. type: 'string',
  11559. name: 'subtopics',
  11560. id: 6
  11561. }, {
  11562. rule: 'optional',
  11563. type: 'JsonObjectMessage',
  11564. name: 'results',
  11565. id: 7
  11566. }]
  11567. }, {
  11568. name: 'BlacklistCommand',
  11569. syntax: 'proto2',
  11570. fields: [{
  11571. rule: 'optional',
  11572. type: 'string',
  11573. name: 'srcCid',
  11574. id: 1
  11575. }, {
  11576. rule: 'repeated',
  11577. type: 'string',
  11578. name: 'toPids',
  11579. id: 2
  11580. }, {
  11581. rule: 'optional',
  11582. type: 'string',
  11583. name: 'srcPid',
  11584. id: 3
  11585. }, {
  11586. rule: 'repeated',
  11587. type: 'string',
  11588. name: 'toCids',
  11589. id: 4
  11590. }, {
  11591. rule: 'optional',
  11592. type: 'int32',
  11593. name: 'limit',
  11594. id: 5
  11595. }, {
  11596. rule: 'optional',
  11597. type: 'string',
  11598. name: 'next',
  11599. id: 6
  11600. }, {
  11601. rule: 'repeated',
  11602. type: 'string',
  11603. name: 'blockedPids',
  11604. id: 8
  11605. }, {
  11606. rule: 'repeated',
  11607. type: 'string',
  11608. name: 'blockedCids',
  11609. id: 9
  11610. }, {
  11611. rule: 'repeated',
  11612. type: 'string',
  11613. name: 'allowedPids',
  11614. id: 10
  11615. }, {
  11616. rule: 'repeated',
  11617. type: 'ErrorCommand',
  11618. name: 'failedPids',
  11619. id: 11
  11620. }, {
  11621. rule: 'optional',
  11622. type: 'int64',
  11623. name: 't',
  11624. id: 12
  11625. }, {
  11626. rule: 'optional',
  11627. type: 'string',
  11628. name: 'n',
  11629. id: 13
  11630. }, {
  11631. rule: 'optional',
  11632. type: 'string',
  11633. name: 's',
  11634. id: 14
  11635. }]
  11636. }, {
  11637. name: 'GenericCommand',
  11638. syntax: 'proto2',
  11639. fields: [{
  11640. rule: 'optional',
  11641. type: 'CommandType',
  11642. name: 'cmd',
  11643. id: 1
  11644. }, {
  11645. rule: 'optional',
  11646. type: 'OpType',
  11647. name: 'op',
  11648. id: 2
  11649. }, {
  11650. rule: 'optional',
  11651. type: 'string',
  11652. name: 'appId',
  11653. id: 3
  11654. }, {
  11655. rule: 'optional',
  11656. type: 'string',
  11657. name: 'peerId',
  11658. id: 4
  11659. }, {
  11660. rule: 'optional',
  11661. type: 'int32',
  11662. name: 'i',
  11663. id: 5
  11664. }, {
  11665. rule: 'optional',
  11666. type: 'string',
  11667. name: 'installationId',
  11668. id: 6
  11669. }, {
  11670. rule: 'optional',
  11671. type: 'int32',
  11672. name: 'priority',
  11673. id: 7
  11674. }, {
  11675. rule: 'optional',
  11676. type: 'int32',
  11677. name: 'service',
  11678. id: 8
  11679. }, {
  11680. rule: 'optional',
  11681. type: 'int64',
  11682. name: 'serverTs',
  11683. id: 9
  11684. }, {
  11685. rule: 'optional',
  11686. type: 'int64',
  11687. name: 'clientTs',
  11688. id: 10
  11689. }, {
  11690. rule: 'optional',
  11691. type: 'int32',
  11692. name: 'notificationType',
  11693. id: 11
  11694. }, {
  11695. rule: 'optional',
  11696. type: 'DataCommand',
  11697. name: 'dataMessage',
  11698. id: 101
  11699. }, {
  11700. rule: 'optional',
  11701. type: 'SessionCommand',
  11702. name: 'sessionMessage',
  11703. id: 102
  11704. }, {
  11705. rule: 'optional',
  11706. type: 'ErrorCommand',
  11707. name: 'errorMessage',
  11708. id: 103
  11709. }, {
  11710. rule: 'optional',
  11711. type: 'DirectCommand',
  11712. name: 'directMessage',
  11713. id: 104
  11714. }, {
  11715. rule: 'optional',
  11716. type: 'AckCommand',
  11717. name: 'ackMessage',
  11718. id: 105
  11719. }, {
  11720. rule: 'optional',
  11721. type: 'UnreadCommand',
  11722. name: 'unreadMessage',
  11723. id: 106
  11724. }, {
  11725. rule: 'optional',
  11726. type: 'ReadCommand',
  11727. name: 'readMessage',
  11728. id: 107
  11729. }, {
  11730. rule: 'optional',
  11731. type: 'RcpCommand',
  11732. name: 'rcpMessage',
  11733. id: 108
  11734. }, {
  11735. rule: 'optional',
  11736. type: 'LogsCommand',
  11737. name: 'logsMessage',
  11738. id: 109
  11739. }, {
  11740. rule: 'optional',
  11741. type: 'ConvCommand',
  11742. name: 'convMessage',
  11743. id: 110
  11744. }, {
  11745. rule: 'optional',
  11746. type: 'RoomCommand',
  11747. name: 'roomMessage',
  11748. id: 111
  11749. }, {
  11750. rule: 'optional',
  11751. type: 'PresenceCommand',
  11752. name: 'presenceMessage',
  11753. id: 112
  11754. }, {
  11755. rule: 'optional',
  11756. type: 'ReportCommand',
  11757. name: 'reportMessage',
  11758. id: 113
  11759. }, {
  11760. rule: 'optional',
  11761. type: 'PatchCommand',
  11762. name: 'patchMessage',
  11763. id: 114
  11764. }, {
  11765. rule: 'optional',
  11766. type: 'PubsubCommand',
  11767. name: 'pubsubMessage',
  11768. id: 115
  11769. }, {
  11770. rule: 'optional',
  11771. type: 'BlacklistCommand',
  11772. name: 'blacklistMessage',
  11773. id: 116
  11774. }]
  11775. }],
  11776. enums: [{
  11777. name: 'CommandType',
  11778. syntax: 'proto2',
  11779. values: [{
  11780. name: 'session',
  11781. id: 0
  11782. }, {
  11783. name: 'conv',
  11784. id: 1
  11785. }, {
  11786. name: 'direct',
  11787. id: 2
  11788. }, {
  11789. name: 'ack',
  11790. id: 3
  11791. }, {
  11792. name: 'rcp',
  11793. id: 4
  11794. }, {
  11795. name: 'unread',
  11796. id: 5
  11797. }, {
  11798. name: 'logs',
  11799. id: 6
  11800. }, {
  11801. name: 'error',
  11802. id: 7
  11803. }, {
  11804. name: 'login',
  11805. id: 8
  11806. }, {
  11807. name: 'data',
  11808. id: 9
  11809. }, {
  11810. name: 'room',
  11811. id: 10
  11812. }, {
  11813. name: 'read',
  11814. id: 11
  11815. }, {
  11816. name: 'presence',
  11817. id: 12
  11818. }, {
  11819. name: 'report',
  11820. id: 13
  11821. }, {
  11822. name: 'echo',
  11823. id: 14
  11824. }, {
  11825. name: 'loggedin',
  11826. id: 15
  11827. }, {
  11828. name: 'logout',
  11829. id: 16
  11830. }, {
  11831. name: 'loggedout',
  11832. id: 17
  11833. }, {
  11834. name: 'patch',
  11835. id: 18
  11836. }, {
  11837. name: 'pubsub',
  11838. id: 19
  11839. }, {
  11840. name: 'blacklist',
  11841. id: 20
  11842. }, {
  11843. name: 'goaway',
  11844. id: 21
  11845. }]
  11846. }, {
  11847. name: 'OpType',
  11848. syntax: 'proto2',
  11849. values: [{
  11850. name: 'open',
  11851. id: 1
  11852. }, {
  11853. name: 'add',
  11854. id: 2
  11855. }, {
  11856. name: 'remove',
  11857. id: 3
  11858. }, {
  11859. name: 'close',
  11860. id: 4
  11861. }, {
  11862. name: 'opened',
  11863. id: 5
  11864. }, {
  11865. name: 'closed',
  11866. id: 6
  11867. }, {
  11868. name: 'query',
  11869. id: 7
  11870. }, {
  11871. name: 'query_result',
  11872. id: 8
  11873. }, {
  11874. name: 'conflict',
  11875. id: 9
  11876. }, {
  11877. name: 'added',
  11878. id: 10
  11879. }, {
  11880. name: 'removed',
  11881. id: 11
  11882. }, {
  11883. name: 'refresh',
  11884. id: 12
  11885. }, {
  11886. name: 'refreshed',
  11887. id: 13
  11888. }, {
  11889. name: 'start',
  11890. id: 30
  11891. }, {
  11892. name: 'started',
  11893. id: 31
  11894. }, {
  11895. name: 'joined',
  11896. id: 32
  11897. }, {
  11898. name: 'members_joined',
  11899. id: 33
  11900. }, {
  11901. name: 'left',
  11902. id: 39
  11903. }, {
  11904. name: 'members_left',
  11905. id: 40
  11906. }, {
  11907. name: 'results',
  11908. id: 42
  11909. }, {
  11910. name: 'count',
  11911. id: 43
  11912. }, {
  11913. name: 'result',
  11914. id: 44
  11915. }, {
  11916. name: 'update',
  11917. id: 45
  11918. }, {
  11919. name: 'updated',
  11920. id: 46
  11921. }, {
  11922. name: 'mute',
  11923. id: 47
  11924. }, {
  11925. name: 'unmute',
  11926. id: 48
  11927. }, {
  11928. name: 'status',
  11929. id: 49
  11930. }, {
  11931. name: 'members',
  11932. id: 50
  11933. }, {
  11934. name: 'max_read',
  11935. id: 51
  11936. }, {
  11937. name: 'is_member',
  11938. id: 52
  11939. }, {
  11940. name: 'member_info_update',
  11941. id: 53
  11942. }, {
  11943. name: 'member_info_updated',
  11944. id: 54
  11945. }, {
  11946. name: 'member_info_changed',
  11947. id: 55
  11948. }, {
  11949. name: 'join',
  11950. id: 80
  11951. }, {
  11952. name: 'invite',
  11953. id: 81
  11954. }, {
  11955. name: 'leave',
  11956. id: 82
  11957. }, {
  11958. name: 'kick',
  11959. id: 83
  11960. }, {
  11961. name: 'reject',
  11962. id: 84
  11963. }, {
  11964. name: 'invited',
  11965. id: 85
  11966. }, {
  11967. name: 'kicked',
  11968. id: 86
  11969. }, {
  11970. name: 'upload',
  11971. id: 100
  11972. }, {
  11973. name: 'uploaded',
  11974. id: 101
  11975. }, {
  11976. name: 'subscribe',
  11977. id: 120
  11978. }, {
  11979. name: 'subscribed',
  11980. id: 121
  11981. }, {
  11982. name: 'unsubscribe',
  11983. id: 122
  11984. }, {
  11985. name: 'unsubscribed',
  11986. id: 123
  11987. }, {
  11988. name: 'is_subscribed',
  11989. id: 124
  11990. }, {
  11991. name: 'modify',
  11992. id: 150
  11993. }, {
  11994. name: 'modified',
  11995. id: 151
  11996. }, {
  11997. name: 'block',
  11998. id: 170
  11999. }, {
  12000. name: 'unblock',
  12001. id: 171
  12002. }, {
  12003. name: 'blocked',
  12004. id: 172
  12005. }, {
  12006. name: 'unblocked',
  12007. id: 173
  12008. }, {
  12009. name: 'members_blocked',
  12010. id: 174
  12011. }, {
  12012. name: 'members_unblocked',
  12013. id: 175
  12014. }, {
  12015. name: 'check_block',
  12016. id: 176
  12017. }, {
  12018. name: 'check_result',
  12019. id: 177
  12020. }, {
  12021. name: 'add_shutup',
  12022. id: 180
  12023. }, {
  12024. name: 'remove_shutup',
  12025. id: 181
  12026. }, {
  12027. name: 'query_shutup',
  12028. id: 182
  12029. }, {
  12030. name: 'shutup_added',
  12031. id: 183
  12032. }, {
  12033. name: 'shutup_removed',
  12034. id: 184
  12035. }, {
  12036. name: 'shutup_result',
  12037. id: 185
  12038. }, {
  12039. name: 'shutuped',
  12040. id: 186
  12041. }, {
  12042. name: 'unshutuped',
  12043. id: 187
  12044. }, {
  12045. name: 'members_shutuped',
  12046. id: 188
  12047. }, {
  12048. name: 'members_unshutuped',
  12049. id: 189
  12050. }, {
  12051. name: 'check_shutup',
  12052. id: 190
  12053. }]
  12054. }, {
  12055. name: 'StatusType',
  12056. syntax: 'proto2',
  12057. values: [{
  12058. name: 'on',
  12059. id: 1
  12060. }, {
  12061. name: 'off',
  12062. id: 2
  12063. }]
  12064. }],
  12065. isNamespace: true
  12066. }).build();
  12067. var _messages$push_server = messageCompiled.push_server.messages2,
  12068. JsonObjectMessage = _messages$push_server.JsonObjectMessage,
  12069. UnreadTuple = _messages$push_server.UnreadTuple,
  12070. LogItem = _messages$push_server.LogItem,
  12071. DataCommand = _messages$push_server.DataCommand,
  12072. SessionCommand = _messages$push_server.SessionCommand,
  12073. ErrorCommand = _messages$push_server.ErrorCommand,
  12074. DirectCommand = _messages$push_server.DirectCommand,
  12075. AckCommand = _messages$push_server.AckCommand,
  12076. UnreadCommand = _messages$push_server.UnreadCommand,
  12077. ConvCommand = _messages$push_server.ConvCommand,
  12078. RoomCommand = _messages$push_server.RoomCommand,
  12079. LogsCommand = _messages$push_server.LogsCommand,
  12080. RcpCommand = _messages$push_server.RcpCommand,
  12081. ReadTuple = _messages$push_server.ReadTuple,
  12082. MaxReadTuple = _messages$push_server.MaxReadTuple,
  12083. ReadCommand = _messages$push_server.ReadCommand,
  12084. PresenceCommand = _messages$push_server.PresenceCommand,
  12085. ReportCommand = _messages$push_server.ReportCommand,
  12086. GenericCommand = _messages$push_server.GenericCommand,
  12087. BlacklistCommand = _messages$push_server.BlacklistCommand,
  12088. PatchCommand = _messages$push_server.PatchCommand,
  12089. PatchItem = _messages$push_server.PatchItem,
  12090. ConvMemberInfo = _messages$push_server.ConvMemberInfo,
  12091. CommandType = _messages$push_server.CommandType,
  12092. OpType = _messages$push_server.OpType,
  12093. StatusType = _messages$push_server.StatusType;
  12094. var message = /*#__PURE__*/Object.freeze({
  12095. __proto__: null,
  12096. JsonObjectMessage: JsonObjectMessage,
  12097. UnreadTuple: UnreadTuple,
  12098. LogItem: LogItem,
  12099. DataCommand: DataCommand,
  12100. SessionCommand: SessionCommand,
  12101. ErrorCommand: ErrorCommand,
  12102. DirectCommand: DirectCommand,
  12103. AckCommand: AckCommand,
  12104. UnreadCommand: UnreadCommand,
  12105. ConvCommand: ConvCommand,
  12106. RoomCommand: RoomCommand,
  12107. LogsCommand: LogsCommand,
  12108. RcpCommand: RcpCommand,
  12109. ReadTuple: ReadTuple,
  12110. MaxReadTuple: MaxReadTuple,
  12111. ReadCommand: ReadCommand,
  12112. PresenceCommand: PresenceCommand,
  12113. ReportCommand: ReportCommand,
  12114. GenericCommand: GenericCommand,
  12115. BlacklistCommand: BlacklistCommand,
  12116. PatchCommand: PatchCommand,
  12117. PatchItem: PatchItem,
  12118. ConvMemberInfo: ConvMemberInfo,
  12119. CommandType: CommandType,
  12120. OpType: OpType,
  12121. StatusType: StatusType
  12122. });
  12123. var eventemitter3 = createCommonjsModule(function (module) {
  12124. var has = Object.prototype.hasOwnProperty
  12125. , prefix = '~';
  12126. /**
  12127. * Constructor to create a storage for our `EE` objects.
  12128. * An `Events` instance is a plain object whose properties are event names.
  12129. *
  12130. * @constructor
  12131. * @private
  12132. */
  12133. function Events() {}
  12134. //
  12135. // We try to not inherit from `Object.prototype`. In some engines creating an
  12136. // instance in this way is faster than calling `Object.create(null)` directly.
  12137. // If `Object.create(null)` is not supported we prefix the event names with a
  12138. // character to make sure that the built-in object properties are not
  12139. // overridden or used as an attack vector.
  12140. //
  12141. if (Object.create) {
  12142. Events.prototype = Object.create(null);
  12143. //
  12144. // This hack is needed because the `__proto__` property is still inherited in
  12145. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  12146. //
  12147. if (!new Events().__proto__) prefix = false;
  12148. }
  12149. /**
  12150. * Representation of a single event listener.
  12151. *
  12152. * @param {Function} fn The listener function.
  12153. * @param {*} context The context to invoke the listener with.
  12154. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  12155. * @constructor
  12156. * @private
  12157. */
  12158. function EE(fn, context, once) {
  12159. this.fn = fn;
  12160. this.context = context;
  12161. this.once = once || false;
  12162. }
  12163. /**
  12164. * Add a listener for a given event.
  12165. *
  12166. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12167. * @param {(String|Symbol)} event The event name.
  12168. * @param {Function} fn The listener function.
  12169. * @param {*} context The context to invoke the listener with.
  12170. * @param {Boolean} once Specify if the listener is a one-time listener.
  12171. * @returns {EventEmitter}
  12172. * @private
  12173. */
  12174. function addListener(emitter, event, fn, context, once) {
  12175. if (typeof fn !== 'function') {
  12176. throw new TypeError('The listener must be a function');
  12177. }
  12178. var listener = new EE(fn, context || emitter, once)
  12179. , evt = prefix ? prefix + event : event;
  12180. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  12181. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  12182. else emitter._events[evt] = [emitter._events[evt], listener];
  12183. return emitter;
  12184. }
  12185. /**
  12186. * Clear event by name.
  12187. *
  12188. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  12189. * @param {(String|Symbol)} evt The Event name.
  12190. * @private
  12191. */
  12192. function clearEvent(emitter, evt) {
  12193. if (--emitter._eventsCount === 0) emitter._events = new Events();
  12194. else delete emitter._events[evt];
  12195. }
  12196. /**
  12197. * Minimal `EventEmitter` interface that is molded against the Node.js
  12198. * `EventEmitter` interface.
  12199. *
  12200. * @constructor
  12201. * @public
  12202. */
  12203. function EventEmitter() {
  12204. this._events = new Events();
  12205. this._eventsCount = 0;
  12206. }
  12207. /**
  12208. * Return an array listing the events for which the emitter has registered
  12209. * listeners.
  12210. *
  12211. * @returns {Array}
  12212. * @public
  12213. */
  12214. EventEmitter.prototype.eventNames = function eventNames() {
  12215. var names = []
  12216. , events
  12217. , name;
  12218. if (this._eventsCount === 0) return names;
  12219. for (name in (events = this._events)) {
  12220. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  12221. }
  12222. if (Object.getOwnPropertySymbols) {
  12223. return names.concat(Object.getOwnPropertySymbols(events));
  12224. }
  12225. return names;
  12226. };
  12227. /**
  12228. * Return the listeners registered for a given event.
  12229. *
  12230. * @param {(String|Symbol)} event The event name.
  12231. * @returns {Array} The registered listeners.
  12232. * @public
  12233. */
  12234. EventEmitter.prototype.listeners = function listeners(event) {
  12235. var evt = prefix ? prefix + event : event
  12236. , handlers = this._events[evt];
  12237. if (!handlers) return [];
  12238. if (handlers.fn) return [handlers.fn];
  12239. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  12240. ee[i] = handlers[i].fn;
  12241. }
  12242. return ee;
  12243. };
  12244. /**
  12245. * Return the number of listeners listening to a given event.
  12246. *
  12247. * @param {(String|Symbol)} event The event name.
  12248. * @returns {Number} The number of listeners.
  12249. * @public
  12250. */
  12251. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  12252. var evt = prefix ? prefix + event : event
  12253. , listeners = this._events[evt];
  12254. if (!listeners) return 0;
  12255. if (listeners.fn) return 1;
  12256. return listeners.length;
  12257. };
  12258. /**
  12259. * Calls each of the listeners registered for a given event.
  12260. *
  12261. * @param {(String|Symbol)} event The event name.
  12262. * @returns {Boolean} `true` if the event had listeners, else `false`.
  12263. * @public
  12264. */
  12265. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  12266. var evt = prefix ? prefix + event : event;
  12267. if (!this._events[evt]) return false;
  12268. var listeners = this._events[evt]
  12269. , len = arguments.length
  12270. , args
  12271. , i;
  12272. if (listeners.fn) {
  12273. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  12274. switch (len) {
  12275. case 1: return listeners.fn.call(listeners.context), true;
  12276. case 2: return listeners.fn.call(listeners.context, a1), true;
  12277. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  12278. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  12279. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  12280. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  12281. }
  12282. for (i = 1, args = new Array(len -1); i < len; i++) {
  12283. args[i - 1] = arguments[i];
  12284. }
  12285. listeners.fn.apply(listeners.context, args);
  12286. } else {
  12287. var length = listeners.length
  12288. , j;
  12289. for (i = 0; i < length; i++) {
  12290. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  12291. switch (len) {
  12292. case 1: listeners[i].fn.call(listeners[i].context); break;
  12293. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  12294. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  12295. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  12296. default:
  12297. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  12298. args[j - 1] = arguments[j];
  12299. }
  12300. listeners[i].fn.apply(listeners[i].context, args);
  12301. }
  12302. }
  12303. }
  12304. return true;
  12305. };
  12306. /**
  12307. * Add a listener for a given event.
  12308. *
  12309. * @param {(String|Symbol)} event The event name.
  12310. * @param {Function} fn The listener function.
  12311. * @param {*} [context=this] The context to invoke the listener with.
  12312. * @returns {EventEmitter} `this`.
  12313. * @public
  12314. */
  12315. EventEmitter.prototype.on = function on(event, fn, context) {
  12316. return addListener(this, event, fn, context, false);
  12317. };
  12318. /**
  12319. * Add a one-time listener for a given event.
  12320. *
  12321. * @param {(String|Symbol)} event The event name.
  12322. * @param {Function} fn The listener function.
  12323. * @param {*} [context=this] The context to invoke the listener with.
  12324. * @returns {EventEmitter} `this`.
  12325. * @public
  12326. */
  12327. EventEmitter.prototype.once = function once(event, fn, context) {
  12328. return addListener(this, event, fn, context, true);
  12329. };
  12330. /**
  12331. * Remove the listeners of a given event.
  12332. *
  12333. * @param {(String|Symbol)} event The event name.
  12334. * @param {Function} fn Only remove the listeners that match this function.
  12335. * @param {*} context Only remove the listeners that have this context.
  12336. * @param {Boolean} once Only remove one-time listeners.
  12337. * @returns {EventEmitter} `this`.
  12338. * @public
  12339. */
  12340. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  12341. var evt = prefix ? prefix + event : event;
  12342. if (!this._events[evt]) return this;
  12343. if (!fn) {
  12344. clearEvent(this, evt);
  12345. return this;
  12346. }
  12347. var listeners = this._events[evt];
  12348. if (listeners.fn) {
  12349. if (
  12350. listeners.fn === fn &&
  12351. (!once || listeners.once) &&
  12352. (!context || listeners.context === context)
  12353. ) {
  12354. clearEvent(this, evt);
  12355. }
  12356. } else {
  12357. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  12358. if (
  12359. listeners[i].fn !== fn ||
  12360. (once && !listeners[i].once) ||
  12361. (context && listeners[i].context !== context)
  12362. ) {
  12363. events.push(listeners[i]);
  12364. }
  12365. }
  12366. //
  12367. // Reset the array, or remove it completely if we have no more listeners.
  12368. //
  12369. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  12370. else clearEvent(this, evt);
  12371. }
  12372. return this;
  12373. };
  12374. /**
  12375. * Remove all listeners, or those of the specified event.
  12376. *
  12377. * @param {(String|Symbol)} [event] The event name.
  12378. * @returns {EventEmitter} `this`.
  12379. * @public
  12380. */
  12381. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  12382. var evt;
  12383. if (event) {
  12384. evt = prefix ? prefix + event : event;
  12385. if (this._events[evt]) clearEvent(this, evt);
  12386. } else {
  12387. this._events = new Events();
  12388. this._eventsCount = 0;
  12389. }
  12390. return this;
  12391. };
  12392. //
  12393. // Alias methods names because people roll like that.
  12394. //
  12395. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  12396. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  12397. //
  12398. // Expose the prefix.
  12399. //
  12400. EventEmitter.prefixed = prefix;
  12401. //
  12402. // Allow `EventEmitter` to be imported as module namespace.
  12403. //
  12404. EventEmitter.EventEmitter = EventEmitter;
  12405. //
  12406. // Expose the module.
  12407. //
  12408. {
  12409. module.exports = EventEmitter;
  12410. }
  12411. });
  12412. var runtime_1 = createCommonjsModule(function (module) {
  12413. /**
  12414. * Copyright (c) 2014-present, Facebook, Inc.
  12415. *
  12416. * This source code is licensed under the MIT license found in the
  12417. * LICENSE file in the root directory of this source tree.
  12418. */
  12419. var runtime = (function (exports) {
  12420. var Op = Object.prototype;
  12421. var hasOwn = Op.hasOwnProperty;
  12422. var undefined$1; // More compressible than void 0.
  12423. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  12424. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  12425. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  12426. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  12427. function wrap(innerFn, outerFn, self, tryLocsList) {
  12428. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  12429. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  12430. var generator = Object.create(protoGenerator.prototype);
  12431. var context = new Context(tryLocsList || []);
  12432. // The ._invoke method unifies the implementations of the .next,
  12433. // .throw, and .return methods.
  12434. generator._invoke = makeInvokeMethod(innerFn, self, context);
  12435. return generator;
  12436. }
  12437. exports.wrap = wrap;
  12438. // Try/catch helper to minimize deoptimizations. Returns a completion
  12439. // record like context.tryEntries[i].completion. This interface could
  12440. // have been (and was previously) designed to take a closure to be
  12441. // invoked without arguments, but in all the cases we care about we
  12442. // already have an existing method we want to call, so there's no need
  12443. // to create a new function object. We can even get away with assuming
  12444. // the method takes exactly one argument, since that happens to be true
  12445. // in every case, so we don't have to touch the arguments object. The
  12446. // only additional allocation required is the completion record, which
  12447. // has a stable shape and so hopefully should be cheap to allocate.
  12448. function tryCatch(fn, obj, arg) {
  12449. try {
  12450. return { type: "normal", arg: fn.call(obj, arg) };
  12451. } catch (err) {
  12452. return { type: "throw", arg: err };
  12453. }
  12454. }
  12455. var GenStateSuspendedStart = "suspendedStart";
  12456. var GenStateSuspendedYield = "suspendedYield";
  12457. var GenStateExecuting = "executing";
  12458. var GenStateCompleted = "completed";
  12459. // Returning this object from the innerFn has the same effect as
  12460. // breaking out of the dispatch switch statement.
  12461. var ContinueSentinel = {};
  12462. // Dummy constructor functions that we use as the .constructor and
  12463. // .constructor.prototype properties for functions that return Generator
  12464. // objects. For full spec compliance, you may wish to configure your
  12465. // minifier not to mangle the names of these two functions.
  12466. function Generator() {}
  12467. function GeneratorFunction() {}
  12468. function GeneratorFunctionPrototype() {}
  12469. // This is a polyfill for %IteratorPrototype% for environments that
  12470. // don't natively support it.
  12471. var IteratorPrototype = {};
  12472. IteratorPrototype[iteratorSymbol] = function () {
  12473. return this;
  12474. };
  12475. var getProto = Object.getPrototypeOf;
  12476. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  12477. if (NativeIteratorPrototype &&
  12478. NativeIteratorPrototype !== Op &&
  12479. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  12480. // This environment has a native %IteratorPrototype%; use it instead
  12481. // of the polyfill.
  12482. IteratorPrototype = NativeIteratorPrototype;
  12483. }
  12484. var Gp = GeneratorFunctionPrototype.prototype =
  12485. Generator.prototype = Object.create(IteratorPrototype);
  12486. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  12487. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  12488. GeneratorFunctionPrototype[toStringTagSymbol] =
  12489. GeneratorFunction.displayName = "GeneratorFunction";
  12490. // Helper for defining the .next, .throw, and .return methods of the
  12491. // Iterator interface in terms of a single ._invoke method.
  12492. function defineIteratorMethods(prototype) {
  12493. ["next", "throw", "return"].forEach(function(method) {
  12494. prototype[method] = function(arg) {
  12495. return this._invoke(method, arg);
  12496. };
  12497. });
  12498. }
  12499. exports.isGeneratorFunction = function(genFun) {
  12500. var ctor = typeof genFun === "function" && genFun.constructor;
  12501. return ctor
  12502. ? ctor === GeneratorFunction ||
  12503. // For the native GeneratorFunction constructor, the best we can
  12504. // do is to check its .name property.
  12505. (ctor.displayName || ctor.name) === "GeneratorFunction"
  12506. : false;
  12507. };
  12508. exports.mark = function(genFun) {
  12509. if (Object.setPrototypeOf) {
  12510. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  12511. } else {
  12512. genFun.__proto__ = GeneratorFunctionPrototype;
  12513. if (!(toStringTagSymbol in genFun)) {
  12514. genFun[toStringTagSymbol] = "GeneratorFunction";
  12515. }
  12516. }
  12517. genFun.prototype = Object.create(Gp);
  12518. return genFun;
  12519. };
  12520. // Within the body of any async function, `await x` is transformed to
  12521. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  12522. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  12523. // meant to be awaited.
  12524. exports.awrap = function(arg) {
  12525. return { __await: arg };
  12526. };
  12527. function AsyncIterator(generator, PromiseImpl) {
  12528. function invoke(method, arg, resolve, reject) {
  12529. var record = tryCatch(generator[method], generator, arg);
  12530. if (record.type === "throw") {
  12531. reject(record.arg);
  12532. } else {
  12533. var result = record.arg;
  12534. var value = result.value;
  12535. if (value &&
  12536. typeof value === "object" &&
  12537. hasOwn.call(value, "__await")) {
  12538. return PromiseImpl.resolve(value.__await).then(function(value) {
  12539. invoke("next", value, resolve, reject);
  12540. }, function(err) {
  12541. invoke("throw", err, resolve, reject);
  12542. });
  12543. }
  12544. return PromiseImpl.resolve(value).then(function(unwrapped) {
  12545. // When a yielded Promise is resolved, its final value becomes
  12546. // the .value of the Promise<{value,done}> result for the
  12547. // current iteration.
  12548. result.value = unwrapped;
  12549. resolve(result);
  12550. }, function(error) {
  12551. // If a rejected Promise was yielded, throw the rejection back
  12552. // into the async generator function so it can be handled there.
  12553. return invoke("throw", error, resolve, reject);
  12554. });
  12555. }
  12556. }
  12557. var previousPromise;
  12558. function enqueue(method, arg) {
  12559. function callInvokeWithMethodAndArg() {
  12560. return new PromiseImpl(function(resolve, reject) {
  12561. invoke(method, arg, resolve, reject);
  12562. });
  12563. }
  12564. return previousPromise =
  12565. // If enqueue has been called before, then we want to wait until
  12566. // all previous Promises have been resolved before calling invoke,
  12567. // so that results are always delivered in the correct order. If
  12568. // enqueue has not been called before, then it is important to
  12569. // call invoke immediately, without waiting on a callback to fire,
  12570. // so that the async generator function has the opportunity to do
  12571. // any necessary setup in a predictable way. This predictability
  12572. // is why the Promise constructor synchronously invokes its
  12573. // executor callback, and why async functions synchronously
  12574. // execute code before the first await. Since we implement simple
  12575. // async functions in terms of async generators, it is especially
  12576. // important to get this right, even though it requires care.
  12577. previousPromise ? previousPromise.then(
  12578. callInvokeWithMethodAndArg,
  12579. // Avoid propagating failures to Promises returned by later
  12580. // invocations of the iterator.
  12581. callInvokeWithMethodAndArg
  12582. ) : callInvokeWithMethodAndArg();
  12583. }
  12584. // Define the unified helper method that is used to implement .next,
  12585. // .throw, and .return (see defineIteratorMethods).
  12586. this._invoke = enqueue;
  12587. }
  12588. defineIteratorMethods(AsyncIterator.prototype);
  12589. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  12590. return this;
  12591. };
  12592. exports.AsyncIterator = AsyncIterator;
  12593. // Note that simple async functions are implemented on top of
  12594. // AsyncIterator objects; they just return a Promise for the value of
  12595. // the final result produced by the iterator.
  12596. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  12597. if (PromiseImpl === void 0) PromiseImpl = Promise;
  12598. var iter = new AsyncIterator(
  12599. wrap(innerFn, outerFn, self, tryLocsList),
  12600. PromiseImpl
  12601. );
  12602. return exports.isGeneratorFunction(outerFn)
  12603. ? iter // If outerFn is a generator, return the full iterator.
  12604. : iter.next().then(function(result) {
  12605. return result.done ? result.value : iter.next();
  12606. });
  12607. };
  12608. function makeInvokeMethod(innerFn, self, context) {
  12609. var state = GenStateSuspendedStart;
  12610. return function invoke(method, arg) {
  12611. if (state === GenStateExecuting) {
  12612. throw new Error("Generator is already running");
  12613. }
  12614. if (state === GenStateCompleted) {
  12615. if (method === "throw") {
  12616. throw arg;
  12617. }
  12618. // Be forgiving, per 25.3.3.3.3 of the spec:
  12619. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  12620. return doneResult();
  12621. }
  12622. context.method = method;
  12623. context.arg = arg;
  12624. while (true) {
  12625. var delegate = context.delegate;
  12626. if (delegate) {
  12627. var delegateResult = maybeInvokeDelegate(delegate, context);
  12628. if (delegateResult) {
  12629. if (delegateResult === ContinueSentinel) continue;
  12630. return delegateResult;
  12631. }
  12632. }
  12633. if (context.method === "next") {
  12634. // Setting context._sent for legacy support of Babel's
  12635. // function.sent implementation.
  12636. context.sent = context._sent = context.arg;
  12637. } else if (context.method === "throw") {
  12638. if (state === GenStateSuspendedStart) {
  12639. state = GenStateCompleted;
  12640. throw context.arg;
  12641. }
  12642. context.dispatchException(context.arg);
  12643. } else if (context.method === "return") {
  12644. context.abrupt("return", context.arg);
  12645. }
  12646. state = GenStateExecuting;
  12647. var record = tryCatch(innerFn, self, context);
  12648. if (record.type === "normal") {
  12649. // If an exception is thrown from innerFn, we leave state ===
  12650. // GenStateExecuting and loop back for another invocation.
  12651. state = context.done
  12652. ? GenStateCompleted
  12653. : GenStateSuspendedYield;
  12654. if (record.arg === ContinueSentinel) {
  12655. continue;
  12656. }
  12657. return {
  12658. value: record.arg,
  12659. done: context.done
  12660. };
  12661. } else if (record.type === "throw") {
  12662. state = GenStateCompleted;
  12663. // Dispatch the exception by looping back around to the
  12664. // context.dispatchException(context.arg) call above.
  12665. context.method = "throw";
  12666. context.arg = record.arg;
  12667. }
  12668. }
  12669. };
  12670. }
  12671. // Call delegate.iterator[context.method](context.arg) and handle the
  12672. // result, either by returning a { value, done } result from the
  12673. // delegate iterator, or by modifying context.method and context.arg,
  12674. // setting context.delegate to null, and returning the ContinueSentinel.
  12675. function maybeInvokeDelegate(delegate, context) {
  12676. var method = delegate.iterator[context.method];
  12677. if (method === undefined$1) {
  12678. // A .throw or .return when the delegate iterator has no .throw
  12679. // method always terminates the yield* loop.
  12680. context.delegate = null;
  12681. if (context.method === "throw") {
  12682. // Note: ["return"] must be used for ES3 parsing compatibility.
  12683. if (delegate.iterator["return"]) {
  12684. // If the delegate iterator has a return method, give it a
  12685. // chance to clean up.
  12686. context.method = "return";
  12687. context.arg = undefined$1;
  12688. maybeInvokeDelegate(delegate, context);
  12689. if (context.method === "throw") {
  12690. // If maybeInvokeDelegate(context) changed context.method from
  12691. // "return" to "throw", let that override the TypeError below.
  12692. return ContinueSentinel;
  12693. }
  12694. }
  12695. context.method = "throw";
  12696. context.arg = new TypeError(
  12697. "The iterator does not provide a 'throw' method");
  12698. }
  12699. return ContinueSentinel;
  12700. }
  12701. var record = tryCatch(method, delegate.iterator, context.arg);
  12702. if (record.type === "throw") {
  12703. context.method = "throw";
  12704. context.arg = record.arg;
  12705. context.delegate = null;
  12706. return ContinueSentinel;
  12707. }
  12708. var info = record.arg;
  12709. if (! info) {
  12710. context.method = "throw";
  12711. context.arg = new TypeError("iterator result is not an object");
  12712. context.delegate = null;
  12713. return ContinueSentinel;
  12714. }
  12715. if (info.done) {
  12716. // Assign the result of the finished delegate to the temporary
  12717. // variable specified by delegate.resultName (see delegateYield).
  12718. context[delegate.resultName] = info.value;
  12719. // Resume execution at the desired location (see delegateYield).
  12720. context.next = delegate.nextLoc;
  12721. // If context.method was "throw" but the delegate handled the
  12722. // exception, let the outer generator proceed normally. If
  12723. // context.method was "next", forget context.arg since it has been
  12724. // "consumed" by the delegate iterator. If context.method was
  12725. // "return", allow the original .return call to continue in the
  12726. // outer generator.
  12727. if (context.method !== "return") {
  12728. context.method = "next";
  12729. context.arg = undefined$1;
  12730. }
  12731. } else {
  12732. // Re-yield the result returned by the delegate method.
  12733. return info;
  12734. }
  12735. // The delegate iterator is finished, so forget it and continue with
  12736. // the outer generator.
  12737. context.delegate = null;
  12738. return ContinueSentinel;
  12739. }
  12740. // Define Generator.prototype.{next,throw,return} in terms of the
  12741. // unified ._invoke helper method.
  12742. defineIteratorMethods(Gp);
  12743. Gp[toStringTagSymbol] = "Generator";
  12744. // A Generator should always return itself as the iterator object when the
  12745. // @@iterator function is called on it. Some browsers' implementations of the
  12746. // iterator prototype chain incorrectly implement this, causing the Generator
  12747. // object to not be returned from this call. This ensures that doesn't happen.
  12748. // See https://github.com/facebook/regenerator/issues/274 for more details.
  12749. Gp[iteratorSymbol] = function() {
  12750. return this;
  12751. };
  12752. Gp.toString = function() {
  12753. return "[object Generator]";
  12754. };
  12755. function pushTryEntry(locs) {
  12756. var entry = { tryLoc: locs[0] };
  12757. if (1 in locs) {
  12758. entry.catchLoc = locs[1];
  12759. }
  12760. if (2 in locs) {
  12761. entry.finallyLoc = locs[2];
  12762. entry.afterLoc = locs[3];
  12763. }
  12764. this.tryEntries.push(entry);
  12765. }
  12766. function resetTryEntry(entry) {
  12767. var record = entry.completion || {};
  12768. record.type = "normal";
  12769. delete record.arg;
  12770. entry.completion = record;
  12771. }
  12772. function Context(tryLocsList) {
  12773. // The root entry object (effectively a try statement without a catch
  12774. // or a finally block) gives us a place to store values thrown from
  12775. // locations where there is no enclosing try statement.
  12776. this.tryEntries = [{ tryLoc: "root" }];
  12777. tryLocsList.forEach(pushTryEntry, this);
  12778. this.reset(true);
  12779. }
  12780. exports.keys = function(object) {
  12781. var keys = [];
  12782. for (var key in object) {
  12783. keys.push(key);
  12784. }
  12785. keys.reverse();
  12786. // Rather than returning an object with a next method, we keep
  12787. // things simple and return the next function itself.
  12788. return function next() {
  12789. while (keys.length) {
  12790. var key = keys.pop();
  12791. if (key in object) {
  12792. next.value = key;
  12793. next.done = false;
  12794. return next;
  12795. }
  12796. }
  12797. // To avoid creating an additional object, we just hang the .value
  12798. // and .done properties off the next function object itself. This
  12799. // also ensures that the minifier will not anonymize the function.
  12800. next.done = true;
  12801. return next;
  12802. };
  12803. };
  12804. function values(iterable) {
  12805. if (iterable) {
  12806. var iteratorMethod = iterable[iteratorSymbol];
  12807. if (iteratorMethod) {
  12808. return iteratorMethod.call(iterable);
  12809. }
  12810. if (typeof iterable.next === "function") {
  12811. return iterable;
  12812. }
  12813. if (!isNaN(iterable.length)) {
  12814. var i = -1, next = function next() {
  12815. while (++i < iterable.length) {
  12816. if (hasOwn.call(iterable, i)) {
  12817. next.value = iterable[i];
  12818. next.done = false;
  12819. return next;
  12820. }
  12821. }
  12822. next.value = undefined$1;
  12823. next.done = true;
  12824. return next;
  12825. };
  12826. return next.next = next;
  12827. }
  12828. }
  12829. // Return an iterator with no values.
  12830. return { next: doneResult };
  12831. }
  12832. exports.values = values;
  12833. function doneResult() {
  12834. return { value: undefined$1, done: true };
  12835. }
  12836. Context.prototype = {
  12837. constructor: Context,
  12838. reset: function(skipTempReset) {
  12839. this.prev = 0;
  12840. this.next = 0;
  12841. // Resetting context._sent for legacy support of Babel's
  12842. // function.sent implementation.
  12843. this.sent = this._sent = undefined$1;
  12844. this.done = false;
  12845. this.delegate = null;
  12846. this.method = "next";
  12847. this.arg = undefined$1;
  12848. this.tryEntries.forEach(resetTryEntry);
  12849. if (!skipTempReset) {
  12850. for (var name in this) {
  12851. // Not sure about the optimal order of these conditions:
  12852. if (name.charAt(0) === "t" &&
  12853. hasOwn.call(this, name) &&
  12854. !isNaN(+name.slice(1))) {
  12855. this[name] = undefined$1;
  12856. }
  12857. }
  12858. }
  12859. },
  12860. stop: function() {
  12861. this.done = true;
  12862. var rootEntry = this.tryEntries[0];
  12863. var rootRecord = rootEntry.completion;
  12864. if (rootRecord.type === "throw") {
  12865. throw rootRecord.arg;
  12866. }
  12867. return this.rval;
  12868. },
  12869. dispatchException: function(exception) {
  12870. if (this.done) {
  12871. throw exception;
  12872. }
  12873. var context = this;
  12874. function handle(loc, caught) {
  12875. record.type = "throw";
  12876. record.arg = exception;
  12877. context.next = loc;
  12878. if (caught) {
  12879. // If the dispatched exception was caught by a catch block,
  12880. // then let that catch block handle the exception normally.
  12881. context.method = "next";
  12882. context.arg = undefined$1;
  12883. }
  12884. return !! caught;
  12885. }
  12886. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  12887. var entry = this.tryEntries[i];
  12888. var record = entry.completion;
  12889. if (entry.tryLoc === "root") {
  12890. // Exception thrown outside of any try block that could handle
  12891. // it, so set the completion value of the entire function to
  12892. // throw the exception.
  12893. return handle("end");
  12894. }
  12895. if (entry.tryLoc <= this.prev) {
  12896. var hasCatch = hasOwn.call(entry, "catchLoc");
  12897. var hasFinally = hasOwn.call(entry, "finallyLoc");
  12898. if (hasCatch && hasFinally) {
  12899. if (this.prev < entry.catchLoc) {
  12900. return handle(entry.catchLoc, true);
  12901. } else if (this.prev < entry.finallyLoc) {
  12902. return handle(entry.finallyLoc);
  12903. }
  12904. } else if (hasCatch) {
  12905. if (this.prev < entry.catchLoc) {
  12906. return handle(entry.catchLoc, true);
  12907. }
  12908. } else if (hasFinally) {
  12909. if (this.prev < entry.finallyLoc) {
  12910. return handle(entry.finallyLoc);
  12911. }
  12912. } else {
  12913. throw new Error("try statement without catch or finally");
  12914. }
  12915. }
  12916. }
  12917. },
  12918. abrupt: function(type, arg) {
  12919. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  12920. var entry = this.tryEntries[i];
  12921. if (entry.tryLoc <= this.prev &&
  12922. hasOwn.call(entry, "finallyLoc") &&
  12923. this.prev < entry.finallyLoc) {
  12924. var finallyEntry = entry;
  12925. break;
  12926. }
  12927. }
  12928. if (finallyEntry &&
  12929. (type === "break" ||
  12930. type === "continue") &&
  12931. finallyEntry.tryLoc <= arg &&
  12932. arg <= finallyEntry.finallyLoc) {
  12933. // Ignore the finally entry if control is not jumping to a
  12934. // location outside the try/catch block.
  12935. finallyEntry = null;
  12936. }
  12937. var record = finallyEntry ? finallyEntry.completion : {};
  12938. record.type = type;
  12939. record.arg = arg;
  12940. if (finallyEntry) {
  12941. this.method = "next";
  12942. this.next = finallyEntry.finallyLoc;
  12943. return ContinueSentinel;
  12944. }
  12945. return this.complete(record);
  12946. },
  12947. complete: function(record, afterLoc) {
  12948. if (record.type === "throw") {
  12949. throw record.arg;
  12950. }
  12951. if (record.type === "break" ||
  12952. record.type === "continue") {
  12953. this.next = record.arg;
  12954. } else if (record.type === "return") {
  12955. this.rval = this.arg = record.arg;
  12956. this.method = "return";
  12957. this.next = "end";
  12958. } else if (record.type === "normal" && afterLoc) {
  12959. this.next = afterLoc;
  12960. }
  12961. return ContinueSentinel;
  12962. },
  12963. finish: function(finallyLoc) {
  12964. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  12965. var entry = this.tryEntries[i];
  12966. if (entry.finallyLoc === finallyLoc) {
  12967. this.complete(entry.completion, entry.afterLoc);
  12968. resetTryEntry(entry);
  12969. return ContinueSentinel;
  12970. }
  12971. }
  12972. },
  12973. "catch": function(tryLoc) {
  12974. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  12975. var entry = this.tryEntries[i];
  12976. if (entry.tryLoc === tryLoc) {
  12977. var record = entry.completion;
  12978. if (record.type === "throw") {
  12979. var thrown = record.arg;
  12980. resetTryEntry(entry);
  12981. }
  12982. return thrown;
  12983. }
  12984. }
  12985. // The context.catch method must only be called with a location
  12986. // argument that corresponds to a known catch block.
  12987. throw new Error("illegal catch attempt");
  12988. },
  12989. delegateYield: function(iterable, resultName, nextLoc) {
  12990. this.delegate = {
  12991. iterator: values(iterable),
  12992. resultName: resultName,
  12993. nextLoc: nextLoc
  12994. };
  12995. if (this.method === "next") {
  12996. // Deliberately forget the last sent value so that we don't
  12997. // accidentally pass it on to the delegate.
  12998. this.arg = undefined$1;
  12999. }
  13000. return ContinueSentinel;
  13001. }
  13002. };
  13003. // Regardless of whether this script is executing as a CommonJS module
  13004. // or not, return the runtime object so that we can declare the variable
  13005. // regeneratorRuntime in the outer scope, which allows this module to be
  13006. // injected easily by `bin/regenerator --include-runtime script.js`.
  13007. return exports;
  13008. }(
  13009. // If this script is executing as a CommonJS module, use module.exports
  13010. // as the regeneratorRuntime namespace. Otherwise create a new empty
  13011. // object. Either way, the resulting object will be used to initialize
  13012. // the regeneratorRuntime variable at the top of this file.
  13013. module.exports
  13014. ));
  13015. try {
  13016. regeneratorRuntime = runtime;
  13017. } catch (accidentalStrictMode) {
  13018. // This module should not be running in strict mode, so the above
  13019. // assignment should always work unless something is misconfigured. Just
  13020. // in case runtime.js accidentally runs in strict mode, we can escape
  13021. // strict mode using a global Function call. This could conceivably fail
  13022. // if a Content Security Policy forbids using Function, but in that case
  13023. // the proper solution is to fix the accidental strict mode problem. If
  13024. // you've misconfigured your bundler to force strict mode and applied a
  13025. // CSP to forbid Function, and you're not willing to fix either of those
  13026. // problems, please detail your unique predicament in a GitHub issue.
  13027. Function("r", "regeneratorRuntime = r")(runtime);
  13028. }
  13029. });
  13030. var regenerator = runtime_1;
  13031. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  13032. try {
  13033. var info = gen[key](arg);
  13034. var value = info.value;
  13035. } catch (error) {
  13036. reject(error);
  13037. return;
  13038. }
  13039. if (info.done) {
  13040. resolve(value);
  13041. } else {
  13042. Promise.resolve(value).then(_next, _throw);
  13043. }
  13044. }
  13045. function _asyncToGenerator(fn) {
  13046. return function () {
  13047. var self = this,
  13048. args = arguments;
  13049. return new Promise(function (resolve, reject) {
  13050. var gen = fn.apply(self, args);
  13051. function _next(value) {
  13052. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  13053. }
  13054. function _throw(err) {
  13055. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  13056. }
  13057. _next(undefined);
  13058. });
  13059. };
  13060. }
  13061. var asyncToGenerator = _asyncToGenerator;
  13062. function _arrayLikeToArray(arr, len) {
  13063. if (len == null || len > arr.length) len = arr.length;
  13064. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  13065. arr2[i] = arr[i];
  13066. }
  13067. return arr2;
  13068. }
  13069. var arrayLikeToArray = _arrayLikeToArray;
  13070. function _arrayWithoutHoles$1(arr) {
  13071. if (Array.isArray(arr)) return arrayLikeToArray(arr);
  13072. }
  13073. var arrayWithoutHoles = _arrayWithoutHoles$1;
  13074. function _iterableToArray$1(iter) {
  13075. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  13076. }
  13077. var iterableToArray = _iterableToArray$1;
  13078. function _unsupportedIterableToArray(o, minLen) {
  13079. if (!o) return;
  13080. if (typeof o === "string") return arrayLikeToArray(o, minLen);
  13081. var n = Object.prototype.toString.call(o).slice(8, -1);
  13082. if (n === "Object" && o.constructor) n = o.constructor.name;
  13083. if (n === "Map" || n === "Set") return Array.from(o);
  13084. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
  13085. }
  13086. var unsupportedIterableToArray = _unsupportedIterableToArray;
  13087. function _nonIterableSpread$1() {
  13088. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  13089. }
  13090. var nonIterableSpread = _nonIterableSpread$1;
  13091. function _toConsumableArray$1(arr) {
  13092. return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
  13093. }
  13094. var toConsumableArray = _toConsumableArray$1;
  13095. function _objectWithoutPropertiesLoose(source, excluded) {
  13096. if (source == null) return {};
  13097. var target = {};
  13098. var sourceKeys = Object.keys(source);
  13099. var key, i;
  13100. for (i = 0; i < sourceKeys.length; i++) {
  13101. key = sourceKeys[i];
  13102. if (excluded.indexOf(key) >= 0) continue;
  13103. target[key] = source[key];
  13104. }
  13105. return target;
  13106. }
  13107. var objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose;
  13108. function _objectWithoutProperties(source, excluded) {
  13109. if (source == null) return {};
  13110. var target = objectWithoutPropertiesLoose(source, excluded);
  13111. var key, i;
  13112. if (Object.getOwnPropertySymbols) {
  13113. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  13114. for (i = 0; i < sourceSymbolKeys.length; i++) {
  13115. key = sourceSymbolKeys[i];
  13116. if (excluded.indexOf(key) >= 0) continue;
  13117. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  13118. target[key] = source[key];
  13119. }
  13120. }
  13121. return target;
  13122. }
  13123. var objectWithoutProperties = _objectWithoutProperties;
  13124. function _assertThisInitialized(self) {
  13125. if (self === void 0) {
  13126. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  13127. }
  13128. return self;
  13129. }
  13130. var assertThisInitialized = _assertThisInitialized;
  13131. function _inheritsLoose(subClass, superClass) {
  13132. subClass.prototype = Object.create(superClass.prototype);
  13133. subClass.prototype.constructor = subClass;
  13134. subClass.__proto__ = superClass;
  13135. }
  13136. var inheritsLoose = _inheritsLoose;
  13137. /**
  13138. * Helpers.
  13139. */
  13140. var s = 1000;
  13141. var m = s * 60;
  13142. var h = m * 60;
  13143. var d = h * 24;
  13144. var w = d * 7;
  13145. var y = d * 365.25;
  13146. /**
  13147. * Parse or format the given `val`.
  13148. *
  13149. * Options:
  13150. *
  13151. * - `long` verbose formatting [false]
  13152. *
  13153. * @param {String|Number} val
  13154. * @param {Object} [options]
  13155. * @throws {Error} throw an error if val is not a non-empty string or a number
  13156. * @return {String|Number}
  13157. * @api public
  13158. */
  13159. var ms = function(val, options) {
  13160. options = options || {};
  13161. var type = typeof val;
  13162. if (type === 'string' && val.length > 0) {
  13163. return parse(val);
  13164. } else if (type === 'number' && isNaN(val) === false) {
  13165. return options.long ? fmtLong(val) : fmtShort(val);
  13166. }
  13167. throw new Error(
  13168. 'val is not a non-empty string or a valid number. val=' +
  13169. JSON.stringify(val)
  13170. );
  13171. };
  13172. /**
  13173. * Parse the given `str` and return milliseconds.
  13174. *
  13175. * @param {String} str
  13176. * @return {Number}
  13177. * @api private
  13178. */
  13179. function parse(str) {
  13180. str = String(str);
  13181. if (str.length > 100) {
  13182. return;
  13183. }
  13184. var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  13185. str
  13186. );
  13187. if (!match) {
  13188. return;
  13189. }
  13190. var n = parseFloat(match[1]);
  13191. var type = (match[2] || 'ms').toLowerCase();
  13192. switch (type) {
  13193. case 'years':
  13194. case 'year':
  13195. case 'yrs':
  13196. case 'yr':
  13197. case 'y':
  13198. return n * y;
  13199. case 'weeks':
  13200. case 'week':
  13201. case 'w':
  13202. return n * w;
  13203. case 'days':
  13204. case 'day':
  13205. case 'd':
  13206. return n * d;
  13207. case 'hours':
  13208. case 'hour':
  13209. case 'hrs':
  13210. case 'hr':
  13211. case 'h':
  13212. return n * h;
  13213. case 'minutes':
  13214. case 'minute':
  13215. case 'mins':
  13216. case 'min':
  13217. case 'm':
  13218. return n * m;
  13219. case 'seconds':
  13220. case 'second':
  13221. case 'secs':
  13222. case 'sec':
  13223. case 's':
  13224. return n * s;
  13225. case 'milliseconds':
  13226. case 'millisecond':
  13227. case 'msecs':
  13228. case 'msec':
  13229. case 'ms':
  13230. return n;
  13231. default:
  13232. return undefined;
  13233. }
  13234. }
  13235. /**
  13236. * Short format for `ms`.
  13237. *
  13238. * @param {Number} ms
  13239. * @return {String}
  13240. * @api private
  13241. */
  13242. function fmtShort(ms) {
  13243. var msAbs = Math.abs(ms);
  13244. if (msAbs >= d) {
  13245. return Math.round(ms / d) + 'd';
  13246. }
  13247. if (msAbs >= h) {
  13248. return Math.round(ms / h) + 'h';
  13249. }
  13250. if (msAbs >= m) {
  13251. return Math.round(ms / m) + 'm';
  13252. }
  13253. if (msAbs >= s) {
  13254. return Math.round(ms / s) + 's';
  13255. }
  13256. return ms + 'ms';
  13257. }
  13258. /**
  13259. * Long format for `ms`.
  13260. *
  13261. * @param {Number} ms
  13262. * @return {String}
  13263. * @api private
  13264. */
  13265. function fmtLong(ms) {
  13266. var msAbs = Math.abs(ms);
  13267. if (msAbs >= d) {
  13268. return plural(ms, msAbs, d, 'day');
  13269. }
  13270. if (msAbs >= h) {
  13271. return plural(ms, msAbs, h, 'hour');
  13272. }
  13273. if (msAbs >= m) {
  13274. return plural(ms, msAbs, m, 'minute');
  13275. }
  13276. if (msAbs >= s) {
  13277. return plural(ms, msAbs, s, 'second');
  13278. }
  13279. return ms + ' ms';
  13280. }
  13281. /**
  13282. * Pluralization helper.
  13283. */
  13284. function plural(ms, msAbs, n, name) {
  13285. var isPlural = msAbs >= n * 1.5;
  13286. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  13287. }
  13288. /**
  13289. * This is the common logic for both the Node.js and web browser
  13290. * implementations of `debug()`.
  13291. */
  13292. function setup(env) {
  13293. createDebug.debug = createDebug;
  13294. createDebug.default = createDebug;
  13295. createDebug.coerce = coerce;
  13296. createDebug.disable = disable;
  13297. createDebug.enable = enable;
  13298. createDebug.enabled = enabled;
  13299. createDebug.humanize = ms;
  13300. Object.keys(env).forEach(function (key) {
  13301. createDebug[key] = env[key];
  13302. });
  13303. /**
  13304. * Active `debug` instances.
  13305. */
  13306. createDebug.instances = [];
  13307. /**
  13308. * The currently active debug mode names, and names to skip.
  13309. */
  13310. createDebug.names = [];
  13311. createDebug.skips = [];
  13312. /**
  13313. * Map of special "%n" handling functions, for the debug "format" argument.
  13314. *
  13315. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  13316. */
  13317. createDebug.formatters = {};
  13318. /**
  13319. * Selects a color for a debug namespace
  13320. * @param {String} namespace The namespace string for the for the debug instance to be colored
  13321. * @return {Number|String} An ANSI color code for the given namespace
  13322. * @api private
  13323. */
  13324. function selectColor(namespace) {
  13325. var hash = 0;
  13326. for (var i = 0; i < namespace.length; i++) {
  13327. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  13328. hash |= 0; // Convert to 32bit integer
  13329. }
  13330. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  13331. }
  13332. createDebug.selectColor = selectColor;
  13333. /**
  13334. * Create a debugger with the given `namespace`.
  13335. *
  13336. * @param {String} namespace
  13337. * @return {Function}
  13338. * @api public
  13339. */
  13340. function createDebug(namespace) {
  13341. var prevTime;
  13342. function debug() {
  13343. // Disabled?
  13344. if (!debug.enabled) {
  13345. return;
  13346. }
  13347. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  13348. args[_key] = arguments[_key];
  13349. }
  13350. var self = debug; // Set `diff` timestamp
  13351. var curr = Number(new Date());
  13352. var ms = curr - (prevTime || curr);
  13353. self.diff = ms;
  13354. self.prev = prevTime;
  13355. self.curr = curr;
  13356. prevTime = curr;
  13357. args[0] = createDebug.coerce(args[0]);
  13358. if (typeof args[0] !== 'string') {
  13359. // Anything else let's inspect with %O
  13360. args.unshift('%O');
  13361. } // Apply any `formatters` transformations
  13362. var index = 0;
  13363. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  13364. // If we encounter an escaped % then don't increase the array index
  13365. if (match === '%%') {
  13366. return match;
  13367. }
  13368. index++;
  13369. var formatter = createDebug.formatters[format];
  13370. if (typeof formatter === 'function') {
  13371. var val = args[index];
  13372. match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  13373. args.splice(index, 1);
  13374. index--;
  13375. }
  13376. return match;
  13377. }); // Apply env-specific formatting (colors, etc.)
  13378. createDebug.formatArgs.call(self, args);
  13379. var logFn = self.log || createDebug.log;
  13380. logFn.apply(self, args);
  13381. }
  13382. debug.namespace = namespace;
  13383. debug.enabled = createDebug.enabled(namespace);
  13384. debug.useColors = createDebug.useColors();
  13385. debug.color = selectColor(namespace);
  13386. debug.destroy = destroy;
  13387. debug.extend = extend; // Debug.formatArgs = formatArgs;
  13388. // debug.rawLog = rawLog;
  13389. // env-specific initialization logic for debug instances
  13390. if (typeof createDebug.init === 'function') {
  13391. createDebug.init(debug);
  13392. }
  13393. createDebug.instances.push(debug);
  13394. return debug;
  13395. }
  13396. function destroy() {
  13397. var index = createDebug.instances.indexOf(this);
  13398. if (index !== -1) {
  13399. createDebug.instances.splice(index, 1);
  13400. return true;
  13401. }
  13402. return false;
  13403. }
  13404. function extend(namespace, delimiter) {
  13405. return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  13406. }
  13407. /**
  13408. * Enables a debug mode by namespaces. This can include modes
  13409. * separated by a colon and wildcards.
  13410. *
  13411. * @param {String} namespaces
  13412. * @api public
  13413. */
  13414. function enable(namespaces) {
  13415. createDebug.save(namespaces);
  13416. createDebug.names = [];
  13417. createDebug.skips = [];
  13418. var i;
  13419. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  13420. var len = split.length;
  13421. for (i = 0; i < len; i++) {
  13422. if (!split[i]) {
  13423. // ignore empty strings
  13424. continue;
  13425. }
  13426. namespaces = split[i].replace(/\*/g, '.*?');
  13427. if (namespaces[0] === '-') {
  13428. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  13429. } else {
  13430. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  13431. }
  13432. }
  13433. for (i = 0; i < createDebug.instances.length; i++) {
  13434. var instance = createDebug.instances[i];
  13435. instance.enabled = createDebug.enabled(instance.namespace);
  13436. }
  13437. }
  13438. /**
  13439. * Disable debug output.
  13440. *
  13441. * @api public
  13442. */
  13443. function disable() {
  13444. createDebug.enable('');
  13445. }
  13446. /**
  13447. * Returns true if the given mode name is enabled, false otherwise.
  13448. *
  13449. * @param {String} name
  13450. * @return {Boolean}
  13451. * @api public
  13452. */
  13453. function enabled(name) {
  13454. if (name[name.length - 1] === '*') {
  13455. return true;
  13456. }
  13457. var i;
  13458. var len;
  13459. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  13460. if (createDebug.skips[i].test(name)) {
  13461. return false;
  13462. }
  13463. }
  13464. for (i = 0, len = createDebug.names.length; i < len; i++) {
  13465. if (createDebug.names[i].test(name)) {
  13466. return true;
  13467. }
  13468. }
  13469. return false;
  13470. }
  13471. /**
  13472. * Coerce `val`.
  13473. *
  13474. * @param {Mixed} val
  13475. * @return {Mixed}
  13476. * @api private
  13477. */
  13478. function coerce(val) {
  13479. if (val instanceof Error) {
  13480. return val.stack || val.message;
  13481. }
  13482. return val;
  13483. }
  13484. createDebug.enable(createDebug.load());
  13485. return createDebug;
  13486. }
  13487. var common = setup;
  13488. var browser = createCommonjsModule(function (module, exports) {
  13489. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  13490. /* eslint-env browser */
  13491. /**
  13492. * This is the web browser implementation of `debug()`.
  13493. */
  13494. exports.log = log;
  13495. exports.formatArgs = formatArgs;
  13496. exports.save = save;
  13497. exports.load = load;
  13498. exports.useColors = useColors;
  13499. exports.storage = localstorage();
  13500. /**
  13501. * Colors.
  13502. */
  13503. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  13504. /**
  13505. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  13506. * and the Firebug extension (any Firefox version) are known
  13507. * to support "%c" CSS customizations.
  13508. *
  13509. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  13510. */
  13511. // eslint-disable-next-line complexity
  13512. function useColors() {
  13513. // NB: In an Electron preload script, document will be defined but not fully
  13514. // initialized. Since we know we're in Chrome, we'll just detect this case
  13515. // explicitly
  13516. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  13517. return true;
  13518. } // Internet Explorer and Edge do not support colors.
  13519. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  13520. return false;
  13521. } // Is webkit? http://stackoverflow.com/a/16459606/376773
  13522. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  13523. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  13524. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  13525. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  13526. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  13527. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  13528. }
  13529. /**
  13530. * Colorize log arguments if enabled.
  13531. *
  13532. * @api public
  13533. */
  13534. function formatArgs(args) {
  13535. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  13536. if (!this.useColors) {
  13537. return;
  13538. }
  13539. var c = 'color: ' + this.color;
  13540. args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
  13541. // arguments passed either before or after the %c, so we need to
  13542. // figure out the correct index to insert the CSS into
  13543. var index = 0;
  13544. var lastC = 0;
  13545. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  13546. if (match === '%%') {
  13547. return;
  13548. }
  13549. index++;
  13550. if (match === '%c') {
  13551. // We only are interested in the *last* %c
  13552. // (the user may have provided their own)
  13553. lastC = index;
  13554. }
  13555. });
  13556. args.splice(lastC, 0, c);
  13557. }
  13558. /**
  13559. * Invokes `console.log()` when available.
  13560. * No-op when `console.log` is not a "function".
  13561. *
  13562. * @api public
  13563. */
  13564. function log() {
  13565. var _console;
  13566. // This hackery is required for IE8/9, where
  13567. // the `console.log` function doesn't have 'apply'
  13568. return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  13569. }
  13570. /**
  13571. * Save `namespaces`.
  13572. *
  13573. * @param {String} namespaces
  13574. * @api private
  13575. */
  13576. function save(namespaces) {
  13577. try {
  13578. if (namespaces) {
  13579. exports.storage.setItem('debug', namespaces);
  13580. } else {
  13581. exports.storage.removeItem('debug');
  13582. }
  13583. } catch (error) {// Swallow
  13584. // XXX (@Qix-) should we be logging these?
  13585. }
  13586. }
  13587. /**
  13588. * Load `namespaces`.
  13589. *
  13590. * @return {String} returns the previously persisted debug modes
  13591. * @api private
  13592. */
  13593. function load() {
  13594. var r;
  13595. try {
  13596. r = exports.storage.getItem('debug');
  13597. } catch (error) {} // Swallow
  13598. // XXX (@Qix-) should we be logging these?
  13599. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  13600. if (!r && typeof process !== 'undefined' && 'env' in process) {
  13601. r = process.env.DEBUG;
  13602. }
  13603. return r;
  13604. }
  13605. /**
  13606. * Localstorage attempts to return the localstorage.
  13607. *
  13608. * This is necessary because safari throws
  13609. * when a user disables cookies/localstorage
  13610. * and you attempt to access it.
  13611. *
  13612. * @return {LocalStorage}
  13613. * @api private
  13614. */
  13615. function localstorage() {
  13616. try {
  13617. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  13618. // The Browser also has localStorage in the global context.
  13619. return localStorage;
  13620. } catch (error) {// Swallow
  13621. // XXX (@Qix-) should we be logging these?
  13622. }
  13623. }
  13624. module.exports = common(exports);
  13625. var formatters = module.exports.formatters;
  13626. /**
  13627. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  13628. */
  13629. formatters.j = function (v) {
  13630. try {
  13631. return JSON.stringify(v);
  13632. } catch (error) {
  13633. return '[UnexpectedJSONParseError]: ' + error.message;
  13634. }
  13635. };
  13636. });
  13637. var browser_1 = browser.log;
  13638. var browser_2 = browser.formatArgs;
  13639. var browser_3 = browser.save;
  13640. var browser_4 = browser.load;
  13641. var browser_5 = browser.useColors;
  13642. var browser_6 = browser.storage;
  13643. var browser_7 = browser.colors;
  13644. /**
  13645. * Copies the values of `source` to `array`.
  13646. *
  13647. * @private
  13648. * @param {Array} source The array to copy values from.
  13649. * @param {Array} [array=[]] The array to copy values to.
  13650. * @returns {Array} Returns `array`.
  13651. */
  13652. function copyArray(source, array) {
  13653. var index = -1,
  13654. length = source.length;
  13655. array || (array = Array(length));
  13656. while (++index < length) {
  13657. array[index] = source[index];
  13658. }
  13659. return array;
  13660. }
  13661. var _copyArray = copyArray;
  13662. /* Built-in method references for those with the same name as other `lodash` methods. */
  13663. var nativeFloor = Math.floor,
  13664. nativeRandom = Math.random;
  13665. /**
  13666. * The base implementation of `_.random` without support for returning
  13667. * floating-point numbers.
  13668. *
  13669. * @private
  13670. * @param {number} lower The lower bound.
  13671. * @param {number} upper The upper bound.
  13672. * @returns {number} Returns the random number.
  13673. */
  13674. function baseRandom(lower, upper) {
  13675. return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
  13676. }
  13677. var _baseRandom = baseRandom;
  13678. /**
  13679. * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
  13680. *
  13681. * @private
  13682. * @param {Array} array The array to shuffle.
  13683. * @param {number} [size=array.length] The size of `array`.
  13684. * @returns {Array} Returns `array`.
  13685. */
  13686. function shuffleSelf(array, size) {
  13687. var index = -1,
  13688. length = array.length,
  13689. lastIndex = length - 1;
  13690. size = size === undefined ? length : size;
  13691. while (++index < size) {
  13692. var rand = _baseRandom(index, lastIndex),
  13693. value = array[rand];
  13694. array[rand] = array[index];
  13695. array[index] = value;
  13696. }
  13697. array.length = size;
  13698. return array;
  13699. }
  13700. var _shuffleSelf = shuffleSelf;
  13701. /**
  13702. * A specialized version of `_.shuffle` for arrays.
  13703. *
  13704. * @private
  13705. * @param {Array} array The array to shuffle.
  13706. * @returns {Array} Returns the new shuffled array.
  13707. */
  13708. function arrayShuffle(array) {
  13709. return _shuffleSelf(_copyArray(array));
  13710. }
  13711. var _arrayShuffle = arrayShuffle;
  13712. /**
  13713. * A specialized version of `_.map` for arrays without support for iteratee
  13714. * shorthands.
  13715. *
  13716. * @private
  13717. * @param {Array} [array] The array to iterate over.
  13718. * @param {Function} iteratee The function invoked per iteration.
  13719. * @returns {Array} Returns the new mapped array.
  13720. */
  13721. function arrayMap(array, iteratee) {
  13722. var index = -1,
  13723. length = array == null ? 0 : array.length,
  13724. result = Array(length);
  13725. while (++index < length) {
  13726. result[index] = iteratee(array[index], index, array);
  13727. }
  13728. return result;
  13729. }
  13730. var _arrayMap = arrayMap;
  13731. /**
  13732. * The base implementation of `_.values` and `_.valuesIn` which creates an
  13733. * array of `object` property values corresponding to the property names
  13734. * of `props`.
  13735. *
  13736. * @private
  13737. * @param {Object} object The object to query.
  13738. * @param {Array} props The property names to get values for.
  13739. * @returns {Object} Returns the array of property values.
  13740. */
  13741. function baseValues(object, props) {
  13742. return _arrayMap(props, function(key) {
  13743. return object[key];
  13744. });
  13745. }
  13746. var _baseValues = baseValues;
  13747. /**
  13748. * The base implementation of `_.times` without support for iteratee shorthands
  13749. * or max array length checks.
  13750. *
  13751. * @private
  13752. * @param {number} n The number of times to invoke `iteratee`.
  13753. * @param {Function} iteratee The function invoked per iteration.
  13754. * @returns {Array} Returns the array of results.
  13755. */
  13756. function baseTimes(n, iteratee) {
  13757. var index = -1,
  13758. result = Array(n);
  13759. while (++index < n) {
  13760. result[index] = iteratee(index);
  13761. }
  13762. return result;
  13763. }
  13764. var _baseTimes = baseTimes;
  13765. /** Detect free variable `global` from Node.js. */
  13766. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  13767. var _freeGlobal = freeGlobal;
  13768. /** Detect free variable `self`. */
  13769. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  13770. /** Used as a reference to the global object. */
  13771. var root = _freeGlobal || freeSelf || Function('return this')();
  13772. var _root = root;
  13773. /** Built-in value references. */
  13774. var Symbol$1 = _root.Symbol;
  13775. var _Symbol = Symbol$1;
  13776. /** Used for built-in method references. */
  13777. var objectProto = Object.prototype;
  13778. /** Used to check objects for own properties. */
  13779. var hasOwnProperty = objectProto.hasOwnProperty;
  13780. /**
  13781. * Used to resolve the
  13782. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  13783. * of values.
  13784. */
  13785. var nativeObjectToString = objectProto.toString;
  13786. /** Built-in value references. */
  13787. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  13788. /**
  13789. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  13790. *
  13791. * @private
  13792. * @param {*} value The value to query.
  13793. * @returns {string} Returns the raw `toStringTag`.
  13794. */
  13795. function getRawTag(value) {
  13796. var isOwn = hasOwnProperty.call(value, symToStringTag),
  13797. tag = value[symToStringTag];
  13798. try {
  13799. value[symToStringTag] = undefined;
  13800. var unmasked = true;
  13801. } catch (e) {}
  13802. var result = nativeObjectToString.call(value);
  13803. if (unmasked) {
  13804. if (isOwn) {
  13805. value[symToStringTag] = tag;
  13806. } else {
  13807. delete value[symToStringTag];
  13808. }
  13809. }
  13810. return result;
  13811. }
  13812. var _getRawTag = getRawTag;
  13813. /** Used for built-in method references. */
  13814. var objectProto$1 = Object.prototype;
  13815. /**
  13816. * Used to resolve the
  13817. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  13818. * of values.
  13819. */
  13820. var nativeObjectToString$1 = objectProto$1.toString;
  13821. /**
  13822. * Converts `value` to a string using `Object.prototype.toString`.
  13823. *
  13824. * @private
  13825. * @param {*} value The value to convert.
  13826. * @returns {string} Returns the converted string.
  13827. */
  13828. function objectToString(value) {
  13829. return nativeObjectToString$1.call(value);
  13830. }
  13831. var _objectToString = objectToString;
  13832. /** `Object#toString` result references. */
  13833. var nullTag = '[object Null]',
  13834. undefinedTag = '[object Undefined]';
  13835. /** Built-in value references. */
  13836. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  13837. /**
  13838. * The base implementation of `getTag` without fallbacks for buggy environments.
  13839. *
  13840. * @private
  13841. * @param {*} value The value to query.
  13842. * @returns {string} Returns the `toStringTag`.
  13843. */
  13844. function baseGetTag(value) {
  13845. if (value == null) {
  13846. return value === undefined ? undefinedTag : nullTag;
  13847. }
  13848. return (symToStringTag$1 && symToStringTag$1 in Object(value))
  13849. ? _getRawTag(value)
  13850. : _objectToString(value);
  13851. }
  13852. var _baseGetTag = baseGetTag;
  13853. /**
  13854. * Checks if `value` is object-like. A value is object-like if it's not `null`
  13855. * and has a `typeof` result of "object".
  13856. *
  13857. * @static
  13858. * @memberOf _
  13859. * @since 4.0.0
  13860. * @category Lang
  13861. * @param {*} value The value to check.
  13862. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  13863. * @example
  13864. *
  13865. * _.isObjectLike({});
  13866. * // => true
  13867. *
  13868. * _.isObjectLike([1, 2, 3]);
  13869. * // => true
  13870. *
  13871. * _.isObjectLike(_.noop);
  13872. * // => false
  13873. *
  13874. * _.isObjectLike(null);
  13875. * // => false
  13876. */
  13877. function isObjectLike(value) {
  13878. return value != null && typeof value == 'object';
  13879. }
  13880. var isObjectLike_1 = isObjectLike;
  13881. /** `Object#toString` result references. */
  13882. var argsTag = '[object Arguments]';
  13883. /**
  13884. * The base implementation of `_.isArguments`.
  13885. *
  13886. * @private
  13887. * @param {*} value The value to check.
  13888. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  13889. */
  13890. function baseIsArguments(value) {
  13891. return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
  13892. }
  13893. var _baseIsArguments = baseIsArguments;
  13894. /** Used for built-in method references. */
  13895. var objectProto$2 = Object.prototype;
  13896. /** Used to check objects for own properties. */
  13897. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  13898. /** Built-in value references. */
  13899. var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
  13900. /**
  13901. * Checks if `value` is likely an `arguments` object.
  13902. *
  13903. * @static
  13904. * @memberOf _
  13905. * @since 0.1.0
  13906. * @category Lang
  13907. * @param {*} value The value to check.
  13908. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  13909. * else `false`.
  13910. * @example
  13911. *
  13912. * _.isArguments(function() { return arguments; }());
  13913. * // => true
  13914. *
  13915. * _.isArguments([1, 2, 3]);
  13916. * // => false
  13917. */
  13918. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  13919. return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') &&
  13920. !propertyIsEnumerable.call(value, 'callee');
  13921. };
  13922. var isArguments_1 = isArguments;
  13923. /**
  13924. * Checks if `value` is classified as an `Array` object.
  13925. *
  13926. * @static
  13927. * @memberOf _
  13928. * @since 0.1.0
  13929. * @category Lang
  13930. * @param {*} value The value to check.
  13931. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  13932. * @example
  13933. *
  13934. * _.isArray([1, 2, 3]);
  13935. * // => true
  13936. *
  13937. * _.isArray(document.body.children);
  13938. * // => false
  13939. *
  13940. * _.isArray('abc');
  13941. * // => false
  13942. *
  13943. * _.isArray(_.noop);
  13944. * // => false
  13945. */
  13946. var isArray = Array.isArray;
  13947. var isArray_1 = isArray;
  13948. /**
  13949. * This method returns `false`.
  13950. *
  13951. * @static
  13952. * @memberOf _
  13953. * @since 4.13.0
  13954. * @category Util
  13955. * @returns {boolean} Returns `false`.
  13956. * @example
  13957. *
  13958. * _.times(2, _.stubFalse);
  13959. * // => [false, false]
  13960. */
  13961. function stubFalse() {
  13962. return false;
  13963. }
  13964. var stubFalse_1 = stubFalse;
  13965. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  13966. /** Detect free variable `exports`. */
  13967. var freeExports = exports && !exports.nodeType && exports;
  13968. /** Detect free variable `module`. */
  13969. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  13970. /** Detect the popular CommonJS extension `module.exports`. */
  13971. var moduleExports = freeModule && freeModule.exports === freeExports;
  13972. /** Built-in value references. */
  13973. var Buffer = moduleExports ? _root.Buffer : undefined;
  13974. /* Built-in method references for those with the same name as other `lodash` methods. */
  13975. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  13976. /**
  13977. * Checks if `value` is a buffer.
  13978. *
  13979. * @static
  13980. * @memberOf _
  13981. * @since 4.3.0
  13982. * @category Lang
  13983. * @param {*} value The value to check.
  13984. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  13985. * @example
  13986. *
  13987. * _.isBuffer(new Buffer(2));
  13988. * // => true
  13989. *
  13990. * _.isBuffer(new Uint8Array(2));
  13991. * // => false
  13992. */
  13993. var isBuffer = nativeIsBuffer || stubFalse_1;
  13994. module.exports = isBuffer;
  13995. });
  13996. /** Used as references for various `Number` constants. */
  13997. var MAX_SAFE_INTEGER = 9007199254740991;
  13998. /** Used to detect unsigned integer values. */
  13999. var reIsUint = /^(?:0|[1-9]\d*)$/;
  14000. /**
  14001. * Checks if `value` is a valid array-like index.
  14002. *
  14003. * @private
  14004. * @param {*} value The value to check.
  14005. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  14006. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  14007. */
  14008. function isIndex(value, length) {
  14009. var type = typeof value;
  14010. length = length == null ? MAX_SAFE_INTEGER : length;
  14011. return !!length &&
  14012. (type == 'number' ||
  14013. (type != 'symbol' && reIsUint.test(value))) &&
  14014. (value > -1 && value % 1 == 0 && value < length);
  14015. }
  14016. var _isIndex = isIndex;
  14017. /** Used as references for various `Number` constants. */
  14018. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  14019. /**
  14020. * Checks if `value` is a valid array-like length.
  14021. *
  14022. * **Note:** This method is loosely based on
  14023. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  14024. *
  14025. * @static
  14026. * @memberOf _
  14027. * @since 4.0.0
  14028. * @category Lang
  14029. * @param {*} value The value to check.
  14030. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  14031. * @example
  14032. *
  14033. * _.isLength(3);
  14034. * // => true
  14035. *
  14036. * _.isLength(Number.MIN_VALUE);
  14037. * // => false
  14038. *
  14039. * _.isLength(Infinity);
  14040. * // => false
  14041. *
  14042. * _.isLength('3');
  14043. * // => false
  14044. */
  14045. function isLength(value) {
  14046. return typeof value == 'number' &&
  14047. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
  14048. }
  14049. var isLength_1 = isLength;
  14050. /** `Object#toString` result references. */
  14051. var argsTag$1 = '[object Arguments]',
  14052. arrayTag = '[object Array]',
  14053. boolTag = '[object Boolean]',
  14054. dateTag = '[object Date]',
  14055. errorTag = '[object Error]',
  14056. funcTag = '[object Function]',
  14057. mapTag = '[object Map]',
  14058. numberTag = '[object Number]',
  14059. objectTag = '[object Object]',
  14060. regexpTag = '[object RegExp]',
  14061. setTag = '[object Set]',
  14062. stringTag = '[object String]',
  14063. weakMapTag = '[object WeakMap]';
  14064. var arrayBufferTag = '[object ArrayBuffer]',
  14065. dataViewTag = '[object DataView]',
  14066. float32Tag = '[object Float32Array]',
  14067. float64Tag = '[object Float64Array]',
  14068. int8Tag = '[object Int8Array]',
  14069. int16Tag = '[object Int16Array]',
  14070. int32Tag = '[object Int32Array]',
  14071. uint8Tag = '[object Uint8Array]',
  14072. uint8ClampedTag = '[object Uint8ClampedArray]',
  14073. uint16Tag = '[object Uint16Array]',
  14074. uint32Tag = '[object Uint32Array]';
  14075. /** Used to identify `toStringTag` values of typed arrays. */
  14076. var typedArrayTags = {};
  14077. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  14078. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  14079. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  14080. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  14081. typedArrayTags[uint32Tag] = true;
  14082. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
  14083. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  14084. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  14085. typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  14086. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  14087. typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  14088. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  14089. typedArrayTags[weakMapTag] = false;
  14090. /**
  14091. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  14092. *
  14093. * @private
  14094. * @param {*} value The value to check.
  14095. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  14096. */
  14097. function baseIsTypedArray(value) {
  14098. return isObjectLike_1(value) &&
  14099. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  14100. }
  14101. var _baseIsTypedArray = baseIsTypedArray;
  14102. /**
  14103. * The base implementation of `_.unary` without support for storing metadata.
  14104. *
  14105. * @private
  14106. * @param {Function} func The function to cap arguments for.
  14107. * @returns {Function} Returns the new capped function.
  14108. */
  14109. function baseUnary(func) {
  14110. return function(value) {
  14111. return func(value);
  14112. };
  14113. }
  14114. var _baseUnary = baseUnary;
  14115. var _nodeUtil = createCommonjsModule(function (module, exports) {
  14116. /** Detect free variable `exports`. */
  14117. var freeExports = exports && !exports.nodeType && exports;
  14118. /** Detect free variable `module`. */
  14119. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  14120. /** Detect the popular CommonJS extension `module.exports`. */
  14121. var moduleExports = freeModule && freeModule.exports === freeExports;
  14122. /** Detect free variable `process` from Node.js. */
  14123. var freeProcess = moduleExports && _freeGlobal.process;
  14124. /** Used to access faster Node.js helpers. */
  14125. var nodeUtil = (function() {
  14126. try {
  14127. // Use `util.types` for Node.js 10+.
  14128. var types = freeModule && freeModule.require && freeModule.require('util').types;
  14129. if (types) {
  14130. return types;
  14131. }
  14132. // Legacy `process.binding('util')` for Node.js < 10.
  14133. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  14134. } catch (e) {}
  14135. }());
  14136. module.exports = nodeUtil;
  14137. });
  14138. /* Node.js helper references. */
  14139. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  14140. /**
  14141. * Checks if `value` is classified as a typed array.
  14142. *
  14143. * @static
  14144. * @memberOf _
  14145. * @since 3.0.0
  14146. * @category Lang
  14147. * @param {*} value The value to check.
  14148. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  14149. * @example
  14150. *
  14151. * _.isTypedArray(new Uint8Array);
  14152. * // => true
  14153. *
  14154. * _.isTypedArray([]);
  14155. * // => false
  14156. */
  14157. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  14158. var isTypedArray_1 = isTypedArray;
  14159. /** Used for built-in method references. */
  14160. var objectProto$3 = Object.prototype;
  14161. /** Used to check objects for own properties. */
  14162. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  14163. /**
  14164. * Creates an array of the enumerable property names of the array-like `value`.
  14165. *
  14166. * @private
  14167. * @param {*} value The value to query.
  14168. * @param {boolean} inherited Specify returning inherited property names.
  14169. * @returns {Array} Returns the array of property names.
  14170. */
  14171. function arrayLikeKeys(value, inherited) {
  14172. var isArr = isArray_1(value),
  14173. isArg = !isArr && isArguments_1(value),
  14174. isBuff = !isArr && !isArg && isBuffer_1(value),
  14175. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  14176. skipIndexes = isArr || isArg || isBuff || isType,
  14177. result = skipIndexes ? _baseTimes(value.length, String) : [],
  14178. length = result.length;
  14179. for (var key in value) {
  14180. if ((inherited || hasOwnProperty$2.call(value, key)) &&
  14181. !(skipIndexes && (
  14182. // Safari 9 has enumerable `arguments.length` in strict mode.
  14183. key == 'length' ||
  14184. // Node.js 0.10 has enumerable non-index properties on buffers.
  14185. (isBuff && (key == 'offset' || key == 'parent')) ||
  14186. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  14187. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  14188. // Skip index properties.
  14189. _isIndex(key, length)
  14190. ))) {
  14191. result.push(key);
  14192. }
  14193. }
  14194. return result;
  14195. }
  14196. var _arrayLikeKeys = arrayLikeKeys;
  14197. /** Used for built-in method references. */
  14198. var objectProto$4 = Object.prototype;
  14199. /**
  14200. * Checks if `value` is likely a prototype object.
  14201. *
  14202. * @private
  14203. * @param {*} value The value to check.
  14204. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  14205. */
  14206. function isPrototype(value) {
  14207. var Ctor = value && value.constructor,
  14208. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4;
  14209. return value === proto;
  14210. }
  14211. var _isPrototype = isPrototype;
  14212. /**
  14213. * Creates a unary function that invokes `func` with its argument transformed.
  14214. *
  14215. * @private
  14216. * @param {Function} func The function to wrap.
  14217. * @param {Function} transform The argument transform.
  14218. * @returns {Function} Returns the new function.
  14219. */
  14220. function overArg(func, transform) {
  14221. return function(arg) {
  14222. return func(transform(arg));
  14223. };
  14224. }
  14225. var _overArg = overArg;
  14226. /* Built-in method references for those with the same name as other `lodash` methods. */
  14227. var nativeKeys = _overArg(Object.keys, Object);
  14228. var _nativeKeys = nativeKeys;
  14229. /** Used for built-in method references. */
  14230. var objectProto$5 = Object.prototype;
  14231. /** Used to check objects for own properties. */
  14232. var hasOwnProperty$3 = objectProto$5.hasOwnProperty;
  14233. /**
  14234. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  14235. *
  14236. * @private
  14237. * @param {Object} object The object to query.
  14238. * @returns {Array} Returns the array of property names.
  14239. */
  14240. function baseKeys(object) {
  14241. if (!_isPrototype(object)) {
  14242. return _nativeKeys(object);
  14243. }
  14244. var result = [];
  14245. for (var key in Object(object)) {
  14246. if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
  14247. result.push(key);
  14248. }
  14249. }
  14250. return result;
  14251. }
  14252. var _baseKeys = baseKeys;
  14253. /**
  14254. * Checks if `value` is the
  14255. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  14256. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  14257. *
  14258. * @static
  14259. * @memberOf _
  14260. * @since 0.1.0
  14261. * @category Lang
  14262. * @param {*} value The value to check.
  14263. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  14264. * @example
  14265. *
  14266. * _.isObject({});
  14267. * // => true
  14268. *
  14269. * _.isObject([1, 2, 3]);
  14270. * // => true
  14271. *
  14272. * _.isObject(_.noop);
  14273. * // => true
  14274. *
  14275. * _.isObject(null);
  14276. * // => false
  14277. */
  14278. function isObject$1(value) {
  14279. var type = typeof value;
  14280. return value != null && (type == 'object' || type == 'function');
  14281. }
  14282. var isObject_1$1 = isObject$1;
  14283. /** `Object#toString` result references. */
  14284. var asyncTag = '[object AsyncFunction]',
  14285. funcTag$1 = '[object Function]',
  14286. genTag = '[object GeneratorFunction]',
  14287. proxyTag = '[object Proxy]';
  14288. /**
  14289. * Checks if `value` is classified as a `Function` object.
  14290. *
  14291. * @static
  14292. * @memberOf _
  14293. * @since 0.1.0
  14294. * @category Lang
  14295. * @param {*} value The value to check.
  14296. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  14297. * @example
  14298. *
  14299. * _.isFunction(_);
  14300. * // => true
  14301. *
  14302. * _.isFunction(/abc/);
  14303. * // => false
  14304. */
  14305. function isFunction(value) {
  14306. if (!isObject_1$1(value)) {
  14307. return false;
  14308. }
  14309. // The use of `Object#toString` avoids issues with the `typeof` operator
  14310. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  14311. var tag = _baseGetTag(value);
  14312. return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
  14313. }
  14314. var isFunction_1 = isFunction;
  14315. /**
  14316. * Checks if `value` is array-like. A value is considered array-like if it's
  14317. * not a function and has a `value.length` that's an integer greater than or
  14318. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  14319. *
  14320. * @static
  14321. * @memberOf _
  14322. * @since 4.0.0
  14323. * @category Lang
  14324. * @param {*} value The value to check.
  14325. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  14326. * @example
  14327. *
  14328. * _.isArrayLike([1, 2, 3]);
  14329. * // => true
  14330. *
  14331. * _.isArrayLike(document.body.children);
  14332. * // => true
  14333. *
  14334. * _.isArrayLike('abc');
  14335. * // => true
  14336. *
  14337. * _.isArrayLike(_.noop);
  14338. * // => false
  14339. */
  14340. function isArrayLike(value) {
  14341. return value != null && isLength_1(value.length) && !isFunction_1(value);
  14342. }
  14343. var isArrayLike_1 = isArrayLike;
  14344. /**
  14345. * Creates an array of the own enumerable property names of `object`.
  14346. *
  14347. * **Note:** Non-object values are coerced to objects. See the
  14348. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  14349. * for more details.
  14350. *
  14351. * @static
  14352. * @since 0.1.0
  14353. * @memberOf _
  14354. * @category Object
  14355. * @param {Object} object The object to query.
  14356. * @returns {Array} Returns the array of property names.
  14357. * @example
  14358. *
  14359. * function Foo() {
  14360. * this.a = 1;
  14361. * this.b = 2;
  14362. * }
  14363. *
  14364. * Foo.prototype.c = 3;
  14365. *
  14366. * _.keys(new Foo);
  14367. * // => ['a', 'b'] (iteration order is not guaranteed)
  14368. *
  14369. * _.keys('hi');
  14370. * // => ['0', '1']
  14371. */
  14372. function keys(object) {
  14373. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  14374. }
  14375. var keys_1 = keys;
  14376. /**
  14377. * Creates an array of the own enumerable string keyed property values of `object`.
  14378. *
  14379. * **Note:** Non-object values are coerced to objects.
  14380. *
  14381. * @static
  14382. * @since 0.1.0
  14383. * @memberOf _
  14384. * @category Object
  14385. * @param {Object} object The object to query.
  14386. * @returns {Array} Returns the array of property values.
  14387. * @example
  14388. *
  14389. * function Foo() {
  14390. * this.a = 1;
  14391. * this.b = 2;
  14392. * }
  14393. *
  14394. * Foo.prototype.c = 3;
  14395. *
  14396. * _.values(new Foo);
  14397. * // => [1, 2] (iteration order is not guaranteed)
  14398. *
  14399. * _.values('hi');
  14400. * // => ['h', 'i']
  14401. */
  14402. function values(object) {
  14403. return object == null ? [] : _baseValues(object, keys_1(object));
  14404. }
  14405. var values_1 = values;
  14406. /**
  14407. * The base implementation of `_.shuffle`.
  14408. *
  14409. * @private
  14410. * @param {Array|Object} collection The collection to shuffle.
  14411. * @returns {Array} Returns the new shuffled array.
  14412. */
  14413. function baseShuffle(collection) {
  14414. return _shuffleSelf(values_1(collection));
  14415. }
  14416. var _baseShuffle = baseShuffle;
  14417. /**
  14418. * Creates an array of shuffled values, using a version of the
  14419. * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
  14420. *
  14421. * @static
  14422. * @memberOf _
  14423. * @since 0.1.0
  14424. * @category Collection
  14425. * @param {Array|Object} collection The collection to shuffle.
  14426. * @returns {Array} Returns the new shuffled array.
  14427. * @example
  14428. *
  14429. * _.shuffle([1, 2, 3, 4]);
  14430. * // => [4, 1, 3, 2]
  14431. */
  14432. function shuffle(collection) {
  14433. var func = isArray_1(collection) ? _arrayShuffle : _baseShuffle;
  14434. return func(collection);
  14435. }
  14436. var shuffle_1 = shuffle;
  14437. function _arrayWithHoles(arr) {
  14438. if (Array.isArray(arr)) return arr;
  14439. }
  14440. var arrayWithHoles = _arrayWithHoles;
  14441. function _nonIterableRest() {
  14442. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  14443. }
  14444. var nonIterableRest = _nonIterableRest;
  14445. function _toArray(arr) {
  14446. return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
  14447. }
  14448. var toArray = _toArray;
  14449. function _defineProperties(target, props) {
  14450. for (var i = 0; i < props.length; i++) {
  14451. var descriptor = props[i];
  14452. descriptor.enumerable = descriptor.enumerable || false;
  14453. descriptor.configurable = true;
  14454. if ("value" in descriptor) descriptor.writable = true;
  14455. Object.defineProperty(target, descriptor.key, descriptor);
  14456. }
  14457. }
  14458. function _createClass(Constructor, protoProps, staticProps) {
  14459. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  14460. if (staticProps) _defineProperties(Constructor, staticProps);
  14461. return Constructor;
  14462. }
  14463. var createClass = _createClass;
  14464. function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  14465. var desc = {};
  14466. Object.keys(descriptor).forEach(function (key) {
  14467. desc[key] = descriptor[key];
  14468. });
  14469. desc.enumerable = !!desc.enumerable;
  14470. desc.configurable = !!desc.configurable;
  14471. if ('value' in desc || desc.initializer) {
  14472. desc.writable = true;
  14473. }
  14474. desc = decorators.slice().reverse().reduce(function (desc, decorator) {
  14475. return decorator(target, property, desc) || desc;
  14476. }, desc);
  14477. if (context && desc.initializer !== void 0) {
  14478. desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
  14479. desc.initializer = undefined;
  14480. }
  14481. if (desc.initializer === void 0) {
  14482. Object.defineProperty(target, property, desc);
  14483. desc = null;
  14484. }
  14485. return desc;
  14486. }
  14487. var applyDecoratedDescriptor = _applyDecoratedDescriptor;
  14488. var stateMachine = createCommonjsModule(function (module, exports) {
  14489. /*
  14490. Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
  14491. Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
  14492. Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
  14493. */
  14494. (function () {
  14495. var StateMachine = {
  14496. //---------------------------------------------------------------------------
  14497. VERSION: "2.4.0",
  14498. //---------------------------------------------------------------------------
  14499. Result: {
  14500. SUCCEEDED: 1, // the event transitioned successfully from one state to another
  14501. NOTRANSITION: 2, // the event was successfull but no state transition was necessary
  14502. CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
  14503. PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
  14504. },
  14505. Error: {
  14506. INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
  14507. PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
  14508. INVALID_CALLBACK: 300 // caller provided callback function threw an exception
  14509. },
  14510. WILDCARD: '*',
  14511. ASYNC: 'async',
  14512. //---------------------------------------------------------------------------
  14513. create: function(cfg, target) {
  14514. var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
  14515. var terminal = cfg.terminal || cfg['final'];
  14516. var fsm = target || cfg.target || {};
  14517. var events = cfg.events || [];
  14518. var callbacks = cfg.callbacks || {};
  14519. var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
  14520. var transitions = {}; // track events allowed from a state { state: [ event ] }
  14521. var add = function(e) {
  14522. var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
  14523. map[e.name] = map[e.name] || {};
  14524. for (var n = 0 ; n < from.length ; n++) {
  14525. transitions[from[n]] = transitions[from[n]] || [];
  14526. transitions[from[n]].push(e.name);
  14527. map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
  14528. }
  14529. if (e.to)
  14530. transitions[e.to] = transitions[e.to] || [];
  14531. };
  14532. if (initial) {
  14533. initial.event = initial.event || 'startup';
  14534. add({ name: initial.event, from: 'none', to: initial.state });
  14535. }
  14536. for(var n = 0 ; n < events.length ; n++)
  14537. add(events[n]);
  14538. for(var name in map) {
  14539. if (map.hasOwnProperty(name))
  14540. fsm[name] = StateMachine.buildEvent(name, map[name]);
  14541. }
  14542. for(var name in callbacks) {
  14543. if (callbacks.hasOwnProperty(name))
  14544. fsm[name] = callbacks[name];
  14545. }
  14546. fsm.current = 'none';
  14547. fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
  14548. fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); };
  14549. fsm.cannot = function(event) { return !this.can(event); };
  14550. fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
  14551. fsm.isFinished = function() { return this.is(terminal); };
  14552. fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
  14553. fsm.states = function() { return Object.keys(transitions).sort() };
  14554. if (initial && !initial.defer)
  14555. fsm[initial.event]();
  14556. return fsm;
  14557. },
  14558. //===========================================================================
  14559. doCallback: function(fsm, func, name, from, to, args) {
  14560. if (func) {
  14561. try {
  14562. return func.apply(fsm, [name, from, to].concat(args));
  14563. }
  14564. catch(e) {
  14565. return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
  14566. }
  14567. }
  14568. },
  14569. beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
  14570. afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
  14571. leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
  14572. enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
  14573. changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
  14574. beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
  14575. afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
  14576. leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
  14577. enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
  14578. beforeEvent: function(fsm, name, from, to, args) {
  14579. if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
  14580. (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
  14581. return false;
  14582. },
  14583. afterEvent: function(fsm, name, from, to, args) {
  14584. StateMachine.afterThisEvent(fsm, name, from, to, args);
  14585. StateMachine.afterAnyEvent( fsm, name, from, to, args);
  14586. },
  14587. leaveState: function(fsm, name, from, to, args) {
  14588. var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
  14589. general = StateMachine.leaveAnyState( fsm, name, from, to, args);
  14590. if ((false === specific) || (false === general))
  14591. return false;
  14592. else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
  14593. return StateMachine.ASYNC;
  14594. },
  14595. enterState: function(fsm, name, from, to, args) {
  14596. StateMachine.enterThisState(fsm, name, from, to, args);
  14597. StateMachine.enterAnyState( fsm, name, from, to, args);
  14598. },
  14599. //===========================================================================
  14600. buildEvent: function(name, map) {
  14601. return function() {
  14602. var from = this.current;
  14603. var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
  14604. var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
  14605. if (this.transition)
  14606. return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
  14607. if (this.cannot(name))
  14608. return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
  14609. if (false === StateMachine.beforeEvent(this, name, from, to, args))
  14610. return StateMachine.Result.CANCELLED;
  14611. if (from === to) {
  14612. StateMachine.afterEvent(this, name, from, to, args);
  14613. return StateMachine.Result.NOTRANSITION;
  14614. }
  14615. // prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
  14616. var fsm = this;
  14617. this.transition = function() {
  14618. fsm.transition = null; // this method should only ever be called once
  14619. fsm.current = to;
  14620. StateMachine.enterState( fsm, name, from, to, args);
  14621. StateMachine.changeState(fsm, name, from, to, args);
  14622. StateMachine.afterEvent( fsm, name, from, to, args);
  14623. return StateMachine.Result.SUCCEEDED;
  14624. };
  14625. this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
  14626. fsm.transition = null;
  14627. StateMachine.afterEvent(fsm, name, from, to, args);
  14628. };
  14629. var leave = StateMachine.leaveState(this, name, from, to, args);
  14630. if (false === leave) {
  14631. this.transition = null;
  14632. return StateMachine.Result.CANCELLED;
  14633. }
  14634. else if (StateMachine.ASYNC === leave) {
  14635. return StateMachine.Result.PENDING;
  14636. }
  14637. else {
  14638. if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
  14639. return this.transition();
  14640. }
  14641. };
  14642. }
  14643. }; // StateMachine
  14644. //===========================================================================
  14645. //======
  14646. // NODE
  14647. //======
  14648. {
  14649. if ( module.exports) {
  14650. exports = module.exports = StateMachine;
  14651. }
  14652. exports.StateMachine = StateMachine;
  14653. }
  14654. }());
  14655. });
  14656. var stateMachine_1 = stateMachine.StateMachine;
  14657. var adapters = {};
  14658. var getAdapter = function getAdapter(name) {
  14659. var adapter = adapters[name];
  14660. if (adapter === undefined) {
  14661. throw new Error("".concat(name, " adapter is not configured"));
  14662. }
  14663. return adapter;
  14664. };
  14665. /**
  14666. * 指定 Adapters
  14667. * @function
  14668. * @memberof module:leancloud-realtime
  14669. * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
  14670. */
  14671. var setAdapters = function setAdapters(newAdapters) {
  14672. Object.assign(adapters, newAdapters);
  14673. };
  14674. /** Built-in value references. */
  14675. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  14676. var _getPrototype = getPrototype;
  14677. /** `Object#toString` result references. */
  14678. var objectTag$1 = '[object Object]';
  14679. /** Used for built-in method references. */
  14680. var funcProto = Function.prototype,
  14681. objectProto$6 = Object.prototype;
  14682. /** Used to resolve the decompiled source of functions. */
  14683. var funcToString = funcProto.toString;
  14684. /** Used to check objects for own properties. */
  14685. var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
  14686. /** Used to infer the `Object` constructor. */
  14687. var objectCtorString = funcToString.call(Object);
  14688. /**
  14689. * Checks if `value` is a plain object, that is, an object created by the
  14690. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  14691. *
  14692. * @static
  14693. * @memberOf _
  14694. * @since 0.8.0
  14695. * @category Lang
  14696. * @param {*} value The value to check.
  14697. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  14698. * @example
  14699. *
  14700. * function Foo() {
  14701. * this.a = 1;
  14702. * }
  14703. *
  14704. * _.isPlainObject(new Foo);
  14705. * // => false
  14706. *
  14707. * _.isPlainObject([1, 2, 3]);
  14708. * // => false
  14709. *
  14710. * _.isPlainObject({ 'x': 0, 'y': 0 });
  14711. * // => true
  14712. *
  14713. * _.isPlainObject(Object.create(null));
  14714. * // => true
  14715. */
  14716. function isPlainObject(value) {
  14717. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  14718. return false;
  14719. }
  14720. var proto = _getPrototype(value);
  14721. if (proto === null) {
  14722. return true;
  14723. }
  14724. var Ctor = hasOwnProperty$4.call(proto, 'constructor') && proto.constructor;
  14725. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  14726. funcToString.call(Ctor) == objectCtorString;
  14727. }
  14728. var isPlainObject_1 = isPlainObject;
  14729. /* eslint-disable */
  14730. var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
  14731. var EXPIRED = Symbol('expired');
  14732. var debug = browser('LC:Expirable');
  14733. var Expirable = /*#__PURE__*/function () {
  14734. function Expirable(value, ttl) {
  14735. this.originalValue = value;
  14736. if (typeof ttl === 'number') {
  14737. this.expiredAt = Date.now() + ttl;
  14738. }
  14739. }
  14740. createClass(Expirable, [{
  14741. key: "value",
  14742. get: function get() {
  14743. var expired = this.expiredAt && this.expiredAt <= Date.now();
  14744. if (expired) debug("expired: ".concat(this.originalValue));
  14745. return expired ? EXPIRED : this.originalValue;
  14746. }
  14747. }]);
  14748. return Expirable;
  14749. }();
  14750. Expirable.EXPIRED = EXPIRED;
  14751. var debug$1 = browser('LC:Cache');
  14752. var Cache = /*#__PURE__*/function () {
  14753. function Cache() {
  14754. var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
  14755. this.name = name;
  14756. this._map = {};
  14757. }
  14758. var _proto = Cache.prototype;
  14759. _proto.get = function get(key) {
  14760. var cache = this._map[key];
  14761. if (cache) {
  14762. var value = cache.value;
  14763. if (value !== Expirable.EXPIRED) {
  14764. debug$1('[%s] hit: %s', this.name, key);
  14765. return value;
  14766. }
  14767. delete this._map[key];
  14768. }
  14769. debug$1("[".concat(this.name, "] missed: ").concat(key));
  14770. return null;
  14771. };
  14772. _proto.set = function set(key, value, ttl) {
  14773. debug$1('[%s] set: %s %d', this.name, key, ttl);
  14774. this._map[key] = new Expirable(value, ttl);
  14775. };
  14776. return Cache;
  14777. }();
  14778. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  14779. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  14780. /**
  14781. * 调试日志控制器
  14782. * @const
  14783. * @memberof module:leancloud-realtime
  14784. * @example
  14785. * debug.enable(); // 启用调试日志
  14786. * debug.disable(); // 关闭调试日志
  14787. */
  14788. var debug$2 = {
  14789. enable: function enable() {
  14790. var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
  14791. return browser.enable(namespaces);
  14792. },
  14793. disable: browser.disable
  14794. };
  14795. var tryAll = function tryAll(promiseConstructors) {
  14796. var promise = new Promise(promiseConstructors[0]);
  14797. if (promiseConstructors.length === 1) {
  14798. return promise;
  14799. }
  14800. return promise["catch"](function () {
  14801. return tryAll(promiseConstructors.slice(1));
  14802. });
  14803. }; // eslint-disable-next-line no-sequences
  14804. var tap = function tap(interceptor) {
  14805. return function (value) {
  14806. return interceptor(value), value;
  14807. };
  14808. };
  14809. var finalize = function finalize(callback) {
  14810. return [// eslint-disable-next-line no-sequences
  14811. function (value) {
  14812. return callback(), value;
  14813. }, function (error) {
  14814. callback();
  14815. throw error;
  14816. }];
  14817. };
  14818. /**
  14819. * 将对象转换为 Date,支持 string、number、ProtoBuf Long 以及 LeanCloud 的 Date 类型,
  14820. * 其他情况下(包括对象为 falsy)返回原值。
  14821. * @private
  14822. */
  14823. var decodeDate = function decodeDate(date) {
  14824. if (!date) return date;
  14825. if (typeof date === 'string' || typeof date === 'number') {
  14826. return new Date(date);
  14827. }
  14828. if (date.__type === 'Date' && date.iso) {
  14829. return new Date(date.iso);
  14830. } // Long
  14831. if (typeof date.toNumber === 'function') {
  14832. return new Date(date.toNumber());
  14833. }
  14834. return date;
  14835. };
  14836. /**
  14837. * 获取 Date 的毫秒数,如果不是一个 Date 返回 undefined。
  14838. * @private
  14839. */
  14840. var getTime = function getTime(date) {
  14841. return date && date.getTime ? date.getTime() : undefined;
  14842. };
  14843. /**
  14844. * 解码对象中的 LeanCloud 数据结构。
  14845. * 目前仅会处理 Date 类型。
  14846. * @private
  14847. */
  14848. var decode = function decode(value) {
  14849. if (!value) return value;
  14850. if (value.__type === 'Date' && value.iso) {
  14851. return new Date(value.iso);
  14852. }
  14853. if (Array.isArray(value)) {
  14854. return value.map(decode);
  14855. }
  14856. if (isPlainObject_1(value)) {
  14857. return Object.keys(value).reduce(function (result, key) {
  14858. return _objectSpread(_objectSpread({}, result), {}, defineProperty({}, key, decode(value[key])));
  14859. }, {});
  14860. }
  14861. return value;
  14862. };
  14863. /**
  14864. * 将对象中的特殊类型编码为 LeanCloud 数据结构。
  14865. * 目前仅会处理 Date 类型。
  14866. * @private
  14867. */
  14868. var encode = function encode(value) {
  14869. if (value instanceof Date) return {
  14870. __type: 'Date',
  14871. iso: value.toJSON()
  14872. };
  14873. if (Array.isArray(value)) {
  14874. return value.map(encode);
  14875. }
  14876. if (isPlainObject_1(value)) {
  14877. return Object.keys(value).reduce(function (result, key) {
  14878. return _objectSpread(_objectSpread({}, result), {}, defineProperty({}, key, encode(value[key])));
  14879. }, {});
  14880. }
  14881. return value;
  14882. };
  14883. var keyRemap = function keyRemap(keymap, obj) {
  14884. return Object.keys(obj).reduce(function (newObj, key) {
  14885. var newKey = keymap[key] || key;
  14886. return Object.assign(newObj, defineProperty({}, newKey, obj[key]));
  14887. }, {});
  14888. };
  14889. var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
  14890. /* eslint-disable no-proto */
  14891. var getStaticProperty = function getStaticProperty(klass, property) {
  14892. return klass[property] || (klass.__proto__ ? getStaticProperty(klass.__proto__, property) : undefined);
  14893. };
  14894. /* eslint-enable no-proto */
  14895. var union = function union(a, b) {
  14896. return Array.from(new Set([].concat(toConsumableArray(a), toConsumableArray(b))));
  14897. };
  14898. var difference = function difference(a, b) {
  14899. return Array.from(function (bSet) {
  14900. return new Set(a.filter(function (x) {
  14901. return !bSet.has(x);
  14902. }));
  14903. }(new Set(b)));
  14904. };
  14905. var map = new WeakMap(); // protected property helper
  14906. var internal = function internal(object) {
  14907. if (!map.has(object)) {
  14908. map.set(object, {});
  14909. }
  14910. return map.get(object);
  14911. };
  14912. var compact = function compact(obj, filter) {
  14913. if (!isPlainObject_1(obj)) return obj;
  14914. var object = _objectSpread({}, obj);
  14915. Object.keys(object).forEach(function (prop) {
  14916. var value = object[prop];
  14917. if (value === filter) {
  14918. delete object[prop];
  14919. } else {
  14920. object[prop] = compact(value, filter);
  14921. }
  14922. });
  14923. return object;
  14924. }; // debug utility
  14925. var removeNull = function removeNull(obj) {
  14926. return compact(obj, null);
  14927. };
  14928. var trim = function trim(message) {
  14929. return removeNull(JSON.parse(JSON.stringify(message)));
  14930. };
  14931. var ensureArray = function ensureArray(target) {
  14932. if (Array.isArray(target)) {
  14933. return target;
  14934. }
  14935. if (target === undefined || target === null) {
  14936. return [];
  14937. }
  14938. return [target];
  14939. };
  14940. var setValue = function setValue(target, key, value) {
  14941. // '.' is not allowed in Class keys, escaping is not in concern now.
  14942. var segs = key.split('.');
  14943. var lastSeg = segs.pop();
  14944. var currentTarget = target;
  14945. segs.forEach(function (seg) {
  14946. if (currentTarget[seg] === undefined) currentTarget[seg] = {};
  14947. currentTarget = currentTarget[seg];
  14948. });
  14949. currentTarget[lastSeg] = value;
  14950. return target;
  14951. };
  14952. var isWeapp = // eslint-disable-next-line no-undef
  14953. (typeof wx === "undefined" ? "undefined" : _typeof_1(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
  14954. var throttle = function throttle(wait) {
  14955. return function (target, property, descriptor) {
  14956. var callback = descriptor.value; // very naive, internal use only
  14957. if (callback.length) {
  14958. throw new Error('throttled function should not accept any arguments');
  14959. }
  14960. return _objectSpread(_objectSpread({}, descriptor), {}, {
  14961. value: function value() {
  14962. var _this = this;
  14963. var _internal = internal(this),
  14964. throttleMeta = _internal.throttleMeta;
  14965. if (!throttleMeta) {
  14966. throttleMeta = {};
  14967. internal(this).throttleMeta = throttleMeta;
  14968. }
  14969. var _throttleMeta = throttleMeta,
  14970. propertyMeta = _throttleMeta[property];
  14971. if (!propertyMeta) {
  14972. propertyMeta = {};
  14973. throttleMeta[property] = propertyMeta;
  14974. }
  14975. var _propertyMeta = propertyMeta,
  14976. _propertyMeta$previou = _propertyMeta.previouseTimestamp,
  14977. previouseTimestamp = _propertyMeta$previou === void 0 ? 0 : _propertyMeta$previou,
  14978. timeout = _propertyMeta.timeout;
  14979. var now = Date.now();
  14980. var remainingTime = wait - (now - previouseTimestamp);
  14981. if (remainingTime <= 0) {
  14982. throttleMeta[property].previouseTimestamp = now;
  14983. callback.apply(this);
  14984. } else if (!timeout) {
  14985. propertyMeta.timeout = setTimeout(function () {
  14986. propertyMeta.previouseTimestamp = Date.now();
  14987. delete propertyMeta.timeout;
  14988. callback.apply(_this);
  14989. }, remainingTime);
  14990. }
  14991. }
  14992. });
  14993. };
  14994. };
  14995. var isCNApp = function isCNApp(appId) {
  14996. return appId.slice(-9) !== '-MdYXbMMI';
  14997. };
  14998. var equalBuffer = function equalBuffer(buffer1, buffer2) {
  14999. if (!buffer1 || !buffer2) return false;
  15000. if (buffer1.byteLength !== buffer2.byteLength) return false;
  15001. var a = new Uint8Array(buffer1);
  15002. var b = new Uint8Array(buffer2);
  15003. return !a.some(function (value, index) {
  15004. return value !== b[index];
  15005. });
  15006. };
  15007. var _class;
  15008. function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  15009. function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  15010. var debug$3 = browser('LC:WebSocketPlus');
  15011. var OPEN = 'open';
  15012. var DISCONNECT = 'disconnect';
  15013. var RECONNECT = 'reconnect';
  15014. var RETRY = 'retry';
  15015. var SCHEDULE = 'schedule';
  15016. var OFFLINE = 'offline';
  15017. var ONLINE = 'online';
  15018. var ERROR = 'error';
  15019. var MESSAGE = 'message';
  15020. var HEARTBEAT_TIME = 180000;
  15021. var TIMEOUT_TIME = 380000;
  15022. var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
  15023. return Math.min(1000 * Math.pow(2, attempt), 300000);
  15024. };
  15025. var requireConnected = function requireConnected(target, name, descriptor) {
  15026. return _objectSpread$1(_objectSpread$1({}, descriptor), {}, {
  15027. value: function requireConnectedWrapper() {
  15028. var _descriptor$value;
  15029. this.checkConnectionAvailability(name);
  15030. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  15031. args[_key] = arguments[_key];
  15032. }
  15033. return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
  15034. }
  15035. });
  15036. };
  15037. var WebSocketPlus = (_class = /*#__PURE__*/function (_EventEmitter) {
  15038. inheritsLoose(WebSocketPlus, _EventEmitter);
  15039. createClass(WebSocketPlus, [{
  15040. key: "urls",
  15041. get: function get() {
  15042. return this._urls;
  15043. },
  15044. set: function set(urls) {
  15045. this._urls = ensureArray(urls);
  15046. }
  15047. }]);
  15048. function WebSocketPlus(getUrls, protocol) {
  15049. var _this;
  15050. _this = _EventEmitter.call(this) || this;
  15051. _this.init();
  15052. _this._protocol = protocol;
  15053. Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
  15054. _this._urls = urls;
  15055. return _this._open();
  15056. }).then(function () {
  15057. _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(assertThisInitialized(_this));
  15058. if (global$1.addEventListener) {
  15059. _this.__pause = function () {
  15060. if (_this.can('pause')) _this.pause();
  15061. };
  15062. _this.__resume = function () {
  15063. if (_this.can('resume')) _this.resume();
  15064. };
  15065. global$1.addEventListener('offline', _this.__pause);
  15066. global$1.addEventListener('online', _this.__resume);
  15067. }
  15068. _this.open();
  15069. })["catch"](_this["throw"].bind(assertThisInitialized(_this)));
  15070. return _this;
  15071. }
  15072. var _proto = WebSocketPlus.prototype;
  15073. _proto._open = function _open() {
  15074. var _this2 = this;
  15075. return this._createWs(this._urls, this._protocol).then(function (ws) {
  15076. var _this2$_urls = toArray(_this2._urls),
  15077. first = _this2$_urls[0],
  15078. reset = _this2$_urls.slice(1);
  15079. _this2._urls = [].concat(toConsumableArray(reset), [first]);
  15080. return ws;
  15081. });
  15082. };
  15083. _proto._createWs = function _createWs(urls, protocol) {
  15084. var _this3 = this;
  15085. return tryAll(urls.map(function (url) {
  15086. return function (resolve, reject) {
  15087. debug$3("connect [".concat(url, "] ").concat(protocol));
  15088. var WebSocket = getAdapter('WebSocket');
  15089. var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
  15090. ws.binaryType = _this3.binaryType || 'arraybuffer';
  15091. ws.onopen = function () {
  15092. return resolve(ws);
  15093. };
  15094. ws.onclose = function (error) {
  15095. if (error instanceof Error) {
  15096. return reject(error);
  15097. } // in browser, error event is useless
  15098. return reject(new Error("Failed to connect [".concat(url, "]")));
  15099. };
  15100. ws.onerror = ws.onclose;
  15101. };
  15102. })).then(function (ws) {
  15103. _this3._ws = ws;
  15104. _this3._ws.onclose = _this3._handleClose.bind(_this3);
  15105. _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
  15106. return ws;
  15107. });
  15108. };
  15109. _proto._destroyWs = function _destroyWs() {
  15110. var ws = this._ws;
  15111. if (!ws) return;
  15112. ws.onopen = null;
  15113. ws.onclose = null;
  15114. ws.onerror = null;
  15115. ws.onmessage = null;
  15116. this._ws = null;
  15117. ws.close();
  15118. } // eslint-disable-next-line class-methods-use-this
  15119. ;
  15120. _proto.onbeforeevent = function onbeforeevent(event, from, to) {
  15121. for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
  15122. payload[_key2 - 3] = arguments[_key2];
  15123. }
  15124. debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
  15125. };
  15126. _proto.onopen = function onopen() {
  15127. this.emit(OPEN);
  15128. };
  15129. _proto.onconnected = function onconnected() {
  15130. this._startConnectionKeeper();
  15131. };
  15132. _proto.onleaveconnected = function onleaveconnected(event, from, to) {
  15133. this._stopConnectionKeeper();
  15134. this._destroyWs();
  15135. if (to === 'offline' || to === 'disconnected') {
  15136. this.emit(DISCONNECT);
  15137. }
  15138. };
  15139. _proto.onpause = function onpause() {
  15140. this.emit(OFFLINE);
  15141. };
  15142. _proto.onbeforeresume = function onbeforeresume() {
  15143. this.emit(ONLINE);
  15144. };
  15145. _proto.onreconnect = function onreconnect() {
  15146. this.emit(RECONNECT);
  15147. };
  15148. _proto.ondisconnected = function ondisconnected(event, from, to) {
  15149. var _this4 = this;
  15150. var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  15151. var delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
  15152. debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
  15153. this.emit(SCHEDULE, attempt, delay);
  15154. if (this.__scheduledRetry) {
  15155. clearTimeout(this.__scheduledRetry);
  15156. }
  15157. this.__scheduledRetry = setTimeout(function () {
  15158. if (_this4.is('disconnected')) {
  15159. _this4.retry(attempt);
  15160. }
  15161. }, delay);
  15162. };
  15163. _proto.onretry = function onretry(event, from, to) {
  15164. var _this5 = this;
  15165. var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  15166. this.emit(RETRY, attempt);
  15167. this._open().then(function () {
  15168. return _this5.can('reconnect') && _this5.reconnect();
  15169. }, function () {
  15170. return _this5.can('fail') && _this5.fail(attempt + 1);
  15171. });
  15172. };
  15173. _proto.onerror = function onerror(event, from, to, error) {
  15174. this.emit(ERROR, error);
  15175. };
  15176. _proto.onclose = function onclose() {
  15177. if (global$1.removeEventListener) {
  15178. if (this.__pause) global$1.removeEventListener('offline', this.__pause);
  15179. if (this.__resume) global$1.removeEventListener('online', this.__resume);
  15180. }
  15181. };
  15182. _proto.checkConnectionAvailability = function checkConnectionAvailability() {
  15183. var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
  15184. if (!this.is('connected')) {
  15185. var currentState = this.current;
  15186. console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
  15187. if (this.is('disconnected') || this.is('reconnecting')) {
  15188. console.warn('disconnect and reconnect event should be handled to avoid such calls.');
  15189. }
  15190. throw new Error('Connection unavailable');
  15191. }
  15192. } // jsdoc-ignore-start
  15193. ;
  15194. _proto. // jsdoc-ignore-end
  15195. _ping = function _ping() {
  15196. debug$3('ping');
  15197. try {
  15198. this.ping();
  15199. } catch (error) {
  15200. console.warn("websocket ping error: ".concat(error.message));
  15201. }
  15202. };
  15203. _proto.ping = function ping() {
  15204. if (this._ws.ping) {
  15205. this._ws.ping();
  15206. } else {
  15207. console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
  15208. }
  15209. };
  15210. _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
  15211. var _this6 = this;
  15212. debug$3('_postponeTimeoutTimer');
  15213. this._clearTimeoutTimers();
  15214. this._timeoutTimer = setTimeout(function () {
  15215. debug$3('timeout');
  15216. _this6.disconnect();
  15217. }, TIMEOUT_TIME);
  15218. };
  15219. _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
  15220. if (this._timeoutTimer) {
  15221. clearTimeout(this._timeoutTimer);
  15222. }
  15223. };
  15224. _proto._startConnectionKeeper = function _startConnectionKeeper() {
  15225. debug$3('start connection keeper');
  15226. this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
  15227. var addListener = this._ws.addListener || this._ws.addEventListener;
  15228. if (!addListener) {
  15229. debug$3('connection keeper disabled due to the lack of #addEventListener.');
  15230. return;
  15231. }
  15232. addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
  15233. addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
  15234. this._postponeTimeoutTimer();
  15235. };
  15236. _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
  15237. debug$3('stop connection keeper'); // websockets/ws#489
  15238. var removeListener = this._ws.removeListener || this._ws.removeEventListener;
  15239. if (removeListener) {
  15240. removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
  15241. removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
  15242. this._clearTimeoutTimers();
  15243. }
  15244. if (this._heartbeatTimer) {
  15245. clearInterval(this._heartbeatTimer);
  15246. }
  15247. };
  15248. _proto._handleClose = function _handleClose(event) {
  15249. debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
  15250. if (this.isFinished()) return;
  15251. this.handleClose(event);
  15252. };
  15253. _proto.handleClose = function handleClose() {
  15254. // reconnect
  15255. this.disconnect();
  15256. } // jsdoc-ignore-start
  15257. ;
  15258. _proto. // jsdoc-ignore-end
  15259. send = function send(data) {
  15260. debug$3('send', data);
  15261. this._ws.send(data);
  15262. };
  15263. _proto._handleMessage = function _handleMessage(event) {
  15264. debug$3('message', event.data);
  15265. this.handleMessage(event.data);
  15266. };
  15267. _proto.handleMessage = function handleMessage(message) {
  15268. this.emit(MESSAGE, message);
  15269. };
  15270. return WebSocketPlus;
  15271. }(eventemitter3), (applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "_ping"), _class.prototype), applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "send"), _class.prototype)), _class);
  15272. stateMachine.create({
  15273. target: WebSocketPlus.prototype,
  15274. initial: {
  15275. state: 'initialized',
  15276. event: 'init',
  15277. defer: true
  15278. },
  15279. terminal: 'closed',
  15280. events: [{
  15281. name: 'open',
  15282. from: 'initialized',
  15283. to: 'connected'
  15284. }, {
  15285. name: 'disconnect',
  15286. from: 'connected',
  15287. to: 'disconnected'
  15288. }, {
  15289. name: 'retry',
  15290. from: 'disconnected',
  15291. to: 'reconnecting'
  15292. }, {
  15293. name: 'fail',
  15294. from: 'reconnecting',
  15295. to: 'disconnected'
  15296. }, {
  15297. name: 'reconnect',
  15298. from: 'reconnecting',
  15299. to: 'connected'
  15300. }, {
  15301. name: 'pause',
  15302. from: ['connected', 'disconnected', 'reconnecting'],
  15303. to: 'offline'
  15304. }, {}, {
  15305. name: 'resume',
  15306. from: 'offline',
  15307. to: 'disconnected'
  15308. }, {
  15309. name: 'close',
  15310. from: ['connected', 'disconnected', 'reconnecting', 'offline'],
  15311. to: 'closed'
  15312. }, {
  15313. name: 'throw',
  15314. from: '*',
  15315. to: 'error'
  15316. }]
  15317. });
  15318. var error = Object.freeze({
  15319. 1000: {
  15320. name: 'CLOSE_NORMAL'
  15321. },
  15322. 1006: {
  15323. name: 'CLOSE_ABNORMAL'
  15324. },
  15325. 4100: {
  15326. name: 'APP_NOT_AVAILABLE',
  15327. message: 'App not exists or realtime message service is disabled.'
  15328. },
  15329. 4102: {
  15330. name: 'SIGNATURE_FAILED',
  15331. message: 'Login signature mismatch.'
  15332. },
  15333. 4103: {
  15334. name: 'INVALID_LOGIN',
  15335. message: 'Malformed clientId.'
  15336. },
  15337. 4105: {
  15338. name: 'SESSION_REQUIRED',
  15339. message: 'Message sent before session opened.'
  15340. },
  15341. 4107: {
  15342. name: 'READ_TIMEOUT'
  15343. },
  15344. 4108: {
  15345. name: 'LOGIN_TIMEOUT'
  15346. },
  15347. 4109: {
  15348. name: 'FRAME_TOO_LONG'
  15349. },
  15350. 4110: {
  15351. name: 'INVALID_ORIGIN',
  15352. message: 'Access denied by domain whitelist.'
  15353. },
  15354. 4111: {
  15355. name: 'SESSION_CONFLICT'
  15356. },
  15357. 4112: {
  15358. name: 'SESSION_TOKEN_EXPIRED'
  15359. },
  15360. 4113: {
  15361. name: 'APP_QUOTA_EXCEEDED',
  15362. message: 'The daily active users limit exceeded.'
  15363. },
  15364. 4116: {
  15365. name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
  15366. message: 'Command sent too fast.'
  15367. },
  15368. 4200: {
  15369. name: 'INTERNAL_ERROR',
  15370. message: 'Internal error, please contact LeanCloud for support.'
  15371. },
  15372. 4301: {
  15373. name: 'CONVERSATION_API_FAILED',
  15374. message: 'Upstream Conversatoin API failed, see error.detail for details.'
  15375. },
  15376. 4302: {
  15377. name: 'CONVERSATION_SIGNATURE_FAILED',
  15378. message: 'Conversation action signature mismatch.'
  15379. },
  15380. 4303: {
  15381. name: 'CONVERSATION_NOT_FOUND'
  15382. },
  15383. 4304: {
  15384. name: 'CONVERSATION_FULL'
  15385. },
  15386. 4305: {
  15387. name: 'CONVERSATION_REJECTED_BY_APP',
  15388. message: 'Conversation action rejected by hook.'
  15389. },
  15390. 4306: {
  15391. name: 'CONVERSATION_UPDATE_FAILED'
  15392. },
  15393. 4307: {
  15394. name: 'CONVERSATION_READ_ONLY'
  15395. },
  15396. 4308: {
  15397. name: 'CONVERSATION_NOT_ALLOWED'
  15398. },
  15399. 4309: {
  15400. name: 'CONVERSATION_UPDATE_REJECTED',
  15401. message: 'Conversation update rejected because the client is not a member.'
  15402. },
  15403. 4310: {
  15404. name: 'CONVERSATION_QUERY_FAILED',
  15405. message: 'Conversation query failed because it is too expansive.'
  15406. },
  15407. 4311: {
  15408. name: 'CONVERSATION_LOG_FAILED'
  15409. },
  15410. 4312: {
  15411. name: 'CONVERSATION_LOG_REJECTED',
  15412. message: 'Message query rejected because the client is not a member of the conversation.'
  15413. },
  15414. 4313: {
  15415. name: 'SYSTEM_CONVERSATION_REQUIRED'
  15416. },
  15417. 4314: {
  15418. name: 'NORMAL_CONVERSATION_REQUIRED'
  15419. },
  15420. 4315: {
  15421. name: 'CONVERSATION_BLACKLISTED',
  15422. message: 'Blacklisted in the conversation.'
  15423. },
  15424. 4316: {
  15425. name: 'TRANSIENT_CONVERSATION_REQUIRED'
  15426. },
  15427. 4317: {
  15428. name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
  15429. },
  15430. 4318: {
  15431. name: 'CONVERSATION_API_QUOTA_EXCEEDED',
  15432. message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
  15433. },
  15434. 4323: {
  15435. name: 'TEMPORARY_CONVERSATION_EXPIRED',
  15436. message: 'Temporary conversation expired or does not exist.'
  15437. },
  15438. 4401: {
  15439. name: 'INVALID_MESSAGING_TARGET',
  15440. message: 'Conversation does not exist or client is not a member.'
  15441. },
  15442. 4402: {
  15443. name: 'MESSAGE_REJECTED_BY_APP',
  15444. message: 'Message rejected by hook.'
  15445. },
  15446. 4403: {
  15447. name: 'MESSAGE_OWNERSHIP_REQUIRED'
  15448. },
  15449. 4404: {
  15450. name: 'MESSAGE_NOT_FOUND'
  15451. },
  15452. 4405: {
  15453. name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
  15454. message: 'Message update rejected by hook.'
  15455. },
  15456. 4406: {
  15457. name: 'MESSAGE_EDIT_DISABLED'
  15458. },
  15459. 4407: {
  15460. name: 'MESSAGE_RECALL_DISABLED'
  15461. },
  15462. 5130: {
  15463. name: 'OWNER_PROMOTION_NOT_ALLOWED',
  15464. message: "Updating a member's role to owner is not allowed."
  15465. }
  15466. });
  15467. var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
  15468. return Object.assign(result, defineProperty({}, error[code].name, Number(code)));
  15469. }, {}));
  15470. var createError = function createError(_ref) {
  15471. var code = _ref.code,
  15472. reason = _ref.reason,
  15473. appCode = _ref.appCode,
  15474. detail = _ref.detail,
  15475. errorMessage = _ref.error;
  15476. var message = reason || detail || errorMessage;
  15477. var name = reason;
  15478. if (!message && error[code]) {
  15479. name = error[code].name;
  15480. message = error[code].message || name;
  15481. }
  15482. if (!message) {
  15483. message = "Unknow Error: ".concat(code);
  15484. }
  15485. var err = new Error(message);
  15486. return Object.assign(err, {
  15487. code: code,
  15488. appCode: appCode,
  15489. detail: detail,
  15490. name: name
  15491. });
  15492. };
  15493. var debug$4 = browser('LC:Connection');
  15494. var COMMAND_TIMEOUT = 20000;
  15495. var EXPIRE = Symbol('expire');
  15496. var isIdempotentCommand = function isIdempotentCommand(command) {
  15497. return !(command.cmd === CommandType.direct || command.cmd === CommandType.session && command.op === OpType.open || command.cmd === CommandType.conv && (command.op === OpType.start || command.op === OpType.update || command.op === OpType.members));
  15498. };
  15499. var Connection = /*#__PURE__*/function (_WebSocketPlus) {
  15500. inheritsLoose(Connection, _WebSocketPlus);
  15501. function Connection(getUrl, _ref) {
  15502. var _this;
  15503. var format = _ref.format,
  15504. version = _ref.version;
  15505. debug$4('initializing Connection');
  15506. var protocolString = "lc.".concat(format, ".").concat(version);
  15507. _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
  15508. _this._protocolFormat = format;
  15509. _this._commands = {};
  15510. _this._serialId = 0;
  15511. return _this;
  15512. }
  15513. var _proto = Connection.prototype;
  15514. _proto.send = /*#__PURE__*/function () {
  15515. var _send = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
  15516. var _this2 = this;
  15517. var waitingForRespond,
  15518. buffer,
  15519. serialId,
  15520. duplicatedCommand,
  15521. message,
  15522. promise,
  15523. _args = arguments;
  15524. return regenerator.wrap(function _callee$(_context) {
  15525. while (1) {
  15526. switch (_context.prev = _context.next) {
  15527. case 0:
  15528. waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
  15529. if (!waitingForRespond) {
  15530. _context.next = 11;
  15531. break;
  15532. }
  15533. if (!isIdempotentCommand(command)) {
  15534. _context.next = 8;
  15535. break;
  15536. }
  15537. buffer = command.toArrayBuffer();
  15538. duplicatedCommand = values_1(this._commands).find(function (_ref2) {
  15539. var targetBuffer = _ref2.buffer,
  15540. targetCommand = _ref2.command;
  15541. return targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer);
  15542. });
  15543. if (!duplicatedCommand) {
  15544. _context.next = 8;
  15545. break;
  15546. }
  15547. console.warn("Duplicated command [cmd:".concat(command.cmd, " op:").concat(command.op, "] is throttled."));
  15548. return _context.abrupt("return", duplicatedCommand.promise);
  15549. case 8:
  15550. this._serialId += 1;
  15551. serialId = this._serialId;
  15552. command.i = serialId; // eslint-disable-line no-param-reassign
  15553. case 11:
  15554. if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
  15555. if (this._protocolFormat === 'proto2base64') {
  15556. message = command.toBase64();
  15557. } else if (command.toArrayBuffer) {
  15558. message = command.toArrayBuffer();
  15559. }
  15560. if (message) {
  15561. _context.next = 15;
  15562. break;
  15563. }
  15564. throw new TypeError("".concat(command, " is not a GenericCommand"));
  15565. case 15:
  15566. _WebSocketPlus.prototype.send.call(this, message);
  15567. if (waitingForRespond) {
  15568. _context.next = 18;
  15569. break;
  15570. }
  15571. return _context.abrupt("return", undefined);
  15572. case 18:
  15573. promise = new Promise(function (resolve, reject) {
  15574. _this2._commands[serialId] = {
  15575. command: command,
  15576. buffer: buffer,
  15577. resolve: resolve,
  15578. reject: reject,
  15579. timeout: setTimeout(function () {
  15580. if (_this2._commands[serialId]) {
  15581. if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
  15582. reject(createError({
  15583. error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
  15584. name: 'COMMAND_TIMEOUT'
  15585. }));
  15586. delete _this2._commands[serialId];
  15587. }
  15588. }, COMMAND_TIMEOUT)
  15589. };
  15590. });
  15591. this._commands[serialId].promise = promise;
  15592. return _context.abrupt("return", promise);
  15593. case 21:
  15594. case "end":
  15595. return _context.stop();
  15596. }
  15597. }
  15598. }, _callee, this);
  15599. }));
  15600. function send(_x) {
  15601. return _send.apply(this, arguments);
  15602. }
  15603. return send;
  15604. }();
  15605. _proto.handleMessage = function handleMessage(msg) {
  15606. var message;
  15607. try {
  15608. message = GenericCommand.decode(msg);
  15609. if (debug$4.enabled) debug$4('↓ %O received', trim(message));
  15610. } catch (e) {
  15611. console.warn('Decode message failed:', e.message, msg);
  15612. return;
  15613. }
  15614. var serialId = message.i;
  15615. if (serialId) {
  15616. if (this._commands[serialId]) {
  15617. clearTimeout(this._commands[serialId].timeout);
  15618. if (message.cmd === CommandType.error) {
  15619. this._commands[serialId].reject(createError(message.errorMessage));
  15620. } else {
  15621. this._commands[serialId].resolve(message);
  15622. }
  15623. delete this._commands[serialId];
  15624. } else {
  15625. console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
  15626. }
  15627. } else {
  15628. switch (message.cmd) {
  15629. case CommandType.error:
  15630. {
  15631. this.emit(ERROR, createError(message.errorMessage));
  15632. return;
  15633. }
  15634. case CommandType.goaway:
  15635. {
  15636. this.emit(EXPIRE);
  15637. return;
  15638. }
  15639. default:
  15640. {
  15641. this.emit(MESSAGE, message);
  15642. }
  15643. }
  15644. }
  15645. };
  15646. _proto.ping = function ping() {
  15647. return this.send(new GenericCommand({
  15648. cmd: CommandType.echo
  15649. }))["catch"](function (error) {
  15650. return debug$4('ping failed:', error);
  15651. });
  15652. };
  15653. return Connection;
  15654. }(WebSocketPlus);
  15655. var promiseTimeout = createCommonjsModule(function (module) {
  15656. /**
  15657. * Local reference to TimeoutError
  15658. * @private
  15659. */
  15660. var TimeoutError;
  15661. /**
  15662. * Rejects a promise with a {@link TimeoutError} if it does not settle within
  15663. * the specified timeout.
  15664. *
  15665. * @param {Promise} promise The promise.
  15666. * @param {number} timeoutMillis Number of milliseconds to wait on settling.
  15667. * @returns {Promise} Either resolves/rejects with `promise`, or rejects with
  15668. * `TimeoutError`, whichever settles first.
  15669. */
  15670. var timeout = module.exports.timeout = function (promise, timeoutMillis) {
  15671. var error = new TimeoutError(),
  15672. timeout;
  15673. return Promise.race([promise, new Promise(function (resolve, reject) {
  15674. timeout = setTimeout(function () {
  15675. reject(error);
  15676. }, timeoutMillis);
  15677. })]).then(function (v) {
  15678. clearTimeout(timeout);
  15679. return v;
  15680. }, function (err) {
  15681. clearTimeout(timeout);
  15682. throw err;
  15683. });
  15684. };
  15685. /**
  15686. * Exception indicating that the timeout expired.
  15687. */
  15688. TimeoutError = module.exports.TimeoutError = function () {
  15689. Error.call(this);
  15690. this.stack = Error().stack;
  15691. this.message = 'Timeout';
  15692. };
  15693. TimeoutError.prototype = Object.create(Error.prototype);
  15694. TimeoutError.prototype.name = "TimeoutError";
  15695. });
  15696. var promiseTimeout_1 = promiseTimeout.timeout;
  15697. var promiseTimeout_2 = promiseTimeout.TimeoutError;
  15698. var debug$5 = browser('LC:request');
  15699. var request = (function (_ref) {
  15700. var _ref$method = _ref.method,
  15701. method = _ref$method === void 0 ? 'GET' : _ref$method,
  15702. _url = _ref.url,
  15703. query = _ref.query,
  15704. headers = _ref.headers,
  15705. data = _ref.data,
  15706. time = _ref.timeout;
  15707. var url = _url;
  15708. if (query) {
  15709. var queryString = Object.keys(query).map(function (key) {
  15710. var value = query[key];
  15711. if (value === undefined) return undefined;
  15712. var v = isPlainObject_1(value) ? JSON.stringify(value) : value;
  15713. return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(v));
  15714. }).filter(function (qs) {
  15715. return qs;
  15716. }).join('&');
  15717. url = "".concat(url, "?").concat(queryString);
  15718. }
  15719. debug$5('Req: %O %O %O', method, url, {
  15720. headers: headers,
  15721. data: data
  15722. });
  15723. var request = getAdapter('request');
  15724. var promise = request(url, {
  15725. method: method,
  15726. headers: headers,
  15727. data: data
  15728. }).then(function (response) {
  15729. if (response.ok === false) {
  15730. var error = createError(response.data);
  15731. error.response = response;
  15732. throw error;
  15733. }
  15734. debug$5('Res: %O %O %O', url, response.status, response.data);
  15735. return response.data;
  15736. })["catch"](function (error) {
  15737. if (error.response) {
  15738. debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
  15739. }
  15740. throw error;
  15741. });
  15742. return time ? promiseTimeout_1(promise, time) : promise;
  15743. });
  15744. var checkType = function checkType(middleware) {
  15745. return function (param) {
  15746. var constructor = param.constructor;
  15747. return Promise.resolve(param).then(middleware).then(tap(function (result) {
  15748. if (result === undefined || result === null) {
  15749. // eslint-disable-next-line max-len
  15750. return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns ").concat(result, " while a ").concat(param.constructor.name, " expected."));
  15751. }
  15752. if (!(result instanceof constructor)) {
  15753. // eslint-disable-next-line max-len
  15754. return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns a ").concat(result.constructor.name, " while a ").concat(param.constructor.name, " expected."));
  15755. }
  15756. return 0;
  15757. }));
  15758. };
  15759. };
  15760. var applyDecorators = function applyDecorators(decorators, target) {
  15761. if (decorators) {
  15762. decorators.forEach(function (decorator) {
  15763. try {
  15764. decorator(target);
  15765. } catch (error) {
  15766. if (decorator._pluginName) {
  15767. error.message += "[".concat(decorator._pluginName, "]");
  15768. }
  15769. throw error;
  15770. }
  15771. });
  15772. }
  15773. };
  15774. var applyMiddlewares = function applyMiddlewares(middlewares) {
  15775. return function (target) {
  15776. return ensureArray(middlewares).reduce(function (previousPromise, middleware) {
  15777. return previousPromise.then(checkType(middleware))["catch"](function (error) {
  15778. if (middleware._pluginName) {
  15779. // eslint-disable-next-line no-param-reassign
  15780. error.message += "[".concat(middleware._pluginName, "]");
  15781. }
  15782. throw error;
  15783. });
  15784. }, Promise.resolve(target));
  15785. };
  15786. };
  15787. var applyDispatcher = function applyDispatcher(dispatchers, payload) {
  15788. return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
  15789. return resultPromise.then(function (shouldDispatch) {
  15790. return shouldDispatch === false ? false : dispatcher.apply(void 0, toConsumableArray(payload));
  15791. })["catch"](function (error) {
  15792. if (dispatcher._pluginName) {
  15793. // eslint-disable-next-line no-param-reassign
  15794. error.message += "[".concat(dispatcher._pluginName, "]");
  15795. }
  15796. throw error;
  15797. });
  15798. }, Promise.resolve(true));
  15799. };
  15800. var version = "5.0.0-rc.7";
  15801. function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  15802. function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  15803. var debug$6 = browser('LC:Realtime');
  15804. var routerCache = new Cache('push-router');
  15805. var initializedApp = {};
  15806. var Realtime = /*#__PURE__*/function (_EventEmitter) {
  15807. inheritsLoose(Realtime, _EventEmitter);
  15808. /**
  15809. * @extends EventEmitter
  15810. * @param {Object} options
  15811. * @param {String} options.appId
  15812. * @param {String} options.appKey (since 4.0.0)
  15813. * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
  15814. * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
  15815. * 适用于 WebSocket 实现不支持二进制数据格式的情况
  15816. * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
  15817. * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
  15818. * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
  15819. */
  15820. function Realtime(_ref) {
  15821. var _this2;
  15822. var plugins = _ref.plugins,
  15823. options = objectWithoutProperties(_ref, ["plugins"]);
  15824. debug$6('initializing Realtime %s %O', version, options);
  15825. _this2 = _EventEmitter.call(this) || this;
  15826. var appId = options.appId;
  15827. if (typeof appId !== 'string') {
  15828. throw new TypeError("appId [".concat(appId, "] is not a string"));
  15829. }
  15830. if (initializedApp[appId]) {
  15831. throw new Error("App [".concat(appId, "] is already initialized."));
  15832. }
  15833. initializedApp[appId] = true;
  15834. if (typeof options.appKey !== 'string') {
  15835. throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
  15836. }
  15837. if (isCNApp(appId)) {
  15838. if (!options.server) {
  15839. throw new TypeError("server option is required for apps from CN region");
  15840. }
  15841. }
  15842. _this2._options = _objectSpread$2({
  15843. appId: undefined,
  15844. appKey: undefined,
  15845. noBinary: false,
  15846. ssl: true,
  15847. RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined
  15848. }, options);
  15849. _this2._cache = new Cache('endpoints');
  15850. var _this = internal(assertThisInitialized(_this2));
  15851. _this.clients = new Set();
  15852. _this.pendingClients = new Set();
  15853. var mergedPlugins = [].concat(toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), toConsumableArray(ensureArray(plugins)));
  15854. debug$6('Using plugins %o', mergedPlugins.map(function (plugin) {
  15855. return plugin.name;
  15856. }));
  15857. _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
  15858. Object.keys(plugin).forEach(function (hook) {
  15859. if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
  15860. if (plugin.name) {
  15861. ensureArray(plugin[hook]).forEach(function (value) {
  15862. // eslint-disable-next-line no-param-reassign
  15863. value._pluginName = plugin.name;
  15864. });
  15865. } // eslint-disable-next-line no-param-reassign
  15866. result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
  15867. }
  15868. });
  15869. return result;
  15870. }, {}); // onRealtimeCreate hook
  15871. applyDecorators(_this2._plugins.onRealtimeCreate, assertThisInitialized(_this2));
  15872. return _this2;
  15873. }
  15874. var _proto = Realtime.prototype;
  15875. _proto._request = /*#__PURE__*/function () {
  15876. var _request2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(_ref2) {
  15877. var method, _url, _ref2$version, version, path, query, headers, data, url, _this$_options, appId, server, _yield$this$construct, api;
  15878. return regenerator.wrap(function _callee$(_context) {
  15879. while (1) {
  15880. switch (_context.prev = _context.next) {
  15881. case 0:
  15882. method = _ref2.method, _url = _ref2.url, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, data = _ref2.data;
  15883. url = _url;
  15884. if (url) {
  15885. _context.next = 9;
  15886. break;
  15887. }
  15888. _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
  15889. _context.next = 6;
  15890. return this.constructor._getServerUrls({
  15891. appId: appId,
  15892. server: server
  15893. });
  15894. case 6:
  15895. _yield$this$construct = _context.sent;
  15896. api = _yield$this$construct.api;
  15897. url = "".concat(api, "/").concat(version).concat(path);
  15898. case 9:
  15899. return _context.abrupt("return", request({
  15900. url: url,
  15901. method: method,
  15902. query: query,
  15903. headers: _objectSpread$2({
  15904. 'X-LC-Id': this._options.appId,
  15905. 'X-LC-Key': this._options.appKey
  15906. }, headers),
  15907. data: data
  15908. }));
  15909. case 10:
  15910. case "end":
  15911. return _context.stop();
  15912. }
  15913. }
  15914. }, _callee, this);
  15915. }));
  15916. function _request(_x) {
  15917. return _request2.apply(this, arguments);
  15918. }
  15919. return _request;
  15920. }();
  15921. _proto._open = function _open() {
  15922. var _this3 = this;
  15923. if (this._openPromise) return this._openPromise;
  15924. var format = 'protobuf2';
  15925. if (this._options.noBinary) {
  15926. // 不发送 binary data,fallback to base64 string
  15927. format = 'proto2base64';
  15928. }
  15929. var version = 3;
  15930. var protocol = {
  15931. format: format,
  15932. version: version
  15933. };
  15934. this._openPromise = new Promise(function (resolve, reject) {
  15935. debug$6('No connection established, create a new one.');
  15936. var connection = new Connection(function () {
  15937. return _this3._getRTMServers(_this3._options);
  15938. }, protocol);
  15939. connection.on(OPEN, function () {
  15940. return resolve(connection);
  15941. }).on(ERROR, function (error) {
  15942. delete _this3._openPromise;
  15943. reject(error);
  15944. }).on(EXPIRE, /*#__PURE__*/asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  15945. return regenerator.wrap(function _callee2$(_context2) {
  15946. while (1) {
  15947. switch (_context2.prev = _context2.next) {
  15948. case 0:
  15949. debug$6('Connection expired. Refresh endpoints.');
  15950. _this3._cache.set('endpoints', null, 0);
  15951. _context2.next = 4;
  15952. return _this3._getRTMServers(_this3._options);
  15953. case 4:
  15954. connection.urls = _context2.sent;
  15955. connection.disconnect();
  15956. case 6:
  15957. case "end":
  15958. return _context2.stop();
  15959. }
  15960. }
  15961. }, _callee2);
  15962. }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
  15963. /**
  15964. * 连接断开。
  15965. * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
  15966. * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
  15967. * @event Realtime#DISCONNECT
  15968. */
  15969. /**
  15970. * 计划在一段时间后尝试重新连接
  15971. * @event Realtime#SCHEDULE
  15972. * @param {Number} attempt 尝试重连的次数
  15973. * @param {Number} delay 延迟的毫秒数
  15974. */
  15975. /**
  15976. * 正在尝试重新连接
  15977. * @event Realtime#RETRY
  15978. * @param {Number} attempt 尝试重连的次数
  15979. */
  15980. /**
  15981. * 连接恢复正常。
  15982. * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
  15983. * @event Realtime#RECONNECT
  15984. */
  15985. /**
  15986. * 客户端连接断开
  15987. * @event IMClient#DISCONNECT
  15988. * @see Realtime#event:DISCONNECT
  15989. * @since 3.2.0
  15990. */
  15991. /**
  15992. * 计划在一段时间后尝试重新连接
  15993. * @event IMClient#SCHEDULE
  15994. * @param {Number} attempt 尝试重连的次数
  15995. * @param {Number} delay 延迟的毫秒数
  15996. * @since 3.2.0
  15997. */
  15998. /**
  15999. * 正在尝试重新连接
  16000. * @event IMClient#RETRY
  16001. * @param {Number} attempt 尝试重连的次数
  16002. * @since 3.2.0
  16003. */
  16004. /**
  16005. * 客户端进入离线状态。
  16006. * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
  16007. * @event Realtime#OFFLINE
  16008. * @since 3.4.0
  16009. */
  16010. /**
  16011. * 客户端恢复在线状态
  16012. * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
  16013. * @event Realtime#ONLINE
  16014. * @since 3.4.0
  16015. */
  16016. /**
  16017. * 进入离线状态。
  16018. * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
  16019. * @event IMClient#OFFLINE
  16020. * @since 3.4.0
  16021. */
  16022. /**
  16023. * 恢复在线状态
  16024. * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
  16025. * @event IMClient#ONLINE
  16026. * @since 3.4.0
  16027. */
  16028. // event proxy
  16029. [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
  16030. return connection.on(event, function () {
  16031. for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
  16032. payload[_key] = arguments[_key];
  16033. }
  16034. debug$6("".concat(event, " event emitted. %o"), payload);
  16035. _this3.emit.apply(_this3, [event].concat(payload));
  16036. if (event !== RECONNECT) {
  16037. internal(_this3).clients.forEach(function (client) {
  16038. client.emit.apply(client, [event].concat(payload));
  16039. });
  16040. }
  16041. });
  16042. }); // override handleClose
  16043. connection.handleClose = function handleClose(event) {
  16044. var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
  16045. return errorCode === event.code;
  16046. });
  16047. if (isFatal) {
  16048. // in these cases, SDK should throw.
  16049. this["throw"](createError(event));
  16050. } else {
  16051. // reconnect
  16052. this.disconnect();
  16053. }
  16054. };
  16055. internal(_this3).connection = connection;
  16056. });
  16057. return this._openPromise;
  16058. };
  16059. _proto._getRTMServers = /*#__PURE__*/function () {
  16060. var _getRTMServers2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(options) {
  16061. var info, cachedEndPoints, _info, server, secondary, ttl;
  16062. return regenerator.wrap(function _callee3$(_context3) {
  16063. while (1) {
  16064. switch (_context3.prev = _context3.next) {
  16065. case 0:
  16066. if (!options.RTMServers) {
  16067. _context3.next = 2;
  16068. break;
  16069. }
  16070. return _context3.abrupt("return", shuffle_1(ensureArray(options.RTMServers)));
  16071. case 2:
  16072. cachedEndPoints = this._cache.get('endpoints');
  16073. if (!cachedEndPoints) {
  16074. _context3.next = 7;
  16075. break;
  16076. }
  16077. info = cachedEndPoints;
  16078. _context3.next = 14;
  16079. break;
  16080. case 7:
  16081. _context3.next = 9;
  16082. return this.constructor._fetchRTMServers(options);
  16083. case 9:
  16084. info = _context3.sent;
  16085. _info = info, server = _info.server, secondary = _info.secondary, ttl = _info.ttl;
  16086. if (!(typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number')) {
  16087. _context3.next = 13;
  16088. break;
  16089. }
  16090. throw new Error("malformed RTM route response: ".concat(JSON.stringify(info)));
  16091. case 13:
  16092. this._cache.set('endpoints', info, info.ttl * 1000);
  16093. case 14:
  16094. debug$6('endpoint info: %O', info);
  16095. return _context3.abrupt("return", [info.server, info.secondary]);
  16096. case 16:
  16097. case "end":
  16098. return _context3.stop();
  16099. }
  16100. }
  16101. }, _callee3, this);
  16102. }));
  16103. function _getRTMServers(_x2) {
  16104. return _getRTMServers2.apply(this, arguments);
  16105. }
  16106. return _getRTMServers;
  16107. }();
  16108. Realtime._getServerUrls = /*#__PURE__*/function () {
  16109. var _getServerUrls2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(_ref4) {
  16110. var appId, server, cachedRouter, defaultProtocol;
  16111. return regenerator.wrap(function _callee4$(_context4) {
  16112. while (1) {
  16113. switch (_context4.prev = _context4.next) {
  16114. case 0:
  16115. appId = _ref4.appId, server = _ref4.server;
  16116. debug$6('fetch server urls');
  16117. if (!server) {
  16118. _context4.next = 6;
  16119. break;
  16120. }
  16121. if (!(typeof server !== 'string')) {
  16122. _context4.next = 5;
  16123. break;
  16124. }
  16125. return _context4.abrupt("return", server);
  16126. case 5:
  16127. return _context4.abrupt("return", {
  16128. RTMRouter: server,
  16129. api: server
  16130. });
  16131. case 6:
  16132. cachedRouter = routerCache.get(appId);
  16133. if (!cachedRouter) {
  16134. _context4.next = 9;
  16135. break;
  16136. }
  16137. return _context4.abrupt("return", cachedRouter);
  16138. case 9:
  16139. defaultProtocol = 'https://';
  16140. return _context4.abrupt("return", request({
  16141. url: 'https://app-router.com/2/route',
  16142. query: {
  16143. appId: appId
  16144. },
  16145. timeout: 20000
  16146. }).then(tap(debug$6)).then(function (_ref5) {
  16147. var RTMRouterServer = _ref5.rtm_router_server,
  16148. APIServer = _ref5.api_server,
  16149. _ref5$ttl = _ref5.ttl,
  16150. ttl = _ref5$ttl === void 0 ? 3600 : _ref5$ttl;
  16151. if (!RTMRouterServer) {
  16152. throw new Error('rtm router not exists');
  16153. }
  16154. var serverUrls = {
  16155. RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
  16156. api: "".concat(defaultProtocol).concat(APIServer)
  16157. };
  16158. routerCache.set(appId, serverUrls, ttl * 1000);
  16159. return serverUrls;
  16160. })["catch"](function () {
  16161. var id = appId.slice(0, 8).toLowerCase();
  16162. var domain = 'lncldglobal.com';
  16163. return {
  16164. RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
  16165. api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
  16166. };
  16167. }));
  16168. case 11:
  16169. case "end":
  16170. return _context4.stop();
  16171. }
  16172. }
  16173. }, _callee4);
  16174. }));
  16175. function _getServerUrls(_x3) {
  16176. return _getServerUrls2.apply(this, arguments);
  16177. }
  16178. return _getServerUrls;
  16179. }();
  16180. Realtime._fetchRTMServers = function _fetchRTMServers(_ref6) {
  16181. var appId = _ref6.appId,
  16182. ssl = _ref6.ssl,
  16183. server = _ref6.server,
  16184. RTMServerName = _ref6.RTMServerName;
  16185. debug$6('fetch endpoint info');
  16186. return this._getServerUrls({
  16187. appId: appId,
  16188. server: server
  16189. }).then(tap(debug$6)).then(function (_ref7) {
  16190. var RTMRouter = _ref7.RTMRouter;
  16191. return request({
  16192. url: "".concat(RTMRouter, "/v1/route"),
  16193. query: {
  16194. appId: appId,
  16195. secure: ssl,
  16196. features: isWeapp ? 'wechat' : undefined,
  16197. server: RTMServerName,
  16198. _t: Date.now()
  16199. },
  16200. timeout: 20000
  16201. }).then(tap(debug$6));
  16202. });
  16203. };
  16204. _proto._close = function _close() {
  16205. if (this._openPromise) {
  16206. this._openPromise.then(function (connection) {
  16207. return connection.close();
  16208. });
  16209. }
  16210. delete this._openPromise;
  16211. }
  16212. /**
  16213. * 手动进行重连。
  16214. * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
  16215. * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
  16216. */
  16217. ;
  16218. _proto.retry = function retry() {
  16219. var _internal = internal(this),
  16220. connection = _internal.connection;
  16221. if (!connection) {
  16222. throw new Error('no connection established');
  16223. }
  16224. if (connection.cannot('retry')) {
  16225. throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
  16226. }
  16227. return connection.retry();
  16228. }
  16229. /**
  16230. * 暂停,使 SDK 进入离线状态。
  16231. * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
  16232. * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
  16233. *
  16234. * @since 3.4.0
  16235. * @see Realtime#event:OFFLINE
  16236. */
  16237. ;
  16238. _proto.pause = function pause() {
  16239. // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
  16240. // 因此不像 retry,这个方法应该尽可能 loose
  16241. var _internal2 = internal(this),
  16242. connection = _internal2.connection;
  16243. if (!connection) return;
  16244. if (connection.can('pause')) connection.pause();
  16245. }
  16246. /**
  16247. * 恢复在线状态。
  16248. * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
  16249. *
  16250. * @since 3.4.0
  16251. * @see Realtime#event:ONLINE
  16252. */
  16253. ;
  16254. _proto.resume = function resume() {
  16255. // 与 pause 一样,这个方法应该尽可能 loose
  16256. var _internal3 = internal(this),
  16257. connection = _internal3.connection;
  16258. if (!connection) return;
  16259. if (connection.can('resume')) connection.resume();
  16260. };
  16261. _proto._registerPending = function _registerPending(value) {
  16262. internal(this).pendingClients.add(value);
  16263. };
  16264. _proto._deregisterPending = function _deregisterPending(client) {
  16265. internal(this).pendingClients["delete"](client);
  16266. };
  16267. _proto._register = function _register(client) {
  16268. internal(this).clients.add(client);
  16269. };
  16270. _proto._deregister = function _deregister(client) {
  16271. var _this = internal(this);
  16272. _this.clients["delete"](client);
  16273. if (_this.clients.size + _this.pendingClients.size === 0) {
  16274. this._close();
  16275. }
  16276. };
  16277. _proto._dispatchCommand = function _dispatchCommand(command) {
  16278. return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
  16279. // no plugin handled this command
  16280. if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
  16281. return false;
  16282. });
  16283. };
  16284. return Realtime;
  16285. }(eventemitter3); // For test purpose only
  16286. var polyfilledPromise = Promise;
  16287. var rngBrowser = createCommonjsModule(function (module) {
  16288. // Unique ID creation requires a high quality random # generator. In the
  16289. // browser this is a little complicated due to unknown quality of Math.random()
  16290. // and inconsistent support for the `crypto` API. We do the best we can via
  16291. // feature-detection
  16292. // getRandomValues needs to be invoked in a context where "this" is a Crypto
  16293. // implementation. Also, find the complete implementation of crypto on IE11.
  16294. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
  16295. (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
  16296. if (getRandomValues) {
  16297. // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  16298. var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  16299. module.exports = function whatwgRNG() {
  16300. getRandomValues(rnds8);
  16301. return rnds8;
  16302. };
  16303. } else {
  16304. // Math.random()-based (RNG)
  16305. //
  16306. // If all else fails, use Math.random(). It's fast, but is of unspecified
  16307. // quality.
  16308. var rnds = new Array(16);
  16309. module.exports = function mathRNG() {
  16310. for (var i = 0, r; i < 16; i++) {
  16311. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  16312. rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  16313. }
  16314. return rnds;
  16315. };
  16316. }
  16317. });
  16318. /**
  16319. * Convert array of 16 byte values to UUID string format of the form:
  16320. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  16321. */
  16322. var byteToHex = [];
  16323. for (var i = 0; i < 256; ++i) {
  16324. byteToHex[i] = (i + 0x100).toString(16).substr(1);
  16325. }
  16326. function bytesToUuid(buf, offset) {
  16327. var i = offset || 0;
  16328. var bth = byteToHex;
  16329. // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  16330. return ([bth[buf[i++]], bth[buf[i++]],
  16331. bth[buf[i++]], bth[buf[i++]], '-',
  16332. bth[buf[i++]], bth[buf[i++]], '-',
  16333. bth[buf[i++]], bth[buf[i++]], '-',
  16334. bth[buf[i++]], bth[buf[i++]], '-',
  16335. bth[buf[i++]], bth[buf[i++]],
  16336. bth[buf[i++]], bth[buf[i++]],
  16337. bth[buf[i++]], bth[buf[i++]]]).join('');
  16338. }
  16339. var bytesToUuid_1 = bytesToUuid;
  16340. function v4(options, buf, offset) {
  16341. var i = buf && offset || 0;
  16342. if (typeof(options) == 'string') {
  16343. buf = options === 'binary' ? new Array(16) : null;
  16344. options = null;
  16345. }
  16346. options = options || {};
  16347. var rnds = options.random || (options.rng || rngBrowser)();
  16348. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  16349. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  16350. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  16351. // Copy bytes to buffer, if provided
  16352. if (buf) {
  16353. for (var ii = 0; ii < 16; ++ii) {
  16354. buf[i + ii] = rnds[ii];
  16355. }
  16356. }
  16357. return buf || bytesToUuid_1(rnds);
  16358. }
  16359. var v4_1 = v4;
  16360. function _iterableToArrayLimit(arr, i) {
  16361. if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  16362. var _arr = [];
  16363. var _n = true;
  16364. var _d = false;
  16365. var _e = undefined;
  16366. try {
  16367. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  16368. _arr.push(_s.value);
  16369. if (i && _arr.length === i) break;
  16370. }
  16371. } catch (err) {
  16372. _d = true;
  16373. _e = err;
  16374. } finally {
  16375. try {
  16376. if (!_n && _i["return"] != null) _i["return"]();
  16377. } finally {
  16378. if (_d) throw _e;
  16379. }
  16380. }
  16381. return _arr;
  16382. }
  16383. var iterableToArrayLimit = _iterableToArrayLimit;
  16384. function _slicedToArray(arr, i) {
  16385. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
  16386. }
  16387. var slicedToArray = _slicedToArray;
  16388. var base64Arraybuffer = createCommonjsModule(function (module, exports) {
  16389. /*
  16390. * base64-arraybuffer
  16391. * https://github.com/niklasvh/base64-arraybuffer
  16392. *
  16393. * Copyright (c) 2012 Niklas von Hertzen
  16394. * Licensed under the MIT license.
  16395. */
  16396. (function(){
  16397. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  16398. // Use a lookup table to find the index.
  16399. var lookup = new Uint8Array(256);
  16400. for (var i = 0; i < chars.length; i++) {
  16401. lookup[chars.charCodeAt(i)] = i;
  16402. }
  16403. exports.encode = function(arraybuffer) {
  16404. var bytes = new Uint8Array(arraybuffer),
  16405. i, len = bytes.length, base64 = "";
  16406. for (i = 0; i < len; i+=3) {
  16407. base64 += chars[bytes[i] >> 2];
  16408. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  16409. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  16410. base64 += chars[bytes[i + 2] & 63];
  16411. }
  16412. if ((len % 3) === 2) {
  16413. base64 = base64.substring(0, base64.length - 1) + "=";
  16414. } else if (len % 3 === 1) {
  16415. base64 = base64.substring(0, base64.length - 2) + "==";
  16416. }
  16417. return base64;
  16418. };
  16419. exports.decode = function(base64) {
  16420. var bufferLength = base64.length * 0.75,
  16421. len = base64.length, i, p = 0,
  16422. encoded1, encoded2, encoded3, encoded4;
  16423. if (base64[base64.length - 1] === "=") {
  16424. bufferLength--;
  16425. if (base64[base64.length - 2] === "=") {
  16426. bufferLength--;
  16427. }
  16428. }
  16429. var arraybuffer = new ArrayBuffer(bufferLength),
  16430. bytes = new Uint8Array(arraybuffer);
  16431. for (i = 0; i < len; i+=4) {
  16432. encoded1 = lookup[base64.charCodeAt(i)];
  16433. encoded2 = lookup[base64.charCodeAt(i+1)];
  16434. encoded3 = lookup[base64.charCodeAt(i+2)];
  16435. encoded4 = lookup[base64.charCodeAt(i+3)];
  16436. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  16437. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  16438. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  16439. }
  16440. return arraybuffer;
  16441. };
  16442. })();
  16443. });
  16444. var base64Arraybuffer_1 = base64Arraybuffer.encode;
  16445. var base64Arraybuffer_2 = base64Arraybuffer.decode;
  16446. /**
  16447. * Removes all key-value entries from the list cache.
  16448. *
  16449. * @private
  16450. * @name clear
  16451. * @memberOf ListCache
  16452. */
  16453. function listCacheClear() {
  16454. this.__data__ = [];
  16455. this.size = 0;
  16456. }
  16457. var _listCacheClear = listCacheClear;
  16458. /**
  16459. * Performs a
  16460. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  16461. * comparison between two values to determine if they are equivalent.
  16462. *
  16463. * @static
  16464. * @memberOf _
  16465. * @since 4.0.0
  16466. * @category Lang
  16467. * @param {*} value The value to compare.
  16468. * @param {*} other The other value to compare.
  16469. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  16470. * @example
  16471. *
  16472. * var object = { 'a': 1 };
  16473. * var other = { 'a': 1 };
  16474. *
  16475. * _.eq(object, object);
  16476. * // => true
  16477. *
  16478. * _.eq(object, other);
  16479. * // => false
  16480. *
  16481. * _.eq('a', 'a');
  16482. * // => true
  16483. *
  16484. * _.eq('a', Object('a'));
  16485. * // => false
  16486. *
  16487. * _.eq(NaN, NaN);
  16488. * // => true
  16489. */
  16490. function eq(value, other) {
  16491. return value === other || (value !== value && other !== other);
  16492. }
  16493. var eq_1 = eq;
  16494. /**
  16495. * Gets the index at which the `key` is found in `array` of key-value pairs.
  16496. *
  16497. * @private
  16498. * @param {Array} array The array to inspect.
  16499. * @param {*} key The key to search for.
  16500. * @returns {number} Returns the index of the matched value, else `-1`.
  16501. */
  16502. function assocIndexOf(array, key) {
  16503. var length = array.length;
  16504. while (length--) {
  16505. if (eq_1(array[length][0], key)) {
  16506. return length;
  16507. }
  16508. }
  16509. return -1;
  16510. }
  16511. var _assocIndexOf = assocIndexOf;
  16512. /** Used for built-in method references. */
  16513. var arrayProto = Array.prototype;
  16514. /** Built-in value references. */
  16515. var splice = arrayProto.splice;
  16516. /**
  16517. * Removes `key` and its value from the list cache.
  16518. *
  16519. * @private
  16520. * @name delete
  16521. * @memberOf ListCache
  16522. * @param {string} key The key of the value to remove.
  16523. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  16524. */
  16525. function listCacheDelete(key) {
  16526. var data = this.__data__,
  16527. index = _assocIndexOf(data, key);
  16528. if (index < 0) {
  16529. return false;
  16530. }
  16531. var lastIndex = data.length - 1;
  16532. if (index == lastIndex) {
  16533. data.pop();
  16534. } else {
  16535. splice.call(data, index, 1);
  16536. }
  16537. --this.size;
  16538. return true;
  16539. }
  16540. var _listCacheDelete = listCacheDelete;
  16541. /**
  16542. * Gets the list cache value for `key`.
  16543. *
  16544. * @private
  16545. * @name get
  16546. * @memberOf ListCache
  16547. * @param {string} key The key of the value to get.
  16548. * @returns {*} Returns the entry value.
  16549. */
  16550. function listCacheGet(key) {
  16551. var data = this.__data__,
  16552. index = _assocIndexOf(data, key);
  16553. return index < 0 ? undefined : data[index][1];
  16554. }
  16555. var _listCacheGet = listCacheGet;
  16556. /**
  16557. * Checks if a list cache value for `key` exists.
  16558. *
  16559. * @private
  16560. * @name has
  16561. * @memberOf ListCache
  16562. * @param {string} key The key of the entry to check.
  16563. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  16564. */
  16565. function listCacheHas(key) {
  16566. return _assocIndexOf(this.__data__, key) > -1;
  16567. }
  16568. var _listCacheHas = listCacheHas;
  16569. /**
  16570. * Sets the list cache `key` to `value`.
  16571. *
  16572. * @private
  16573. * @name set
  16574. * @memberOf ListCache
  16575. * @param {string} key The key of the value to set.
  16576. * @param {*} value The value to set.
  16577. * @returns {Object} Returns the list cache instance.
  16578. */
  16579. function listCacheSet(key, value) {
  16580. var data = this.__data__,
  16581. index = _assocIndexOf(data, key);
  16582. if (index < 0) {
  16583. ++this.size;
  16584. data.push([key, value]);
  16585. } else {
  16586. data[index][1] = value;
  16587. }
  16588. return this;
  16589. }
  16590. var _listCacheSet = listCacheSet;
  16591. /**
  16592. * Creates an list cache object.
  16593. *
  16594. * @private
  16595. * @constructor
  16596. * @param {Array} [entries] The key-value pairs to cache.
  16597. */
  16598. function ListCache(entries) {
  16599. var index = -1,
  16600. length = entries == null ? 0 : entries.length;
  16601. this.clear();
  16602. while (++index < length) {
  16603. var entry = entries[index];
  16604. this.set(entry[0], entry[1]);
  16605. }
  16606. }
  16607. // Add methods to `ListCache`.
  16608. ListCache.prototype.clear = _listCacheClear;
  16609. ListCache.prototype['delete'] = _listCacheDelete;
  16610. ListCache.prototype.get = _listCacheGet;
  16611. ListCache.prototype.has = _listCacheHas;
  16612. ListCache.prototype.set = _listCacheSet;
  16613. var _ListCache = ListCache;
  16614. /**
  16615. * Removes all key-value entries from the stack.
  16616. *
  16617. * @private
  16618. * @name clear
  16619. * @memberOf Stack
  16620. */
  16621. function stackClear() {
  16622. this.__data__ = new _ListCache;
  16623. this.size = 0;
  16624. }
  16625. var _stackClear = stackClear;
  16626. /**
  16627. * Removes `key` and its value from the stack.
  16628. *
  16629. * @private
  16630. * @name delete
  16631. * @memberOf Stack
  16632. * @param {string} key The key of the value to remove.
  16633. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  16634. */
  16635. function stackDelete(key) {
  16636. var data = this.__data__,
  16637. result = data['delete'](key);
  16638. this.size = data.size;
  16639. return result;
  16640. }
  16641. var _stackDelete = stackDelete;
  16642. /**
  16643. * Gets the stack value for `key`.
  16644. *
  16645. * @private
  16646. * @name get
  16647. * @memberOf Stack
  16648. * @param {string} key The key of the value to get.
  16649. * @returns {*} Returns the entry value.
  16650. */
  16651. function stackGet(key) {
  16652. return this.__data__.get(key);
  16653. }
  16654. var _stackGet = stackGet;
  16655. /**
  16656. * Checks if a stack value for `key` exists.
  16657. *
  16658. * @private
  16659. * @name has
  16660. * @memberOf Stack
  16661. * @param {string} key The key of the entry to check.
  16662. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  16663. */
  16664. function stackHas(key) {
  16665. return this.__data__.has(key);
  16666. }
  16667. var _stackHas = stackHas;
  16668. /** Used to detect overreaching core-js shims. */
  16669. var coreJsData = _root['__core-js_shared__'];
  16670. var _coreJsData = coreJsData;
  16671. /** Used to detect methods masquerading as native. */
  16672. var maskSrcKey = (function() {
  16673. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  16674. return uid ? ('Symbol(src)_1.' + uid) : '';
  16675. }());
  16676. /**
  16677. * Checks if `func` has its source masked.
  16678. *
  16679. * @private
  16680. * @param {Function} func The function to check.
  16681. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  16682. */
  16683. function isMasked(func) {
  16684. return !!maskSrcKey && (maskSrcKey in func);
  16685. }
  16686. var _isMasked = isMasked;
  16687. /** Used for built-in method references. */
  16688. var funcProto$1 = Function.prototype;
  16689. /** Used to resolve the decompiled source of functions. */
  16690. var funcToString$1 = funcProto$1.toString;
  16691. /**
  16692. * Converts `func` to its source code.
  16693. *
  16694. * @private
  16695. * @param {Function} func The function to convert.
  16696. * @returns {string} Returns the source code.
  16697. */
  16698. function toSource(func) {
  16699. if (func != null) {
  16700. try {
  16701. return funcToString$1.call(func);
  16702. } catch (e) {}
  16703. try {
  16704. return (func + '');
  16705. } catch (e) {}
  16706. }
  16707. return '';
  16708. }
  16709. var _toSource = toSource;
  16710. /**
  16711. * Used to match `RegExp`
  16712. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  16713. */
  16714. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  16715. /** Used to detect host constructors (Safari). */
  16716. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  16717. /** Used for built-in method references. */
  16718. var funcProto$2 = Function.prototype,
  16719. objectProto$7 = Object.prototype;
  16720. /** Used to resolve the decompiled source of functions. */
  16721. var funcToString$2 = funcProto$2.toString;
  16722. /** Used to check objects for own properties. */
  16723. var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
  16724. /** Used to detect if a method is native. */
  16725. var reIsNative = RegExp('^' +
  16726. funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&')
  16727. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  16728. );
  16729. /**
  16730. * The base implementation of `_.isNative` without bad shim checks.
  16731. *
  16732. * @private
  16733. * @param {*} value The value to check.
  16734. * @returns {boolean} Returns `true` if `value` is a native function,
  16735. * else `false`.
  16736. */
  16737. function baseIsNative(value) {
  16738. if (!isObject_1$1(value) || _isMasked(value)) {
  16739. return false;
  16740. }
  16741. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  16742. return pattern.test(_toSource(value));
  16743. }
  16744. var _baseIsNative = baseIsNative;
  16745. /**
  16746. * Gets the value at `key` of `object`.
  16747. *
  16748. * @private
  16749. * @param {Object} [object] The object to query.
  16750. * @param {string} key The key of the property to get.
  16751. * @returns {*} Returns the property value.
  16752. */
  16753. function getValue(object, key) {
  16754. return object == null ? undefined : object[key];
  16755. }
  16756. var _getValue = getValue;
  16757. /**
  16758. * Gets the native function at `key` of `object`.
  16759. *
  16760. * @private
  16761. * @param {Object} object The object to query.
  16762. * @param {string} key The key of the method to get.
  16763. * @returns {*} Returns the function if it's native, else `undefined`.
  16764. */
  16765. function getNative(object, key) {
  16766. var value = _getValue(object, key);
  16767. return _baseIsNative(value) ? value : undefined;
  16768. }
  16769. var _getNative = getNative;
  16770. /* Built-in method references that are verified to be native. */
  16771. var Map = _getNative(_root, 'Map');
  16772. var _Map = Map;
  16773. /* Built-in method references that are verified to be native. */
  16774. var nativeCreate = _getNative(Object, 'create');
  16775. var _nativeCreate = nativeCreate;
  16776. /**
  16777. * Removes all key-value entries from the hash.
  16778. *
  16779. * @private
  16780. * @name clear
  16781. * @memberOf Hash
  16782. */
  16783. function hashClear() {
  16784. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  16785. this.size = 0;
  16786. }
  16787. var _hashClear = hashClear;
  16788. /**
  16789. * Removes `key` and its value from the hash.
  16790. *
  16791. * @private
  16792. * @name delete
  16793. * @memberOf Hash
  16794. * @param {Object} hash The hash to modify.
  16795. * @param {string} key The key of the value to remove.
  16796. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  16797. */
  16798. function hashDelete(key) {
  16799. var result = this.has(key) && delete this.__data__[key];
  16800. this.size -= result ? 1 : 0;
  16801. return result;
  16802. }
  16803. var _hashDelete = hashDelete;
  16804. /** Used to stand-in for `undefined` hash values. */
  16805. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  16806. /** Used for built-in method references. */
  16807. var objectProto$8 = Object.prototype;
  16808. /** Used to check objects for own properties. */
  16809. var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
  16810. /**
  16811. * Gets the hash value for `key`.
  16812. *
  16813. * @private
  16814. * @name get
  16815. * @memberOf Hash
  16816. * @param {string} key The key of the value to get.
  16817. * @returns {*} Returns the entry value.
  16818. */
  16819. function hashGet(key) {
  16820. var data = this.__data__;
  16821. if (_nativeCreate) {
  16822. var result = data[key];
  16823. return result === HASH_UNDEFINED ? undefined : result;
  16824. }
  16825. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  16826. }
  16827. var _hashGet = hashGet;
  16828. /** Used for built-in method references. */
  16829. var objectProto$9 = Object.prototype;
  16830. /** Used to check objects for own properties. */
  16831. var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
  16832. /**
  16833. * Checks if a hash value for `key` exists.
  16834. *
  16835. * @private
  16836. * @name has
  16837. * @memberOf Hash
  16838. * @param {string} key The key of the entry to check.
  16839. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  16840. */
  16841. function hashHas(key) {
  16842. var data = this.__data__;
  16843. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key);
  16844. }
  16845. var _hashHas = hashHas;
  16846. /** Used to stand-in for `undefined` hash values. */
  16847. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  16848. /**
  16849. * Sets the hash `key` to `value`.
  16850. *
  16851. * @private
  16852. * @name set
  16853. * @memberOf Hash
  16854. * @param {string} key The key of the value to set.
  16855. * @param {*} value The value to set.
  16856. * @returns {Object} Returns the hash instance.
  16857. */
  16858. function hashSet(key, value) {
  16859. var data = this.__data__;
  16860. this.size += this.has(key) ? 0 : 1;
  16861. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  16862. return this;
  16863. }
  16864. var _hashSet = hashSet;
  16865. /**
  16866. * Creates a hash object.
  16867. *
  16868. * @private
  16869. * @constructor
  16870. * @param {Array} [entries] The key-value pairs to cache.
  16871. */
  16872. function Hash(entries) {
  16873. var index = -1,
  16874. length = entries == null ? 0 : entries.length;
  16875. this.clear();
  16876. while (++index < length) {
  16877. var entry = entries[index];
  16878. this.set(entry[0], entry[1]);
  16879. }
  16880. }
  16881. // Add methods to `Hash`.
  16882. Hash.prototype.clear = _hashClear;
  16883. Hash.prototype['delete'] = _hashDelete;
  16884. Hash.prototype.get = _hashGet;
  16885. Hash.prototype.has = _hashHas;
  16886. Hash.prototype.set = _hashSet;
  16887. var _Hash = Hash;
  16888. /**
  16889. * Removes all key-value entries from the map.
  16890. *
  16891. * @private
  16892. * @name clear
  16893. * @memberOf MapCache
  16894. */
  16895. function mapCacheClear() {
  16896. this.size = 0;
  16897. this.__data__ = {
  16898. 'hash': new _Hash,
  16899. 'map': new (_Map || _ListCache),
  16900. 'string': new _Hash
  16901. };
  16902. }
  16903. var _mapCacheClear = mapCacheClear;
  16904. /**
  16905. * Checks if `value` is suitable for use as unique object key.
  16906. *
  16907. * @private
  16908. * @param {*} value The value to check.
  16909. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  16910. */
  16911. function isKeyable(value) {
  16912. var type = typeof value;
  16913. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  16914. ? (value !== '__proto__')
  16915. : (value === null);
  16916. }
  16917. var _isKeyable = isKeyable;
  16918. /**
  16919. * Gets the data for `map`.
  16920. *
  16921. * @private
  16922. * @param {Object} map The map to query.
  16923. * @param {string} key The reference key.
  16924. * @returns {*} Returns the map data.
  16925. */
  16926. function getMapData(map, key) {
  16927. var data = map.__data__;
  16928. return _isKeyable(key)
  16929. ? data[typeof key == 'string' ? 'string' : 'hash']
  16930. : data.map;
  16931. }
  16932. var _getMapData = getMapData;
  16933. /**
  16934. * Removes `key` and its value from the map.
  16935. *
  16936. * @private
  16937. * @name delete
  16938. * @memberOf MapCache
  16939. * @param {string} key The key of the value to remove.
  16940. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  16941. */
  16942. function mapCacheDelete(key) {
  16943. var result = _getMapData(this, key)['delete'](key);
  16944. this.size -= result ? 1 : 0;
  16945. return result;
  16946. }
  16947. var _mapCacheDelete = mapCacheDelete;
  16948. /**
  16949. * Gets the map value for `key`.
  16950. *
  16951. * @private
  16952. * @name get
  16953. * @memberOf MapCache
  16954. * @param {string} key The key of the value to get.
  16955. * @returns {*} Returns the entry value.
  16956. */
  16957. function mapCacheGet(key) {
  16958. return _getMapData(this, key).get(key);
  16959. }
  16960. var _mapCacheGet = mapCacheGet;
  16961. /**
  16962. * Checks if a map value for `key` exists.
  16963. *
  16964. * @private
  16965. * @name has
  16966. * @memberOf MapCache
  16967. * @param {string} key The key of the entry to check.
  16968. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  16969. */
  16970. function mapCacheHas(key) {
  16971. return _getMapData(this, key).has(key);
  16972. }
  16973. var _mapCacheHas = mapCacheHas;
  16974. /**
  16975. * Sets the map `key` to `value`.
  16976. *
  16977. * @private
  16978. * @name set
  16979. * @memberOf MapCache
  16980. * @param {string} key The key of the value to set.
  16981. * @param {*} value The value to set.
  16982. * @returns {Object} Returns the map cache instance.
  16983. */
  16984. function mapCacheSet(key, value) {
  16985. var data = _getMapData(this, key),
  16986. size = data.size;
  16987. data.set(key, value);
  16988. this.size += data.size == size ? 0 : 1;
  16989. return this;
  16990. }
  16991. var _mapCacheSet = mapCacheSet;
  16992. /**
  16993. * Creates a map cache object to store key-value pairs.
  16994. *
  16995. * @private
  16996. * @constructor
  16997. * @param {Array} [entries] The key-value pairs to cache.
  16998. */
  16999. function MapCache(entries) {
  17000. var index = -1,
  17001. length = entries == null ? 0 : entries.length;
  17002. this.clear();
  17003. while (++index < length) {
  17004. var entry = entries[index];
  17005. this.set(entry[0], entry[1]);
  17006. }
  17007. }
  17008. // Add methods to `MapCache`.
  17009. MapCache.prototype.clear = _mapCacheClear;
  17010. MapCache.prototype['delete'] = _mapCacheDelete;
  17011. MapCache.prototype.get = _mapCacheGet;
  17012. MapCache.prototype.has = _mapCacheHas;
  17013. MapCache.prototype.set = _mapCacheSet;
  17014. var _MapCache = MapCache;
  17015. /** Used as the size to enable large array optimizations. */
  17016. var LARGE_ARRAY_SIZE = 200;
  17017. /**
  17018. * Sets the stack `key` to `value`.
  17019. *
  17020. * @private
  17021. * @name set
  17022. * @memberOf Stack
  17023. * @param {string} key The key of the value to set.
  17024. * @param {*} value The value to set.
  17025. * @returns {Object} Returns the stack cache instance.
  17026. */
  17027. function stackSet(key, value) {
  17028. var data = this.__data__;
  17029. if (data instanceof _ListCache) {
  17030. var pairs = data.__data__;
  17031. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  17032. pairs.push([key, value]);
  17033. this.size = ++data.size;
  17034. return this;
  17035. }
  17036. data = this.__data__ = new _MapCache(pairs);
  17037. }
  17038. data.set(key, value);
  17039. this.size = data.size;
  17040. return this;
  17041. }
  17042. var _stackSet = stackSet;
  17043. /**
  17044. * Creates a stack cache object to store key-value pairs.
  17045. *
  17046. * @private
  17047. * @constructor
  17048. * @param {Array} [entries] The key-value pairs to cache.
  17049. */
  17050. function Stack(entries) {
  17051. var data = this.__data__ = new _ListCache(entries);
  17052. this.size = data.size;
  17053. }
  17054. // Add methods to `Stack`.
  17055. Stack.prototype.clear = _stackClear;
  17056. Stack.prototype['delete'] = _stackDelete;
  17057. Stack.prototype.get = _stackGet;
  17058. Stack.prototype.has = _stackHas;
  17059. Stack.prototype.set = _stackSet;
  17060. var _Stack = Stack;
  17061. /** Used to stand-in for `undefined` hash values. */
  17062. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  17063. /**
  17064. * Adds `value` to the array cache.
  17065. *
  17066. * @private
  17067. * @name add
  17068. * @memberOf SetCache
  17069. * @alias push
  17070. * @param {*} value The value to cache.
  17071. * @returns {Object} Returns the cache instance.
  17072. */
  17073. function setCacheAdd(value) {
  17074. this.__data__.set(value, HASH_UNDEFINED$2);
  17075. return this;
  17076. }
  17077. var _setCacheAdd = setCacheAdd;
  17078. /**
  17079. * Checks if `value` is in the array cache.
  17080. *
  17081. * @private
  17082. * @name has
  17083. * @memberOf SetCache
  17084. * @param {*} value The value to search for.
  17085. * @returns {number} Returns `true` if `value` is found, else `false`.
  17086. */
  17087. function setCacheHas(value) {
  17088. return this.__data__.has(value);
  17089. }
  17090. var _setCacheHas = setCacheHas;
  17091. /**
  17092. *
  17093. * Creates an array cache object to store unique values.
  17094. *
  17095. * @private
  17096. * @constructor
  17097. * @param {Array} [values] The values to cache.
  17098. */
  17099. function SetCache(values) {
  17100. var index = -1,
  17101. length = values == null ? 0 : values.length;
  17102. this.__data__ = new _MapCache;
  17103. while (++index < length) {
  17104. this.add(values[index]);
  17105. }
  17106. }
  17107. // Add methods to `SetCache`.
  17108. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  17109. SetCache.prototype.has = _setCacheHas;
  17110. var _SetCache = SetCache;
  17111. /**
  17112. * A specialized version of `_.some` for arrays without support for iteratee
  17113. * shorthands.
  17114. *
  17115. * @private
  17116. * @param {Array} [array] The array to iterate over.
  17117. * @param {Function} predicate The function invoked per iteration.
  17118. * @returns {boolean} Returns `true` if any element passes the predicate check,
  17119. * else `false`.
  17120. */
  17121. function arraySome(array, predicate) {
  17122. var index = -1,
  17123. length = array == null ? 0 : array.length;
  17124. while (++index < length) {
  17125. if (predicate(array[index], index, array)) {
  17126. return true;
  17127. }
  17128. }
  17129. return false;
  17130. }
  17131. var _arraySome = arraySome;
  17132. /**
  17133. * Checks if a `cache` value for `key` exists.
  17134. *
  17135. * @private
  17136. * @param {Object} cache The cache to query.
  17137. * @param {string} key The key of the entry to check.
  17138. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  17139. */
  17140. function cacheHas(cache, key) {
  17141. return cache.has(key);
  17142. }
  17143. var _cacheHas = cacheHas;
  17144. /** Used to compose bitmasks for value comparisons. */
  17145. var COMPARE_PARTIAL_FLAG = 1,
  17146. COMPARE_UNORDERED_FLAG = 2;
  17147. /**
  17148. * A specialized version of `baseIsEqualDeep` for arrays with support for
  17149. * partial deep comparisons.
  17150. *
  17151. * @private
  17152. * @param {Array} array The array to compare.
  17153. * @param {Array} other The other array to compare.
  17154. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  17155. * @param {Function} customizer The function to customize comparisons.
  17156. * @param {Function} equalFunc The function to determine equivalents of values.
  17157. * @param {Object} stack Tracks traversed `array` and `other` objects.
  17158. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  17159. */
  17160. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  17161. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  17162. arrLength = array.length,
  17163. othLength = other.length;
  17164. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  17165. return false;
  17166. }
  17167. // Check that cyclic values are equal.
  17168. var arrStacked = stack.get(array);
  17169. var othStacked = stack.get(other);
  17170. if (arrStacked && othStacked) {
  17171. return arrStacked == other && othStacked == array;
  17172. }
  17173. var index = -1,
  17174. result = true,
  17175. seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;
  17176. stack.set(array, other);
  17177. stack.set(other, array);
  17178. // Ignore non-index properties.
  17179. while (++index < arrLength) {
  17180. var arrValue = array[index],
  17181. othValue = other[index];
  17182. if (customizer) {
  17183. var compared = isPartial
  17184. ? customizer(othValue, arrValue, index, other, array, stack)
  17185. : customizer(arrValue, othValue, index, array, other, stack);
  17186. }
  17187. if (compared !== undefined) {
  17188. if (compared) {
  17189. continue;
  17190. }
  17191. result = false;
  17192. break;
  17193. }
  17194. // Recursively compare arrays (susceptible to call stack limits).
  17195. if (seen) {
  17196. if (!_arraySome(other, function(othValue, othIndex) {
  17197. if (!_cacheHas(seen, othIndex) &&
  17198. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  17199. return seen.push(othIndex);
  17200. }
  17201. })) {
  17202. result = false;
  17203. break;
  17204. }
  17205. } else if (!(
  17206. arrValue === othValue ||
  17207. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  17208. )) {
  17209. result = false;
  17210. break;
  17211. }
  17212. }
  17213. stack['delete'](array);
  17214. stack['delete'](other);
  17215. return result;
  17216. }
  17217. var _equalArrays = equalArrays;
  17218. /** Built-in value references. */
  17219. var Uint8Array$1 = _root.Uint8Array;
  17220. var _Uint8Array = Uint8Array$1;
  17221. /**
  17222. * Converts `map` to its key-value pairs.
  17223. *
  17224. * @private
  17225. * @param {Object} map The map to convert.
  17226. * @returns {Array} Returns the key-value pairs.
  17227. */
  17228. function mapToArray(map) {
  17229. var index = -1,
  17230. result = Array(map.size);
  17231. map.forEach(function(value, key) {
  17232. result[++index] = [key, value];
  17233. });
  17234. return result;
  17235. }
  17236. var _mapToArray = mapToArray;
  17237. /**
  17238. * Converts `set` to an array of its values.
  17239. *
  17240. * @private
  17241. * @param {Object} set The set to convert.
  17242. * @returns {Array} Returns the values.
  17243. */
  17244. function setToArray(set) {
  17245. var index = -1,
  17246. result = Array(set.size);
  17247. set.forEach(function(value) {
  17248. result[++index] = value;
  17249. });
  17250. return result;
  17251. }
  17252. var _setToArray = setToArray;
  17253. /** Used to compose bitmasks for value comparisons. */
  17254. var COMPARE_PARTIAL_FLAG$1 = 1,
  17255. COMPARE_UNORDERED_FLAG$1 = 2;
  17256. /** `Object#toString` result references. */
  17257. var boolTag$1 = '[object Boolean]',
  17258. dateTag$1 = '[object Date]',
  17259. errorTag$1 = '[object Error]',
  17260. mapTag$1 = '[object Map]',
  17261. numberTag$1 = '[object Number]',
  17262. regexpTag$1 = '[object RegExp]',
  17263. setTag$1 = '[object Set]',
  17264. stringTag$1 = '[object String]',
  17265. symbolTag = '[object Symbol]';
  17266. var arrayBufferTag$1 = '[object ArrayBuffer]',
  17267. dataViewTag$1 = '[object DataView]';
  17268. /** Used to convert symbols to primitives and strings. */
  17269. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  17270. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  17271. /**
  17272. * A specialized version of `baseIsEqualDeep` for comparing objects of
  17273. * the same `toStringTag`.
  17274. *
  17275. * **Note:** This function only supports comparing values with tags of
  17276. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  17277. *
  17278. * @private
  17279. * @param {Object} object The object to compare.
  17280. * @param {Object} other The other object to compare.
  17281. * @param {string} tag The `toStringTag` of the objects to compare.
  17282. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  17283. * @param {Function} customizer The function to customize comparisons.
  17284. * @param {Function} equalFunc The function to determine equivalents of values.
  17285. * @param {Object} stack Tracks traversed `object` and `other` objects.
  17286. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  17287. */
  17288. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  17289. switch (tag) {
  17290. case dataViewTag$1:
  17291. if ((object.byteLength != other.byteLength) ||
  17292. (object.byteOffset != other.byteOffset)) {
  17293. return false;
  17294. }
  17295. object = object.buffer;
  17296. other = other.buffer;
  17297. case arrayBufferTag$1:
  17298. if ((object.byteLength != other.byteLength) ||
  17299. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  17300. return false;
  17301. }
  17302. return true;
  17303. case boolTag$1:
  17304. case dateTag$1:
  17305. case numberTag$1:
  17306. // Coerce booleans to `1` or `0` and dates to milliseconds.
  17307. // Invalid dates are coerced to `NaN`.
  17308. return eq_1(+object, +other);
  17309. case errorTag$1:
  17310. return object.name == other.name && object.message == other.message;
  17311. case regexpTag$1:
  17312. case stringTag$1:
  17313. // Coerce regexes to strings and treat strings, primitives and objects,
  17314. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  17315. // for more details.
  17316. return object == (other + '');
  17317. case mapTag$1:
  17318. var convert = _mapToArray;
  17319. case setTag$1:
  17320. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
  17321. convert || (convert = _setToArray);
  17322. if (object.size != other.size && !isPartial) {
  17323. return false;
  17324. }
  17325. // Assume cyclic values are equal.
  17326. var stacked = stack.get(object);
  17327. if (stacked) {
  17328. return stacked == other;
  17329. }
  17330. bitmask |= COMPARE_UNORDERED_FLAG$1;
  17331. // Recursively compare objects (susceptible to call stack limits).
  17332. stack.set(object, other);
  17333. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  17334. stack['delete'](object);
  17335. return result;
  17336. case symbolTag:
  17337. if (symbolValueOf) {
  17338. return symbolValueOf.call(object) == symbolValueOf.call(other);
  17339. }
  17340. }
  17341. return false;
  17342. }
  17343. var _equalByTag = equalByTag;
  17344. /**
  17345. * Appends the elements of `values` to `array`.
  17346. *
  17347. * @private
  17348. * @param {Array} array The array to modify.
  17349. * @param {Array} values The values to append.
  17350. * @returns {Array} Returns `array`.
  17351. */
  17352. function arrayPush(array, values) {
  17353. var index = -1,
  17354. length = values.length,
  17355. offset = array.length;
  17356. while (++index < length) {
  17357. array[offset + index] = values[index];
  17358. }
  17359. return array;
  17360. }
  17361. var _arrayPush = arrayPush;
  17362. /**
  17363. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  17364. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  17365. * symbols of `object`.
  17366. *
  17367. * @private
  17368. * @param {Object} object The object to query.
  17369. * @param {Function} keysFunc The function to get the keys of `object`.
  17370. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  17371. * @returns {Array} Returns the array of property names and symbols.
  17372. */
  17373. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  17374. var result = keysFunc(object);
  17375. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  17376. }
  17377. var _baseGetAllKeys = baseGetAllKeys;
  17378. /**
  17379. * A specialized version of `_.filter` for arrays without support for
  17380. * iteratee shorthands.
  17381. *
  17382. * @private
  17383. * @param {Array} [array] The array to iterate over.
  17384. * @param {Function} predicate The function invoked per iteration.
  17385. * @returns {Array} Returns the new filtered array.
  17386. */
  17387. function arrayFilter(array, predicate) {
  17388. var index = -1,
  17389. length = array == null ? 0 : array.length,
  17390. resIndex = 0,
  17391. result = [];
  17392. while (++index < length) {
  17393. var value = array[index];
  17394. if (predicate(value, index, array)) {
  17395. result[resIndex++] = value;
  17396. }
  17397. }
  17398. return result;
  17399. }
  17400. var _arrayFilter = arrayFilter;
  17401. /**
  17402. * This method returns a new empty array.
  17403. *
  17404. * @static
  17405. * @memberOf _
  17406. * @since 4.13.0
  17407. * @category Util
  17408. * @returns {Array} Returns the new empty array.
  17409. * @example
  17410. *
  17411. * var arrays = _.times(2, _.stubArray);
  17412. *
  17413. * console.log(arrays);
  17414. * // => [[], []]
  17415. *
  17416. * console.log(arrays[0] === arrays[1]);
  17417. * // => false
  17418. */
  17419. function stubArray() {
  17420. return [];
  17421. }
  17422. var stubArray_1 = stubArray;
  17423. /** Used for built-in method references. */
  17424. var objectProto$a = Object.prototype;
  17425. /** Built-in value references. */
  17426. var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
  17427. /* Built-in method references for those with the same name as other `lodash` methods. */
  17428. var nativeGetSymbols = Object.getOwnPropertySymbols;
  17429. /**
  17430. * Creates an array of the own enumerable symbols of `object`.
  17431. *
  17432. * @private
  17433. * @param {Object} object The object to query.
  17434. * @returns {Array} Returns the array of symbols.
  17435. */
  17436. var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
  17437. if (object == null) {
  17438. return [];
  17439. }
  17440. object = Object(object);
  17441. return _arrayFilter(nativeGetSymbols(object), function(symbol) {
  17442. return propertyIsEnumerable$1.call(object, symbol);
  17443. });
  17444. };
  17445. var _getSymbols = getSymbols;
  17446. /**
  17447. * Creates an array of own enumerable property names and symbols of `object`.
  17448. *
  17449. * @private
  17450. * @param {Object} object The object to query.
  17451. * @returns {Array} Returns the array of property names and symbols.
  17452. */
  17453. function getAllKeys(object) {
  17454. return _baseGetAllKeys(object, keys_1, _getSymbols);
  17455. }
  17456. var _getAllKeys = getAllKeys;
  17457. /** Used to compose bitmasks for value comparisons. */
  17458. var COMPARE_PARTIAL_FLAG$2 = 1;
  17459. /** Used for built-in method references. */
  17460. var objectProto$b = Object.prototype;
  17461. /** Used to check objects for own properties. */
  17462. var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
  17463. /**
  17464. * A specialized version of `baseIsEqualDeep` for objects with support for
  17465. * partial deep comparisons.
  17466. *
  17467. * @private
  17468. * @param {Object} object The object to compare.
  17469. * @param {Object} other The other object to compare.
  17470. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  17471. * @param {Function} customizer The function to customize comparisons.
  17472. * @param {Function} equalFunc The function to determine equivalents of values.
  17473. * @param {Object} stack Tracks traversed `object` and `other` objects.
  17474. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  17475. */
  17476. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  17477. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
  17478. objProps = _getAllKeys(object),
  17479. objLength = objProps.length,
  17480. othProps = _getAllKeys(other),
  17481. othLength = othProps.length;
  17482. if (objLength != othLength && !isPartial) {
  17483. return false;
  17484. }
  17485. var index = objLength;
  17486. while (index--) {
  17487. var key = objProps[index];
  17488. if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
  17489. return false;
  17490. }
  17491. }
  17492. // Check that cyclic values are equal.
  17493. var objStacked = stack.get(object);
  17494. var othStacked = stack.get(other);
  17495. if (objStacked && othStacked) {
  17496. return objStacked == other && othStacked == object;
  17497. }
  17498. var result = true;
  17499. stack.set(object, other);
  17500. stack.set(other, object);
  17501. var skipCtor = isPartial;
  17502. while (++index < objLength) {
  17503. key = objProps[index];
  17504. var objValue = object[key],
  17505. othValue = other[key];
  17506. if (customizer) {
  17507. var compared = isPartial
  17508. ? customizer(othValue, objValue, key, other, object, stack)
  17509. : customizer(objValue, othValue, key, object, other, stack);
  17510. }
  17511. // Recursively compare objects (susceptible to call stack limits).
  17512. if (!(compared === undefined
  17513. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  17514. : compared
  17515. )) {
  17516. result = false;
  17517. break;
  17518. }
  17519. skipCtor || (skipCtor = key == 'constructor');
  17520. }
  17521. if (result && !skipCtor) {
  17522. var objCtor = object.constructor,
  17523. othCtor = other.constructor;
  17524. // Non `Object` object instances with different constructors are not equal.
  17525. if (objCtor != othCtor &&
  17526. ('constructor' in object && 'constructor' in other) &&
  17527. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  17528. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  17529. result = false;
  17530. }
  17531. }
  17532. stack['delete'](object);
  17533. stack['delete'](other);
  17534. return result;
  17535. }
  17536. var _equalObjects = equalObjects;
  17537. /* Built-in method references that are verified to be native. */
  17538. var DataView = _getNative(_root, 'DataView');
  17539. var _DataView = DataView;
  17540. /* Built-in method references that are verified to be native. */
  17541. var Promise$1 = _getNative(_root, 'Promise');
  17542. var _Promise = Promise$1;
  17543. /* Built-in method references that are verified to be native. */
  17544. var Set$1 = _getNative(_root, 'Set');
  17545. var _Set = Set$1;
  17546. /* Built-in method references that are verified to be native. */
  17547. var WeakMap$1 = _getNative(_root, 'WeakMap');
  17548. var _WeakMap = WeakMap$1;
  17549. /** `Object#toString` result references. */
  17550. var mapTag$2 = '[object Map]',
  17551. objectTag$2 = '[object Object]',
  17552. promiseTag = '[object Promise]',
  17553. setTag$2 = '[object Set]',
  17554. weakMapTag$1 = '[object WeakMap]';
  17555. var dataViewTag$2 = '[object DataView]';
  17556. /** Used to detect maps, sets, and weakmaps. */
  17557. var dataViewCtorString = _toSource(_DataView),
  17558. mapCtorString = _toSource(_Map),
  17559. promiseCtorString = _toSource(_Promise),
  17560. setCtorString = _toSource(_Set),
  17561. weakMapCtorString = _toSource(_WeakMap);
  17562. /**
  17563. * Gets the `toStringTag` of `value`.
  17564. *
  17565. * @private
  17566. * @param {*} value The value to query.
  17567. * @returns {string} Returns the `toStringTag`.
  17568. */
  17569. var getTag = _baseGetTag;
  17570. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  17571. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) ||
  17572. (_Map && getTag(new _Map) != mapTag$2) ||
  17573. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  17574. (_Set && getTag(new _Set) != setTag$2) ||
  17575. (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) {
  17576. getTag = function(value) {
  17577. var result = _baseGetTag(value),
  17578. Ctor = result == objectTag$2 ? value.constructor : undefined,
  17579. ctorString = Ctor ? _toSource(Ctor) : '';
  17580. if (ctorString) {
  17581. switch (ctorString) {
  17582. case dataViewCtorString: return dataViewTag$2;
  17583. case mapCtorString: return mapTag$2;
  17584. case promiseCtorString: return promiseTag;
  17585. case setCtorString: return setTag$2;
  17586. case weakMapCtorString: return weakMapTag$1;
  17587. }
  17588. }
  17589. return result;
  17590. };
  17591. }
  17592. var _getTag = getTag;
  17593. /** Used to compose bitmasks for value comparisons. */
  17594. var COMPARE_PARTIAL_FLAG$3 = 1;
  17595. /** `Object#toString` result references. */
  17596. var argsTag$2 = '[object Arguments]',
  17597. arrayTag$1 = '[object Array]',
  17598. objectTag$3 = '[object Object]';
  17599. /** Used for built-in method references. */
  17600. var objectProto$c = Object.prototype;
  17601. /** Used to check objects for own properties. */
  17602. var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
  17603. /**
  17604. * A specialized version of `baseIsEqual` for arrays and objects which performs
  17605. * deep comparisons and tracks traversed objects enabling objects with circular
  17606. * references to be compared.
  17607. *
  17608. * @private
  17609. * @param {Object} object The object to compare.
  17610. * @param {Object} other The other object to compare.
  17611. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  17612. * @param {Function} customizer The function to customize comparisons.
  17613. * @param {Function} equalFunc The function to determine equivalents of values.
  17614. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  17615. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  17616. */
  17617. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  17618. var objIsArr = isArray_1(object),
  17619. othIsArr = isArray_1(other),
  17620. objTag = objIsArr ? arrayTag$1 : _getTag(object),
  17621. othTag = othIsArr ? arrayTag$1 : _getTag(other);
  17622. objTag = objTag == argsTag$2 ? objectTag$3 : objTag;
  17623. othTag = othTag == argsTag$2 ? objectTag$3 : othTag;
  17624. var objIsObj = objTag == objectTag$3,
  17625. othIsObj = othTag == objectTag$3,
  17626. isSameTag = objTag == othTag;
  17627. if (isSameTag && isBuffer_1(object)) {
  17628. if (!isBuffer_1(other)) {
  17629. return false;
  17630. }
  17631. objIsArr = true;
  17632. objIsObj = false;
  17633. }
  17634. if (isSameTag && !objIsObj) {
  17635. stack || (stack = new _Stack);
  17636. return (objIsArr || isTypedArray_1(object))
  17637. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  17638. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  17639. }
  17640. if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
  17641. var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
  17642. othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
  17643. if (objIsWrapped || othIsWrapped) {
  17644. var objUnwrapped = objIsWrapped ? object.value() : object,
  17645. othUnwrapped = othIsWrapped ? other.value() : other;
  17646. stack || (stack = new _Stack);
  17647. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  17648. }
  17649. }
  17650. if (!isSameTag) {
  17651. return false;
  17652. }
  17653. stack || (stack = new _Stack);
  17654. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  17655. }
  17656. var _baseIsEqualDeep = baseIsEqualDeep;
  17657. /**
  17658. * The base implementation of `_.isEqual` which supports partial comparisons
  17659. * and tracks traversed objects.
  17660. *
  17661. * @private
  17662. * @param {*} value The value to compare.
  17663. * @param {*} other The other value to compare.
  17664. * @param {boolean} bitmask The bitmask flags.
  17665. * 1 - Unordered comparison
  17666. * 2 - Partial comparison
  17667. * @param {Function} [customizer] The function to customize comparisons.
  17668. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  17669. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  17670. */
  17671. function baseIsEqual(value, other, bitmask, customizer, stack) {
  17672. if (value === other) {
  17673. return true;
  17674. }
  17675. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  17676. return value !== value && other !== other;
  17677. }
  17678. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  17679. }
  17680. var _baseIsEqual = baseIsEqual;
  17681. /** Used to compose bitmasks for value comparisons. */
  17682. var COMPARE_PARTIAL_FLAG$4 = 1,
  17683. COMPARE_UNORDERED_FLAG$2 = 2;
  17684. /**
  17685. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  17686. *
  17687. * @private
  17688. * @param {Object} object The object to inspect.
  17689. * @param {Object} source The object of property values to match.
  17690. * @param {Array} matchData The property names, values, and compare flags to match.
  17691. * @param {Function} [customizer] The function to customize comparisons.
  17692. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  17693. */
  17694. function baseIsMatch(object, source, matchData, customizer) {
  17695. var index = matchData.length,
  17696. length = index,
  17697. noCustomizer = !customizer;
  17698. if (object == null) {
  17699. return !length;
  17700. }
  17701. object = Object(object);
  17702. while (index--) {
  17703. var data = matchData[index];
  17704. if ((noCustomizer && data[2])
  17705. ? data[1] !== object[data[0]]
  17706. : !(data[0] in object)
  17707. ) {
  17708. return false;
  17709. }
  17710. }
  17711. while (++index < length) {
  17712. data = matchData[index];
  17713. var key = data[0],
  17714. objValue = object[key],
  17715. srcValue = data[1];
  17716. if (noCustomizer && data[2]) {
  17717. if (objValue === undefined && !(key in object)) {
  17718. return false;
  17719. }
  17720. } else {
  17721. var stack = new _Stack;
  17722. if (customizer) {
  17723. var result = customizer(objValue, srcValue, key, object, source, stack);
  17724. }
  17725. if (!(result === undefined
  17726. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)
  17727. : result
  17728. )) {
  17729. return false;
  17730. }
  17731. }
  17732. }
  17733. return true;
  17734. }
  17735. var _baseIsMatch = baseIsMatch;
  17736. /**
  17737. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  17738. *
  17739. * @private
  17740. * @param {*} value The value to check.
  17741. * @returns {boolean} Returns `true` if `value` if suitable for strict
  17742. * equality comparisons, else `false`.
  17743. */
  17744. function isStrictComparable(value) {
  17745. return value === value && !isObject_1$1(value);
  17746. }
  17747. var _isStrictComparable = isStrictComparable;
  17748. /**
  17749. * Gets the property names, values, and compare flags of `object`.
  17750. *
  17751. * @private
  17752. * @param {Object} object The object to query.
  17753. * @returns {Array} Returns the match data of `object`.
  17754. */
  17755. function getMatchData(object) {
  17756. var result = keys_1(object),
  17757. length = result.length;
  17758. while (length--) {
  17759. var key = result[length],
  17760. value = object[key];
  17761. result[length] = [key, value, _isStrictComparable(value)];
  17762. }
  17763. return result;
  17764. }
  17765. var _getMatchData = getMatchData;
  17766. /**
  17767. * A specialized version of `matchesProperty` for source values suitable
  17768. * for strict equality comparisons, i.e. `===`.
  17769. *
  17770. * @private
  17771. * @param {string} key The key of the property to get.
  17772. * @param {*} srcValue The value to match.
  17773. * @returns {Function} Returns the new spec function.
  17774. */
  17775. function matchesStrictComparable(key, srcValue) {
  17776. return function(object) {
  17777. if (object == null) {
  17778. return false;
  17779. }
  17780. return object[key] === srcValue &&
  17781. (srcValue !== undefined || (key in Object(object)));
  17782. };
  17783. }
  17784. var _matchesStrictComparable = matchesStrictComparable;
  17785. /**
  17786. * The base implementation of `_.matches` which doesn't clone `source`.
  17787. *
  17788. * @private
  17789. * @param {Object} source The object of property values to match.
  17790. * @returns {Function} Returns the new spec function.
  17791. */
  17792. function baseMatches(source) {
  17793. var matchData = _getMatchData(source);
  17794. if (matchData.length == 1 && matchData[0][2]) {
  17795. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  17796. }
  17797. return function(object) {
  17798. return object === source || _baseIsMatch(object, source, matchData);
  17799. };
  17800. }
  17801. var _baseMatches = baseMatches;
  17802. /** `Object#toString` result references. */
  17803. var symbolTag$1 = '[object Symbol]';
  17804. /**
  17805. * Checks if `value` is classified as a `Symbol` primitive or object.
  17806. *
  17807. * @static
  17808. * @memberOf _
  17809. * @since 4.0.0
  17810. * @category Lang
  17811. * @param {*} value The value to check.
  17812. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  17813. * @example
  17814. *
  17815. * _.isSymbol(Symbol.iterator);
  17816. * // => true
  17817. *
  17818. * _.isSymbol('abc');
  17819. * // => false
  17820. */
  17821. function isSymbol(value) {
  17822. return typeof value == 'symbol' ||
  17823. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1);
  17824. }
  17825. var isSymbol_1 = isSymbol;
  17826. /** Used to match property names within property paths. */
  17827. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  17828. reIsPlainProp = /^\w*$/;
  17829. /**
  17830. * Checks if `value` is a property name and not a property path.
  17831. *
  17832. * @private
  17833. * @param {*} value The value to check.
  17834. * @param {Object} [object] The object to query keys on.
  17835. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  17836. */
  17837. function isKey(value, object) {
  17838. if (isArray_1(value)) {
  17839. return false;
  17840. }
  17841. var type = typeof value;
  17842. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  17843. value == null || isSymbol_1(value)) {
  17844. return true;
  17845. }
  17846. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  17847. (object != null && value in Object(object));
  17848. }
  17849. var _isKey = isKey;
  17850. /** Error message constants. */
  17851. var FUNC_ERROR_TEXT = 'Expected a function';
  17852. /**
  17853. * Creates a function that memoizes the result of `func`. If `resolver` is
  17854. * provided, it determines the cache key for storing the result based on the
  17855. * arguments provided to the memoized function. By default, the first argument
  17856. * provided to the memoized function is used as the map cache key. The `func`
  17857. * is invoked with the `this` binding of the memoized function.
  17858. *
  17859. * **Note:** The cache is exposed as the `cache` property on the memoized
  17860. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  17861. * constructor with one whose instances implement the
  17862. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  17863. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  17864. *
  17865. * @static
  17866. * @memberOf _
  17867. * @since 0.1.0
  17868. * @category Function
  17869. * @param {Function} func The function to have its output memoized.
  17870. * @param {Function} [resolver] The function to resolve the cache key.
  17871. * @returns {Function} Returns the new memoized function.
  17872. * @example
  17873. *
  17874. * var object = { 'a': 1, 'b': 2 };
  17875. * var other = { 'c': 3, 'd': 4 };
  17876. *
  17877. * var values = _.memoize(_.values);
  17878. * values(object);
  17879. * // => [1, 2]
  17880. *
  17881. * values(other);
  17882. * // => [3, 4]
  17883. *
  17884. * object.a = 2;
  17885. * values(object);
  17886. * // => [1, 2]
  17887. *
  17888. * // Modify the result cache.
  17889. * values.cache.set(object, ['a', 'b']);
  17890. * values(object);
  17891. * // => ['a', 'b']
  17892. *
  17893. * // Replace `_.memoize.Cache`.
  17894. * _.memoize.Cache = WeakMap;
  17895. */
  17896. function memoize(func, resolver) {
  17897. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  17898. throw new TypeError(FUNC_ERROR_TEXT);
  17899. }
  17900. var memoized = function() {
  17901. var args = arguments,
  17902. key = resolver ? resolver.apply(this, args) : args[0],
  17903. cache = memoized.cache;
  17904. if (cache.has(key)) {
  17905. return cache.get(key);
  17906. }
  17907. var result = func.apply(this, args);
  17908. memoized.cache = cache.set(key, result) || cache;
  17909. return result;
  17910. };
  17911. memoized.cache = new (memoize.Cache || _MapCache);
  17912. return memoized;
  17913. }
  17914. // Expose `MapCache`.
  17915. memoize.Cache = _MapCache;
  17916. var memoize_1 = memoize;
  17917. /** Used as the maximum memoize cache size. */
  17918. var MAX_MEMOIZE_SIZE = 500;
  17919. /**
  17920. * A specialized version of `_.memoize` which clears the memoized function's
  17921. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  17922. *
  17923. * @private
  17924. * @param {Function} func The function to have its output memoized.
  17925. * @returns {Function} Returns the new memoized function.
  17926. */
  17927. function memoizeCapped(func) {
  17928. var result = memoize_1(func, function(key) {
  17929. if (cache.size === MAX_MEMOIZE_SIZE) {
  17930. cache.clear();
  17931. }
  17932. return key;
  17933. });
  17934. var cache = result.cache;
  17935. return result;
  17936. }
  17937. var _memoizeCapped = memoizeCapped;
  17938. /** Used to match property names within property paths. */
  17939. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  17940. /** Used to match backslashes in property paths. */
  17941. var reEscapeChar = /\\(\\)?/g;
  17942. /**
  17943. * Converts `string` to a property path array.
  17944. *
  17945. * @private
  17946. * @param {string} string The string to convert.
  17947. * @returns {Array} Returns the property path array.
  17948. */
  17949. var stringToPath = _memoizeCapped(function(string) {
  17950. var result = [];
  17951. if (string.charCodeAt(0) === 46 /* . */) {
  17952. result.push('');
  17953. }
  17954. string.replace(rePropName, function(match, number, quote, subString) {
  17955. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  17956. });
  17957. return result;
  17958. });
  17959. var _stringToPath = stringToPath;
  17960. /** Used as references for various `Number` constants. */
  17961. var INFINITY = 1 / 0;
  17962. /** Used to convert symbols to primitives and strings. */
  17963. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  17964. symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
  17965. /**
  17966. * The base implementation of `_.toString` which doesn't convert nullish
  17967. * values to empty strings.
  17968. *
  17969. * @private
  17970. * @param {*} value The value to process.
  17971. * @returns {string} Returns the string.
  17972. */
  17973. function baseToString(value) {
  17974. // Exit early for strings to avoid a performance hit in some environments.
  17975. if (typeof value == 'string') {
  17976. return value;
  17977. }
  17978. if (isArray_1(value)) {
  17979. // Recursively convert values (susceptible to call stack limits).
  17980. return _arrayMap(value, baseToString) + '';
  17981. }
  17982. if (isSymbol_1(value)) {
  17983. return symbolToString ? symbolToString.call(value) : '';
  17984. }
  17985. var result = (value + '');
  17986. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  17987. }
  17988. var _baseToString = baseToString;
  17989. /**
  17990. * Converts `value` to a string. An empty string is returned for `null`
  17991. * and `undefined` values. The sign of `-0` is preserved.
  17992. *
  17993. * @static
  17994. * @memberOf _
  17995. * @since 4.0.0
  17996. * @category Lang
  17997. * @param {*} value The value to convert.
  17998. * @returns {string} Returns the converted string.
  17999. * @example
  18000. *
  18001. * _.toString(null);
  18002. * // => ''
  18003. *
  18004. * _.toString(-0);
  18005. * // => '-0'
  18006. *
  18007. * _.toString([1, 2, 3]);
  18008. * // => '1,2,3'
  18009. */
  18010. function toString(value) {
  18011. return value == null ? '' : _baseToString(value);
  18012. }
  18013. var toString_1 = toString;
  18014. /**
  18015. * Casts `value` to a path array if it's not one.
  18016. *
  18017. * @private
  18018. * @param {*} value The value to inspect.
  18019. * @param {Object} [object] The object to query keys on.
  18020. * @returns {Array} Returns the cast property path array.
  18021. */
  18022. function castPath(value, object) {
  18023. if (isArray_1(value)) {
  18024. return value;
  18025. }
  18026. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  18027. }
  18028. var _castPath = castPath;
  18029. /** Used as references for various `Number` constants. */
  18030. var INFINITY$1 = 1 / 0;
  18031. /**
  18032. * Converts `value` to a string key if it's not a string or symbol.
  18033. *
  18034. * @private
  18035. * @param {*} value The value to inspect.
  18036. * @returns {string|symbol} Returns the key.
  18037. */
  18038. function toKey(value) {
  18039. if (typeof value == 'string' || isSymbol_1(value)) {
  18040. return value;
  18041. }
  18042. var result = (value + '');
  18043. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  18044. }
  18045. var _toKey = toKey;
  18046. /**
  18047. * The base implementation of `_.get` without support for default values.
  18048. *
  18049. * @private
  18050. * @param {Object} object The object to query.
  18051. * @param {Array|string} path The path of the property to get.
  18052. * @returns {*} Returns the resolved value.
  18053. */
  18054. function baseGet(object, path) {
  18055. path = _castPath(path, object);
  18056. var index = 0,
  18057. length = path.length;
  18058. while (object != null && index < length) {
  18059. object = object[_toKey(path[index++])];
  18060. }
  18061. return (index && index == length) ? object : undefined;
  18062. }
  18063. var _baseGet = baseGet;
  18064. /**
  18065. * Gets the value at `path` of `object`. If the resolved value is
  18066. * `undefined`, the `defaultValue` is returned in its place.
  18067. *
  18068. * @static
  18069. * @memberOf _
  18070. * @since 3.7.0
  18071. * @category Object
  18072. * @param {Object} object The object to query.
  18073. * @param {Array|string} path The path of the property to get.
  18074. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  18075. * @returns {*} Returns the resolved value.
  18076. * @example
  18077. *
  18078. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  18079. *
  18080. * _.get(object, 'a[0].b.c');
  18081. * // => 3
  18082. *
  18083. * _.get(object, ['a', '0', 'b', 'c']);
  18084. * // => 3
  18085. *
  18086. * _.get(object, 'a.b.c', 'default');
  18087. * // => 'default'
  18088. */
  18089. function get(object, path, defaultValue) {
  18090. var result = object == null ? undefined : _baseGet(object, path);
  18091. return result === undefined ? defaultValue : result;
  18092. }
  18093. var get_1 = get;
  18094. /**
  18095. * The base implementation of `_.hasIn` without support for deep paths.
  18096. *
  18097. * @private
  18098. * @param {Object} [object] The object to query.
  18099. * @param {Array|string} key The key to check.
  18100. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  18101. */
  18102. function baseHasIn(object, key) {
  18103. return object != null && key in Object(object);
  18104. }
  18105. var _baseHasIn = baseHasIn;
  18106. /**
  18107. * Checks if `path` exists on `object`.
  18108. *
  18109. * @private
  18110. * @param {Object} object The object to query.
  18111. * @param {Array|string} path The path to check.
  18112. * @param {Function} hasFunc The function to check properties.
  18113. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  18114. */
  18115. function hasPath(object, path, hasFunc) {
  18116. path = _castPath(path, object);
  18117. var index = -1,
  18118. length = path.length,
  18119. result = false;
  18120. while (++index < length) {
  18121. var key = _toKey(path[index]);
  18122. if (!(result = object != null && hasFunc(object, key))) {
  18123. break;
  18124. }
  18125. object = object[key];
  18126. }
  18127. if (result || ++index != length) {
  18128. return result;
  18129. }
  18130. length = object == null ? 0 : object.length;
  18131. return !!length && isLength_1(length) && _isIndex(key, length) &&
  18132. (isArray_1(object) || isArguments_1(object));
  18133. }
  18134. var _hasPath = hasPath;
  18135. /**
  18136. * Checks if `path` is a direct or inherited property of `object`.
  18137. *
  18138. * @static
  18139. * @memberOf _
  18140. * @since 4.0.0
  18141. * @category Object
  18142. * @param {Object} object The object to query.
  18143. * @param {Array|string} path The path to check.
  18144. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  18145. * @example
  18146. *
  18147. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  18148. *
  18149. * _.hasIn(object, 'a');
  18150. * // => true
  18151. *
  18152. * _.hasIn(object, 'a.b');
  18153. * // => true
  18154. *
  18155. * _.hasIn(object, ['a', 'b']);
  18156. * // => true
  18157. *
  18158. * _.hasIn(object, 'b');
  18159. * // => false
  18160. */
  18161. function hasIn(object, path) {
  18162. return object != null && _hasPath(object, path, _baseHasIn);
  18163. }
  18164. var hasIn_1 = hasIn;
  18165. /** Used to compose bitmasks for value comparisons. */
  18166. var COMPARE_PARTIAL_FLAG$5 = 1,
  18167. COMPARE_UNORDERED_FLAG$3 = 2;
  18168. /**
  18169. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  18170. *
  18171. * @private
  18172. * @param {string} path The path of the property to get.
  18173. * @param {*} srcValue The value to match.
  18174. * @returns {Function} Returns the new spec function.
  18175. */
  18176. function baseMatchesProperty(path, srcValue) {
  18177. if (_isKey(path) && _isStrictComparable(srcValue)) {
  18178. return _matchesStrictComparable(_toKey(path), srcValue);
  18179. }
  18180. return function(object) {
  18181. var objValue = get_1(object, path);
  18182. return (objValue === undefined && objValue === srcValue)
  18183. ? hasIn_1(object, path)
  18184. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
  18185. };
  18186. }
  18187. var _baseMatchesProperty = baseMatchesProperty;
  18188. /**
  18189. * This method returns the first argument it receives.
  18190. *
  18191. * @static
  18192. * @since 0.1.0
  18193. * @memberOf _
  18194. * @category Util
  18195. * @param {*} value Any value.
  18196. * @returns {*} Returns `value`.
  18197. * @example
  18198. *
  18199. * var object = { 'a': 1 };
  18200. *
  18201. * console.log(_.identity(object) === object);
  18202. * // => true
  18203. */
  18204. function identity(value) {
  18205. return value;
  18206. }
  18207. var identity_1 = identity;
  18208. /**
  18209. * The base implementation of `_.property` without support for deep paths.
  18210. *
  18211. * @private
  18212. * @param {string} key The key of the property to get.
  18213. * @returns {Function} Returns the new accessor function.
  18214. */
  18215. function baseProperty(key) {
  18216. return function(object) {
  18217. return object == null ? undefined : object[key];
  18218. };
  18219. }
  18220. var _baseProperty = baseProperty;
  18221. /**
  18222. * A specialized version of `baseProperty` which supports deep paths.
  18223. *
  18224. * @private
  18225. * @param {Array|string} path The path of the property to get.
  18226. * @returns {Function} Returns the new accessor function.
  18227. */
  18228. function basePropertyDeep(path) {
  18229. return function(object) {
  18230. return _baseGet(object, path);
  18231. };
  18232. }
  18233. var _basePropertyDeep = basePropertyDeep;
  18234. /**
  18235. * Creates a function that returns the value at `path` of a given object.
  18236. *
  18237. * @static
  18238. * @memberOf _
  18239. * @since 2.4.0
  18240. * @category Util
  18241. * @param {Array|string} path The path of the property to get.
  18242. * @returns {Function} Returns the new accessor function.
  18243. * @example
  18244. *
  18245. * var objects = [
  18246. * { 'a': { 'b': 2 } },
  18247. * { 'a': { 'b': 1 } }
  18248. * ];
  18249. *
  18250. * _.map(objects, _.property('a.b'));
  18251. * // => [2, 1]
  18252. *
  18253. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  18254. * // => [1, 2]
  18255. */
  18256. function property(path) {
  18257. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  18258. }
  18259. var property_1 = property;
  18260. /**
  18261. * The base implementation of `_.iteratee`.
  18262. *
  18263. * @private
  18264. * @param {*} [value=_.identity] The value to convert to an iteratee.
  18265. * @returns {Function} Returns the iteratee.
  18266. */
  18267. function baseIteratee(value) {
  18268. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  18269. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  18270. if (typeof value == 'function') {
  18271. return value;
  18272. }
  18273. if (value == null) {
  18274. return identity_1;
  18275. }
  18276. if (typeof value == 'object') {
  18277. return isArray_1(value)
  18278. ? _baseMatchesProperty(value[0], value[1])
  18279. : _baseMatches(value);
  18280. }
  18281. return property_1(value);
  18282. }
  18283. var _baseIteratee = baseIteratee;
  18284. /**
  18285. * Gets the last element of `array`.
  18286. *
  18287. * @static
  18288. * @memberOf _
  18289. * @since 0.1.0
  18290. * @category Array
  18291. * @param {Array} array The array to query.
  18292. * @returns {*} Returns the last element of `array`.
  18293. * @example
  18294. *
  18295. * _.last([1, 2, 3]);
  18296. * // => 3
  18297. */
  18298. function last(array) {
  18299. var length = array == null ? 0 : array.length;
  18300. return length ? array[length - 1] : undefined;
  18301. }
  18302. var last_1 = last;
  18303. /**
  18304. * The base implementation of `_.slice` without an iteratee call guard.
  18305. *
  18306. * @private
  18307. * @param {Array} array The array to slice.
  18308. * @param {number} [start=0] The start position.
  18309. * @param {number} [end=array.length] The end position.
  18310. * @returns {Array} Returns the slice of `array`.
  18311. */
  18312. function baseSlice(array, start, end) {
  18313. var index = -1,
  18314. length = array.length;
  18315. if (start < 0) {
  18316. start = -start > length ? 0 : (length + start);
  18317. }
  18318. end = end > length ? length : end;
  18319. if (end < 0) {
  18320. end += length;
  18321. }
  18322. length = start > end ? 0 : ((end - start) >>> 0);
  18323. start >>>= 0;
  18324. var result = Array(length);
  18325. while (++index < length) {
  18326. result[index] = array[index + start];
  18327. }
  18328. return result;
  18329. }
  18330. var _baseSlice = baseSlice;
  18331. /**
  18332. * Gets the parent value at `path` of `object`.
  18333. *
  18334. * @private
  18335. * @param {Object} object The object to query.
  18336. * @param {Array} path The path to get the parent value of.
  18337. * @returns {*} Returns the parent value.
  18338. */
  18339. function parent(object, path) {
  18340. return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
  18341. }
  18342. var _parent = parent;
  18343. /**
  18344. * The base implementation of `_.unset`.
  18345. *
  18346. * @private
  18347. * @param {Object} object The object to modify.
  18348. * @param {Array|string} path The property path to unset.
  18349. * @returns {boolean} Returns `true` if the property is deleted, else `false`.
  18350. */
  18351. function baseUnset(object, path) {
  18352. path = _castPath(path, object);
  18353. object = _parent(object, path);
  18354. return object == null || delete object[_toKey(last_1(path))];
  18355. }
  18356. var _baseUnset = baseUnset;
  18357. /** Used for built-in method references. */
  18358. var arrayProto$1 = Array.prototype;
  18359. /** Built-in value references. */
  18360. var splice$1 = arrayProto$1.splice;
  18361. /**
  18362. * The base implementation of `_.pullAt` without support for individual
  18363. * indexes or capturing the removed elements.
  18364. *
  18365. * @private
  18366. * @param {Array} array The array to modify.
  18367. * @param {number[]} indexes The indexes of elements to remove.
  18368. * @returns {Array} Returns `array`.
  18369. */
  18370. function basePullAt(array, indexes) {
  18371. var length = array ? indexes.length : 0,
  18372. lastIndex = length - 1;
  18373. while (length--) {
  18374. var index = indexes[length];
  18375. if (length == lastIndex || index !== previous) {
  18376. var previous = index;
  18377. if (_isIndex(index)) {
  18378. splice$1.call(array, index, 1);
  18379. } else {
  18380. _baseUnset(array, index);
  18381. }
  18382. }
  18383. }
  18384. return array;
  18385. }
  18386. var _basePullAt = basePullAt;
  18387. /**
  18388. * Removes all elements from `array` that `predicate` returns truthy for
  18389. * and returns an array of the removed elements. The predicate is invoked
  18390. * with three arguments: (value, index, array).
  18391. *
  18392. * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
  18393. * to pull elements from an array by value.
  18394. *
  18395. * @static
  18396. * @memberOf _
  18397. * @since 2.0.0
  18398. * @category Array
  18399. * @param {Array} array The array to modify.
  18400. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  18401. * @returns {Array} Returns the new array of removed elements.
  18402. * @example
  18403. *
  18404. * var array = [1, 2, 3, 4];
  18405. * var evens = _.remove(array, function(n) {
  18406. * return n % 2 == 0;
  18407. * });
  18408. *
  18409. * console.log(array);
  18410. * // => [1, 3]
  18411. *
  18412. * console.log(evens);
  18413. * // => [2, 4]
  18414. */
  18415. function remove(array, predicate) {
  18416. var result = [];
  18417. if (!(array && array.length)) {
  18418. return result;
  18419. }
  18420. var index = -1,
  18421. indexes = [],
  18422. length = array.length;
  18423. predicate = _baseIteratee(predicate);
  18424. while (++index < length) {
  18425. var value = array[index];
  18426. if (predicate(value, index, array)) {
  18427. result.push(value);
  18428. indexes.push(index);
  18429. }
  18430. }
  18431. _basePullAt(array, indexes);
  18432. return result;
  18433. }
  18434. var remove_1 = remove;
  18435. /** `Object#toString` result references. */
  18436. var mapTag$3 = '[object Map]',
  18437. setTag$3 = '[object Set]';
  18438. /** Used for built-in method references. */
  18439. var objectProto$d = Object.prototype;
  18440. /** Used to check objects for own properties. */
  18441. var hasOwnProperty$a = objectProto$d.hasOwnProperty;
  18442. /**
  18443. * Checks if `value` is an empty object, collection, map, or set.
  18444. *
  18445. * Objects are considered empty if they have no own enumerable string keyed
  18446. * properties.
  18447. *
  18448. * Array-like values such as `arguments` objects, arrays, buffers, strings, or
  18449. * jQuery-like collections are considered empty if they have a `length` of `0`.
  18450. * Similarly, maps and sets are considered empty if they have a `size` of `0`.
  18451. *
  18452. * @static
  18453. * @memberOf _
  18454. * @since 0.1.0
  18455. * @category Lang
  18456. * @param {*} value The value to check.
  18457. * @returns {boolean} Returns `true` if `value` is empty, else `false`.
  18458. * @example
  18459. *
  18460. * _.isEmpty(null);
  18461. * // => true
  18462. *
  18463. * _.isEmpty(true);
  18464. * // => true
  18465. *
  18466. * _.isEmpty(1);
  18467. * // => true
  18468. *
  18469. * _.isEmpty([1, 2, 3]);
  18470. * // => false
  18471. *
  18472. * _.isEmpty({ 'a': 1 });
  18473. * // => false
  18474. */
  18475. function isEmpty(value) {
  18476. if (value == null) {
  18477. return true;
  18478. }
  18479. if (isArrayLike_1(value) &&
  18480. (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' ||
  18481. isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
  18482. return !value.length;
  18483. }
  18484. var tag = _getTag(value);
  18485. if (tag == mapTag$3 || tag == setTag$3) {
  18486. return !value.size;
  18487. }
  18488. if (_isPrototype(value)) {
  18489. return !_baseKeys(value).length;
  18490. }
  18491. for (var key in value) {
  18492. if (hasOwnProperty$a.call(value, key)) {
  18493. return false;
  18494. }
  18495. }
  18496. return true;
  18497. }
  18498. var isEmpty_1 = isEmpty;
  18499. /**
  18500. * A specialized version of `_.forEach` for arrays without support for
  18501. * iteratee shorthands.
  18502. *
  18503. * @private
  18504. * @param {Array} [array] The array to iterate over.
  18505. * @param {Function} iteratee The function invoked per iteration.
  18506. * @returns {Array} Returns `array`.
  18507. */
  18508. function arrayEach(array, iteratee) {
  18509. var index = -1,
  18510. length = array == null ? 0 : array.length;
  18511. while (++index < length) {
  18512. if (iteratee(array[index], index, array) === false) {
  18513. break;
  18514. }
  18515. }
  18516. return array;
  18517. }
  18518. var _arrayEach = arrayEach;
  18519. var defineProperty$1 = (function() {
  18520. try {
  18521. var func = _getNative(Object, 'defineProperty');
  18522. func({}, '', {});
  18523. return func;
  18524. } catch (e) {}
  18525. }());
  18526. var _defineProperty$1 = defineProperty$1;
  18527. /**
  18528. * The base implementation of `assignValue` and `assignMergeValue` without
  18529. * value checks.
  18530. *
  18531. * @private
  18532. * @param {Object} object The object to modify.
  18533. * @param {string} key The key of the property to assign.
  18534. * @param {*} value The value to assign.
  18535. */
  18536. function baseAssignValue(object, key, value) {
  18537. if (key == '__proto__' && _defineProperty$1) {
  18538. _defineProperty$1(object, key, {
  18539. 'configurable': true,
  18540. 'enumerable': true,
  18541. 'value': value,
  18542. 'writable': true
  18543. });
  18544. } else {
  18545. object[key] = value;
  18546. }
  18547. }
  18548. var _baseAssignValue = baseAssignValue;
  18549. /** Used for built-in method references. */
  18550. var objectProto$e = Object.prototype;
  18551. /** Used to check objects for own properties. */
  18552. var hasOwnProperty$b = objectProto$e.hasOwnProperty;
  18553. /**
  18554. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  18555. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  18556. * for equality comparisons.
  18557. *
  18558. * @private
  18559. * @param {Object} object The object to modify.
  18560. * @param {string} key The key of the property to assign.
  18561. * @param {*} value The value to assign.
  18562. */
  18563. function assignValue(object, key, value) {
  18564. var objValue = object[key];
  18565. if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) ||
  18566. (value === undefined && !(key in object))) {
  18567. _baseAssignValue(object, key, value);
  18568. }
  18569. }
  18570. var _assignValue = assignValue;
  18571. /**
  18572. * Copies properties of `source` to `object`.
  18573. *
  18574. * @private
  18575. * @param {Object} source The object to copy properties from.
  18576. * @param {Array} props The property identifiers to copy.
  18577. * @param {Object} [object={}] The object to copy properties to.
  18578. * @param {Function} [customizer] The function to customize copied values.
  18579. * @returns {Object} Returns `object`.
  18580. */
  18581. function copyObject(source, props, object, customizer) {
  18582. var isNew = !object;
  18583. object || (object = {});
  18584. var index = -1,
  18585. length = props.length;
  18586. while (++index < length) {
  18587. var key = props[index];
  18588. var newValue = customizer
  18589. ? customizer(object[key], source[key], key, object, source)
  18590. : undefined;
  18591. if (newValue === undefined) {
  18592. newValue = source[key];
  18593. }
  18594. if (isNew) {
  18595. _baseAssignValue(object, key, newValue);
  18596. } else {
  18597. _assignValue(object, key, newValue);
  18598. }
  18599. }
  18600. return object;
  18601. }
  18602. var _copyObject = copyObject;
  18603. /**
  18604. * The base implementation of `_.assign` without support for multiple sources
  18605. * or `customizer` functions.
  18606. *
  18607. * @private
  18608. * @param {Object} object The destination object.
  18609. * @param {Object} source The source object.
  18610. * @returns {Object} Returns `object`.
  18611. */
  18612. function baseAssign(object, source) {
  18613. return object && _copyObject(source, keys_1(source), object);
  18614. }
  18615. var _baseAssign = baseAssign;
  18616. /**
  18617. * This function is like
  18618. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  18619. * except that it includes inherited enumerable properties.
  18620. *
  18621. * @private
  18622. * @param {Object} object The object to query.
  18623. * @returns {Array} Returns the array of property names.
  18624. */
  18625. function nativeKeysIn(object) {
  18626. var result = [];
  18627. if (object != null) {
  18628. for (var key in Object(object)) {
  18629. result.push(key);
  18630. }
  18631. }
  18632. return result;
  18633. }
  18634. var _nativeKeysIn = nativeKeysIn;
  18635. /** Used for built-in method references. */
  18636. var objectProto$f = Object.prototype;
  18637. /** Used to check objects for own properties. */
  18638. var hasOwnProperty$c = objectProto$f.hasOwnProperty;
  18639. /**
  18640. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  18641. *
  18642. * @private
  18643. * @param {Object} object The object to query.
  18644. * @returns {Array} Returns the array of property names.
  18645. */
  18646. function baseKeysIn(object) {
  18647. if (!isObject_1$1(object)) {
  18648. return _nativeKeysIn(object);
  18649. }
  18650. var isProto = _isPrototype(object),
  18651. result = [];
  18652. for (var key in object) {
  18653. if (!(key == 'constructor' && (isProto || !hasOwnProperty$c.call(object, key)))) {
  18654. result.push(key);
  18655. }
  18656. }
  18657. return result;
  18658. }
  18659. var _baseKeysIn = baseKeysIn;
  18660. /**
  18661. * Creates an array of the own and inherited enumerable property names of `object`.
  18662. *
  18663. * **Note:** Non-object values are coerced to objects.
  18664. *
  18665. * @static
  18666. * @memberOf _
  18667. * @since 3.0.0
  18668. * @category Object
  18669. * @param {Object} object The object to query.
  18670. * @returns {Array} Returns the array of property names.
  18671. * @example
  18672. *
  18673. * function Foo() {
  18674. * this.a = 1;
  18675. * this.b = 2;
  18676. * }
  18677. *
  18678. * Foo.prototype.c = 3;
  18679. *
  18680. * _.keysIn(new Foo);
  18681. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  18682. */
  18683. function keysIn(object) {
  18684. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  18685. }
  18686. var keysIn_1 = keysIn;
  18687. /**
  18688. * The base implementation of `_.assignIn` without support for multiple sources
  18689. * or `customizer` functions.
  18690. *
  18691. * @private
  18692. * @param {Object} object The destination object.
  18693. * @param {Object} source The source object.
  18694. * @returns {Object} Returns `object`.
  18695. */
  18696. function baseAssignIn(object, source) {
  18697. return object && _copyObject(source, keysIn_1(source), object);
  18698. }
  18699. var _baseAssignIn = baseAssignIn;
  18700. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  18701. /** Detect free variable `exports`. */
  18702. var freeExports = exports && !exports.nodeType && exports;
  18703. /** Detect free variable `module`. */
  18704. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  18705. /** Detect the popular CommonJS extension `module.exports`. */
  18706. var moduleExports = freeModule && freeModule.exports === freeExports;
  18707. /** Built-in value references. */
  18708. var Buffer = moduleExports ? _root.Buffer : undefined,
  18709. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  18710. /**
  18711. * Creates a clone of `buffer`.
  18712. *
  18713. * @private
  18714. * @param {Buffer} buffer The buffer to clone.
  18715. * @param {boolean} [isDeep] Specify a deep clone.
  18716. * @returns {Buffer} Returns the cloned buffer.
  18717. */
  18718. function cloneBuffer(buffer, isDeep) {
  18719. if (isDeep) {
  18720. return buffer.slice();
  18721. }
  18722. var length = buffer.length,
  18723. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  18724. buffer.copy(result);
  18725. return result;
  18726. }
  18727. module.exports = cloneBuffer;
  18728. });
  18729. /**
  18730. * Copies own symbols of `source` to `object`.
  18731. *
  18732. * @private
  18733. * @param {Object} source The object to copy symbols from.
  18734. * @param {Object} [object={}] The object to copy symbols to.
  18735. * @returns {Object} Returns `object`.
  18736. */
  18737. function copySymbols(source, object) {
  18738. return _copyObject(source, _getSymbols(source), object);
  18739. }
  18740. var _copySymbols = copySymbols;
  18741. /* Built-in method references for those with the same name as other `lodash` methods. */
  18742. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  18743. /**
  18744. * Creates an array of the own and inherited enumerable symbols of `object`.
  18745. *
  18746. * @private
  18747. * @param {Object} object The object to query.
  18748. * @returns {Array} Returns the array of symbols.
  18749. */
  18750. var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  18751. var result = [];
  18752. while (object) {
  18753. _arrayPush(result, _getSymbols(object));
  18754. object = _getPrototype(object);
  18755. }
  18756. return result;
  18757. };
  18758. var _getSymbolsIn = getSymbolsIn;
  18759. /**
  18760. * Copies own and inherited symbols of `source` to `object`.
  18761. *
  18762. * @private
  18763. * @param {Object} source The object to copy symbols from.
  18764. * @param {Object} [object={}] The object to copy symbols to.
  18765. * @returns {Object} Returns `object`.
  18766. */
  18767. function copySymbolsIn(source, object) {
  18768. return _copyObject(source, _getSymbolsIn(source), object);
  18769. }
  18770. var _copySymbolsIn = copySymbolsIn;
  18771. /**
  18772. * Creates an array of own and inherited enumerable property names and
  18773. * symbols of `object`.
  18774. *
  18775. * @private
  18776. * @param {Object} object The object to query.
  18777. * @returns {Array} Returns the array of property names and symbols.
  18778. */
  18779. function getAllKeysIn(object) {
  18780. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  18781. }
  18782. var _getAllKeysIn = getAllKeysIn;
  18783. /** Used for built-in method references. */
  18784. var objectProto$g = Object.prototype;
  18785. /** Used to check objects for own properties. */
  18786. var hasOwnProperty$d = objectProto$g.hasOwnProperty;
  18787. /**
  18788. * Initializes an array clone.
  18789. *
  18790. * @private
  18791. * @param {Array} array The array to clone.
  18792. * @returns {Array} Returns the initialized clone.
  18793. */
  18794. function initCloneArray(array) {
  18795. var length = array.length,
  18796. result = new array.constructor(length);
  18797. // Add properties assigned by `RegExp#exec`.
  18798. if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) {
  18799. result.index = array.index;
  18800. result.input = array.input;
  18801. }
  18802. return result;
  18803. }
  18804. var _initCloneArray = initCloneArray;
  18805. /**
  18806. * Creates a clone of `arrayBuffer`.
  18807. *
  18808. * @private
  18809. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  18810. * @returns {ArrayBuffer} Returns the cloned array buffer.
  18811. */
  18812. function cloneArrayBuffer(arrayBuffer) {
  18813. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  18814. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  18815. return result;
  18816. }
  18817. var _cloneArrayBuffer = cloneArrayBuffer;
  18818. /**
  18819. * Creates a clone of `dataView`.
  18820. *
  18821. * @private
  18822. * @param {Object} dataView The data view to clone.
  18823. * @param {boolean} [isDeep] Specify a deep clone.
  18824. * @returns {Object} Returns the cloned data view.
  18825. */
  18826. function cloneDataView(dataView, isDeep) {
  18827. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  18828. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  18829. }
  18830. var _cloneDataView = cloneDataView;
  18831. /** Used to match `RegExp` flags from their coerced string values. */
  18832. var reFlags = /\w*$/;
  18833. /**
  18834. * Creates a clone of `regexp`.
  18835. *
  18836. * @private
  18837. * @param {Object} regexp The regexp to clone.
  18838. * @returns {Object} Returns the cloned regexp.
  18839. */
  18840. function cloneRegExp(regexp) {
  18841. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  18842. result.lastIndex = regexp.lastIndex;
  18843. return result;
  18844. }
  18845. var _cloneRegExp = cloneRegExp;
  18846. /** Used to convert symbols to primitives and strings. */
  18847. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  18848. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  18849. /**
  18850. * Creates a clone of the `symbol` object.
  18851. *
  18852. * @private
  18853. * @param {Object} symbol The symbol object to clone.
  18854. * @returns {Object} Returns the cloned symbol object.
  18855. */
  18856. function cloneSymbol(symbol) {
  18857. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  18858. }
  18859. var _cloneSymbol = cloneSymbol;
  18860. /**
  18861. * Creates a clone of `typedArray`.
  18862. *
  18863. * @private
  18864. * @param {Object} typedArray The typed array to clone.
  18865. * @param {boolean} [isDeep] Specify a deep clone.
  18866. * @returns {Object} Returns the cloned typed array.
  18867. */
  18868. function cloneTypedArray(typedArray, isDeep) {
  18869. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  18870. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  18871. }
  18872. var _cloneTypedArray = cloneTypedArray;
  18873. /** `Object#toString` result references. */
  18874. var boolTag$2 = '[object Boolean]',
  18875. dateTag$2 = '[object Date]',
  18876. mapTag$4 = '[object Map]',
  18877. numberTag$2 = '[object Number]',
  18878. regexpTag$2 = '[object RegExp]',
  18879. setTag$4 = '[object Set]',
  18880. stringTag$2 = '[object String]',
  18881. symbolTag$2 = '[object Symbol]';
  18882. var arrayBufferTag$2 = '[object ArrayBuffer]',
  18883. dataViewTag$3 = '[object DataView]',
  18884. float32Tag$1 = '[object Float32Array]',
  18885. float64Tag$1 = '[object Float64Array]',
  18886. int8Tag$1 = '[object Int8Array]',
  18887. int16Tag$1 = '[object Int16Array]',
  18888. int32Tag$1 = '[object Int32Array]',
  18889. uint8Tag$1 = '[object Uint8Array]',
  18890. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  18891. uint16Tag$1 = '[object Uint16Array]',
  18892. uint32Tag$1 = '[object Uint32Array]';
  18893. /**
  18894. * Initializes an object clone based on its `toStringTag`.
  18895. *
  18896. * **Note:** This function only supports cloning values with tags of
  18897. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  18898. *
  18899. * @private
  18900. * @param {Object} object The object to clone.
  18901. * @param {string} tag The `toStringTag` of the object to clone.
  18902. * @param {boolean} [isDeep] Specify a deep clone.
  18903. * @returns {Object} Returns the initialized clone.
  18904. */
  18905. function initCloneByTag(object, tag, isDeep) {
  18906. var Ctor = object.constructor;
  18907. switch (tag) {
  18908. case arrayBufferTag$2:
  18909. return _cloneArrayBuffer(object);
  18910. case boolTag$2:
  18911. case dateTag$2:
  18912. return new Ctor(+object);
  18913. case dataViewTag$3:
  18914. return _cloneDataView(object, isDeep);
  18915. case float32Tag$1: case float64Tag$1:
  18916. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  18917. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  18918. return _cloneTypedArray(object, isDeep);
  18919. case mapTag$4:
  18920. return new Ctor;
  18921. case numberTag$2:
  18922. case stringTag$2:
  18923. return new Ctor(object);
  18924. case regexpTag$2:
  18925. return _cloneRegExp(object);
  18926. case setTag$4:
  18927. return new Ctor;
  18928. case symbolTag$2:
  18929. return _cloneSymbol(object);
  18930. }
  18931. }
  18932. var _initCloneByTag = initCloneByTag;
  18933. /** Built-in value references. */
  18934. var objectCreate = Object.create;
  18935. /**
  18936. * The base implementation of `_.create` without support for assigning
  18937. * properties to the created object.
  18938. *
  18939. * @private
  18940. * @param {Object} proto The object to inherit from.
  18941. * @returns {Object} Returns the new object.
  18942. */
  18943. var baseCreate = (function() {
  18944. function object() {}
  18945. return function(proto) {
  18946. if (!isObject_1$1(proto)) {
  18947. return {};
  18948. }
  18949. if (objectCreate) {
  18950. return objectCreate(proto);
  18951. }
  18952. object.prototype = proto;
  18953. var result = new object;
  18954. object.prototype = undefined;
  18955. return result;
  18956. };
  18957. }());
  18958. var _baseCreate = baseCreate;
  18959. /**
  18960. * Initializes an object clone.
  18961. *
  18962. * @private
  18963. * @param {Object} object The object to clone.
  18964. * @returns {Object} Returns the initialized clone.
  18965. */
  18966. function initCloneObject(object) {
  18967. return (typeof object.constructor == 'function' && !_isPrototype(object))
  18968. ? _baseCreate(_getPrototype(object))
  18969. : {};
  18970. }
  18971. var _initCloneObject = initCloneObject;
  18972. /** `Object#toString` result references. */
  18973. var mapTag$5 = '[object Map]';
  18974. /**
  18975. * The base implementation of `_.isMap` without Node.js optimizations.
  18976. *
  18977. * @private
  18978. * @param {*} value The value to check.
  18979. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  18980. */
  18981. function baseIsMap(value) {
  18982. return isObjectLike_1(value) && _getTag(value) == mapTag$5;
  18983. }
  18984. var _baseIsMap = baseIsMap;
  18985. /* Node.js helper references. */
  18986. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  18987. /**
  18988. * Checks if `value` is classified as a `Map` object.
  18989. *
  18990. * @static
  18991. * @memberOf _
  18992. * @since 4.3.0
  18993. * @category Lang
  18994. * @param {*} value The value to check.
  18995. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  18996. * @example
  18997. *
  18998. * _.isMap(new Map);
  18999. * // => true
  19000. *
  19001. * _.isMap(new WeakMap);
  19002. * // => false
  19003. */
  19004. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  19005. var isMap_1 = isMap;
  19006. /** `Object#toString` result references. */
  19007. var setTag$5 = '[object Set]';
  19008. /**
  19009. * The base implementation of `_.isSet` without Node.js optimizations.
  19010. *
  19011. * @private
  19012. * @param {*} value The value to check.
  19013. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  19014. */
  19015. function baseIsSet(value) {
  19016. return isObjectLike_1(value) && _getTag(value) == setTag$5;
  19017. }
  19018. var _baseIsSet = baseIsSet;
  19019. /* Node.js helper references. */
  19020. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  19021. /**
  19022. * Checks if `value` is classified as a `Set` object.
  19023. *
  19024. * @static
  19025. * @memberOf _
  19026. * @since 4.3.0
  19027. * @category Lang
  19028. * @param {*} value The value to check.
  19029. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  19030. * @example
  19031. *
  19032. * _.isSet(new Set);
  19033. * // => true
  19034. *
  19035. * _.isSet(new WeakSet);
  19036. * // => false
  19037. */
  19038. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  19039. var isSet_1 = isSet;
  19040. /** Used to compose bitmasks for cloning. */
  19041. var CLONE_DEEP_FLAG = 1,
  19042. CLONE_FLAT_FLAG = 2,
  19043. CLONE_SYMBOLS_FLAG = 4;
  19044. /** `Object#toString` result references. */
  19045. var argsTag$3 = '[object Arguments]',
  19046. arrayTag$2 = '[object Array]',
  19047. boolTag$3 = '[object Boolean]',
  19048. dateTag$3 = '[object Date]',
  19049. errorTag$2 = '[object Error]',
  19050. funcTag$2 = '[object Function]',
  19051. genTag$1 = '[object GeneratorFunction]',
  19052. mapTag$6 = '[object Map]',
  19053. numberTag$3 = '[object Number]',
  19054. objectTag$4 = '[object Object]',
  19055. regexpTag$3 = '[object RegExp]',
  19056. setTag$6 = '[object Set]',
  19057. stringTag$3 = '[object String]',
  19058. symbolTag$3 = '[object Symbol]',
  19059. weakMapTag$2 = '[object WeakMap]';
  19060. var arrayBufferTag$3 = '[object ArrayBuffer]',
  19061. dataViewTag$4 = '[object DataView]',
  19062. float32Tag$2 = '[object Float32Array]',
  19063. float64Tag$2 = '[object Float64Array]',
  19064. int8Tag$2 = '[object Int8Array]',
  19065. int16Tag$2 = '[object Int16Array]',
  19066. int32Tag$2 = '[object Int32Array]',
  19067. uint8Tag$2 = '[object Uint8Array]',
  19068. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  19069. uint16Tag$2 = '[object Uint16Array]',
  19070. uint32Tag$2 = '[object Uint32Array]';
  19071. /** Used to identify `toStringTag` values supported by `_.clone`. */
  19072. var cloneableTags = {};
  19073. cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] =
  19074. cloneableTags[arrayBufferTag$3] = cloneableTags[dataViewTag$4] =
  19075. cloneableTags[boolTag$3] = cloneableTags[dateTag$3] =
  19076. cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
  19077. cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
  19078. cloneableTags[int32Tag$2] = cloneableTags[mapTag$6] =
  19079. cloneableTags[numberTag$3] = cloneableTags[objectTag$4] =
  19080. cloneableTags[regexpTag$3] = cloneableTags[setTag$6] =
  19081. cloneableTags[stringTag$3] = cloneableTags[symbolTag$3] =
  19082. cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
  19083. cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
  19084. cloneableTags[errorTag$2] = cloneableTags[funcTag$2] =
  19085. cloneableTags[weakMapTag$2] = false;
  19086. /**
  19087. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  19088. * traversed objects.
  19089. *
  19090. * @private
  19091. * @param {*} value The value to clone.
  19092. * @param {boolean} bitmask The bitmask flags.
  19093. * 1 - Deep clone
  19094. * 2 - Flatten inherited properties
  19095. * 4 - Clone symbols
  19096. * @param {Function} [customizer] The function to customize cloning.
  19097. * @param {string} [key] The key of `value`.
  19098. * @param {Object} [object] The parent object of `value`.
  19099. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  19100. * @returns {*} Returns the cloned value.
  19101. */
  19102. function baseClone(value, bitmask, customizer, key, object, stack) {
  19103. var result,
  19104. isDeep = bitmask & CLONE_DEEP_FLAG,
  19105. isFlat = bitmask & CLONE_FLAT_FLAG,
  19106. isFull = bitmask & CLONE_SYMBOLS_FLAG;
  19107. if (customizer) {
  19108. result = object ? customizer(value, key, object, stack) : customizer(value);
  19109. }
  19110. if (result !== undefined) {
  19111. return result;
  19112. }
  19113. if (!isObject_1$1(value)) {
  19114. return value;
  19115. }
  19116. var isArr = isArray_1(value);
  19117. if (isArr) {
  19118. result = _initCloneArray(value);
  19119. if (!isDeep) {
  19120. return _copyArray(value, result);
  19121. }
  19122. } else {
  19123. var tag = _getTag(value),
  19124. isFunc = tag == funcTag$2 || tag == genTag$1;
  19125. if (isBuffer_1(value)) {
  19126. return _cloneBuffer(value, isDeep);
  19127. }
  19128. if (tag == objectTag$4 || tag == argsTag$3 || (isFunc && !object)) {
  19129. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  19130. if (!isDeep) {
  19131. return isFlat
  19132. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  19133. : _copySymbols(value, _baseAssign(result, value));
  19134. }
  19135. } else {
  19136. if (!cloneableTags[tag]) {
  19137. return object ? value : {};
  19138. }
  19139. result = _initCloneByTag(value, tag, isDeep);
  19140. }
  19141. }
  19142. // Check for circular references and return its corresponding clone.
  19143. stack || (stack = new _Stack);
  19144. var stacked = stack.get(value);
  19145. if (stacked) {
  19146. return stacked;
  19147. }
  19148. stack.set(value, result);
  19149. if (isSet_1(value)) {
  19150. value.forEach(function(subValue) {
  19151. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  19152. });
  19153. } else if (isMap_1(value)) {
  19154. value.forEach(function(subValue, key) {
  19155. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  19156. });
  19157. }
  19158. var keysFunc = isFull
  19159. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  19160. : (isFlat ? keysIn_1 : keys_1);
  19161. var props = isArr ? undefined : keysFunc(value);
  19162. _arrayEach(props || value, function(subValue, key) {
  19163. if (props) {
  19164. key = subValue;
  19165. subValue = value[key];
  19166. }
  19167. // Recursively populate clone (susceptible to call stack limits).
  19168. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  19169. });
  19170. return result;
  19171. }
  19172. var _baseClone = baseClone;
  19173. /** Used to compose bitmasks for cloning. */
  19174. var CLONE_DEEP_FLAG$1 = 1,
  19175. CLONE_SYMBOLS_FLAG$1 = 4;
  19176. /**
  19177. * This method is like `_.clone` except that it recursively clones `value`.
  19178. *
  19179. * @static
  19180. * @memberOf _
  19181. * @since 1.0.0
  19182. * @category Lang
  19183. * @param {*} value The value to recursively clone.
  19184. * @returns {*} Returns the deep cloned value.
  19185. * @see _.clone
  19186. * @example
  19187. *
  19188. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  19189. *
  19190. * var deep = _.cloneDeep(objects);
  19191. * console.log(deep[0] === objects[0]);
  19192. * // => false
  19193. */
  19194. function cloneDeep(value) {
  19195. return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
  19196. }
  19197. var cloneDeep_1 = cloneDeep;
  19198. /**
  19199. * Creates a `_.find` or `_.findLast` function.
  19200. *
  19201. * @private
  19202. * @param {Function} findIndexFunc The function to find the collection index.
  19203. * @returns {Function} Returns the new find function.
  19204. */
  19205. function createFind(findIndexFunc) {
  19206. return function(collection, predicate, fromIndex) {
  19207. var iterable = Object(collection);
  19208. if (!isArrayLike_1(collection)) {
  19209. var iteratee = _baseIteratee(predicate);
  19210. collection = keys_1(collection);
  19211. predicate = function(key) { return iteratee(iterable[key], key, iterable); };
  19212. }
  19213. var index = findIndexFunc(collection, predicate, fromIndex);
  19214. return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
  19215. };
  19216. }
  19217. var _createFind = createFind;
  19218. /**
  19219. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  19220. * support for iteratee shorthands.
  19221. *
  19222. * @private
  19223. * @param {Array} array The array to inspect.
  19224. * @param {Function} predicate The function invoked per iteration.
  19225. * @param {number} fromIndex The index to search from.
  19226. * @param {boolean} [fromRight] Specify iterating from right to left.
  19227. * @returns {number} Returns the index of the matched value, else `-1`.
  19228. */
  19229. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  19230. var length = array.length,
  19231. index = fromIndex + (fromRight ? 1 : -1);
  19232. while ((fromRight ? index-- : ++index < length)) {
  19233. if (predicate(array[index], index, array)) {
  19234. return index;
  19235. }
  19236. }
  19237. return -1;
  19238. }
  19239. var _baseFindIndex = baseFindIndex;
  19240. /** Used to match a single whitespace character. */
  19241. var reWhitespace = /\s/;
  19242. /**
  19243. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  19244. * character of `string`.
  19245. *
  19246. * @private
  19247. * @param {string} string The string to inspect.
  19248. * @returns {number} Returns the index of the last non-whitespace character.
  19249. */
  19250. function trimmedEndIndex(string) {
  19251. var index = string.length;
  19252. while (index-- && reWhitespace.test(string.charAt(index))) {}
  19253. return index;
  19254. }
  19255. var _trimmedEndIndex = trimmedEndIndex;
  19256. /** Used to match leading whitespace. */
  19257. var reTrimStart = /^\s+/;
  19258. /**
  19259. * The base implementation of `_.trim`.
  19260. *
  19261. * @private
  19262. * @param {string} string The string to trim.
  19263. * @returns {string} Returns the trimmed string.
  19264. */
  19265. function baseTrim(string) {
  19266. return string
  19267. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  19268. : string;
  19269. }
  19270. var _baseTrim = baseTrim;
  19271. /** Used as references for various `Number` constants. */
  19272. var NAN = 0 / 0;
  19273. /** Used to detect bad signed hexadecimal string values. */
  19274. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  19275. /** Used to detect binary string values. */
  19276. var reIsBinary = /^0b[01]+$/i;
  19277. /** Used to detect octal string values. */
  19278. var reIsOctal = /^0o[0-7]+$/i;
  19279. /** Built-in method references without a dependency on `root`. */
  19280. var freeParseInt = parseInt;
  19281. /**
  19282. * Converts `value` to a number.
  19283. *
  19284. * @static
  19285. * @memberOf _
  19286. * @since 4.0.0
  19287. * @category Lang
  19288. * @param {*} value The value to process.
  19289. * @returns {number} Returns the number.
  19290. * @example
  19291. *
  19292. * _.toNumber(3.2);
  19293. * // => 3.2
  19294. *
  19295. * _.toNumber(Number.MIN_VALUE);
  19296. * // => 5e-324
  19297. *
  19298. * _.toNumber(Infinity);
  19299. * // => Infinity
  19300. *
  19301. * _.toNumber('3.2');
  19302. * // => 3.2
  19303. */
  19304. function toNumber(value) {
  19305. if (typeof value == 'number') {
  19306. return value;
  19307. }
  19308. if (isSymbol_1(value)) {
  19309. return NAN;
  19310. }
  19311. if (isObject_1$1(value)) {
  19312. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  19313. value = isObject_1$1(other) ? (other + '') : other;
  19314. }
  19315. if (typeof value != 'string') {
  19316. return value === 0 ? value : +value;
  19317. }
  19318. value = _baseTrim(value);
  19319. var isBinary = reIsBinary.test(value);
  19320. return (isBinary || reIsOctal.test(value))
  19321. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  19322. : (reIsBadHex.test(value) ? NAN : +value);
  19323. }
  19324. var toNumber_1 = toNumber;
  19325. /** Used as references for various `Number` constants. */
  19326. var INFINITY$2 = 1 / 0,
  19327. MAX_INTEGER = 1.7976931348623157e+308;
  19328. /**
  19329. * Converts `value` to a finite number.
  19330. *
  19331. * @static
  19332. * @memberOf _
  19333. * @since 4.12.0
  19334. * @category Lang
  19335. * @param {*} value The value to convert.
  19336. * @returns {number} Returns the converted number.
  19337. * @example
  19338. *
  19339. * _.toFinite(3.2);
  19340. * // => 3.2
  19341. *
  19342. * _.toFinite(Number.MIN_VALUE);
  19343. * // => 5e-324
  19344. *
  19345. * _.toFinite(Infinity);
  19346. * // => 1.7976931348623157e+308
  19347. *
  19348. * _.toFinite('3.2');
  19349. * // => 3.2
  19350. */
  19351. function toFinite(value) {
  19352. if (!value) {
  19353. return value === 0 ? value : 0;
  19354. }
  19355. value = toNumber_1(value);
  19356. if (value === INFINITY$2 || value === -INFINITY$2) {
  19357. var sign = (value < 0 ? -1 : 1);
  19358. return sign * MAX_INTEGER;
  19359. }
  19360. return value === value ? value : 0;
  19361. }
  19362. var toFinite_1 = toFinite;
  19363. /**
  19364. * Converts `value` to an integer.
  19365. *
  19366. * **Note:** This method is loosely based on
  19367. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  19368. *
  19369. * @static
  19370. * @memberOf _
  19371. * @since 4.0.0
  19372. * @category Lang
  19373. * @param {*} value The value to convert.
  19374. * @returns {number} Returns the converted integer.
  19375. * @example
  19376. *
  19377. * _.toInteger(3.2);
  19378. * // => 3
  19379. *
  19380. * _.toInteger(Number.MIN_VALUE);
  19381. * // => 0
  19382. *
  19383. * _.toInteger(Infinity);
  19384. * // => 1.7976931348623157e+308
  19385. *
  19386. * _.toInteger('3.2');
  19387. * // => 3
  19388. */
  19389. function toInteger(value) {
  19390. var result = toFinite_1(value),
  19391. remainder = result % 1;
  19392. return result === result ? (remainder ? result - remainder : result) : 0;
  19393. }
  19394. var toInteger_1 = toInteger;
  19395. /* Built-in method references for those with the same name as other `lodash` methods. */
  19396. var nativeMax = Math.max;
  19397. /**
  19398. * This method is like `_.find` except that it returns the index of the first
  19399. * element `predicate` returns truthy for instead of the element itself.
  19400. *
  19401. * @static
  19402. * @memberOf _
  19403. * @since 1.1.0
  19404. * @category Array
  19405. * @param {Array} array The array to inspect.
  19406. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  19407. * @param {number} [fromIndex=0] The index to search from.
  19408. * @returns {number} Returns the index of the found element, else `-1`.
  19409. * @example
  19410. *
  19411. * var users = [
  19412. * { 'user': 'barney', 'active': false },
  19413. * { 'user': 'fred', 'active': false },
  19414. * { 'user': 'pebbles', 'active': true }
  19415. * ];
  19416. *
  19417. * _.findIndex(users, function(o) { return o.user == 'barney'; });
  19418. * // => 0
  19419. *
  19420. * // The `_.matches` iteratee shorthand.
  19421. * _.findIndex(users, { 'user': 'fred', 'active': false });
  19422. * // => 1
  19423. *
  19424. * // The `_.matchesProperty` iteratee shorthand.
  19425. * _.findIndex(users, ['active', false]);
  19426. * // => 0
  19427. *
  19428. * // The `_.property` iteratee shorthand.
  19429. * _.findIndex(users, 'active');
  19430. * // => 2
  19431. */
  19432. function findIndex(array, predicate, fromIndex) {
  19433. var length = array == null ? 0 : array.length;
  19434. if (!length) {
  19435. return -1;
  19436. }
  19437. var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
  19438. if (index < 0) {
  19439. index = nativeMax(length + index, 0);
  19440. }
  19441. return _baseFindIndex(array, _baseIteratee(predicate), index);
  19442. }
  19443. var findIndex_1 = findIndex;
  19444. /**
  19445. * Iterates over elements of `collection`, returning the first element
  19446. * `predicate` returns truthy for. The predicate is invoked with three
  19447. * arguments: (value, index|key, collection).
  19448. *
  19449. * @static
  19450. * @memberOf _
  19451. * @since 0.1.0
  19452. * @category Collection
  19453. * @param {Array|Object} collection The collection to inspect.
  19454. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  19455. * @param {number} [fromIndex=0] The index to search from.
  19456. * @returns {*} Returns the matched element, else `undefined`.
  19457. * @example
  19458. *
  19459. * var users = [
  19460. * { 'user': 'barney', 'age': 36, 'active': true },
  19461. * { 'user': 'fred', 'age': 40, 'active': false },
  19462. * { 'user': 'pebbles', 'age': 1, 'active': true }
  19463. * ];
  19464. *
  19465. * _.find(users, function(o) { return o.age < 40; });
  19466. * // => object for 'barney'
  19467. *
  19468. * // The `_.matches` iteratee shorthand.
  19469. * _.find(users, { 'age': 1, 'active': true });
  19470. * // => object for 'pebbles'
  19471. *
  19472. * // The `_.matchesProperty` iteratee shorthand.
  19473. * _.find(users, ['active', false]);
  19474. * // => object for 'fred'
  19475. *
  19476. * // The `_.property` iteratee shorthand.
  19477. * _.find(users, 'active');
  19478. * // => object for 'barney'
  19479. */
  19480. var find = _createFind(findIndex_1);
  19481. var find_1 = find;
  19482. // IMClient
  19483. var UNREAD_MESSAGES_COUNT_UPDATE = 'unreadmessagescountupdate';
  19484. var CLOSE = 'close';
  19485. var CONFLICT = 'conflict';
  19486. var CONVERSATION_INFO_UPDATED = 'conversationinfoupdated';
  19487. var UNHANDLED_MESSAGE = 'unhandledmessage'; // shared
  19488. var INVITED = 'invited';
  19489. var KICKED = 'kicked';
  19490. var MEMBERS_JOINED = 'membersjoined';
  19491. var MEMBERS_LEFT = 'membersleft';
  19492. var MEMBER_INFO_UPDATED = 'memberinfoupdated';
  19493. var BLOCKED = 'blocked';
  19494. var UNBLOCKED = 'unblocked';
  19495. var MEMBERS_BLOCKED = 'membersblocked';
  19496. var MEMBERS_UNBLOCKED = 'membersunblocked';
  19497. var MUTED = 'muted';
  19498. var UNMUTED = 'unmuted';
  19499. var MEMBERS_MUTED = 'membersmuted';
  19500. var MEMBERS_UNMUTED = 'membersunmuted';
  19501. var MESSAGE$1 = 'message';
  19502. var MESSAGE_RECALL = 'messagerecall';
  19503. var MESSAGE_UPDATE = 'messageupdate'; // Conversation
  19504. var LAST_DELIVERED_AT_UPDATE = 'lastdeliveredatupdate';
  19505. var LAST_READ_AT_UPDATE = 'lastreadatupdate';
  19506. var INFO_UPDATED = 'infoupdated';
  19507. var IMEvent = /*#__PURE__*/Object.freeze({
  19508. __proto__: null,
  19509. UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE,
  19510. CLOSE: CLOSE,
  19511. CONFLICT: CONFLICT,
  19512. CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED,
  19513. UNHANDLED_MESSAGE: UNHANDLED_MESSAGE,
  19514. INVITED: INVITED,
  19515. KICKED: KICKED,
  19516. MEMBERS_JOINED: MEMBERS_JOINED,
  19517. MEMBERS_LEFT: MEMBERS_LEFT,
  19518. MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED,
  19519. BLOCKED: BLOCKED,
  19520. UNBLOCKED: UNBLOCKED,
  19521. MEMBERS_BLOCKED: MEMBERS_BLOCKED,
  19522. MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED,
  19523. MUTED: MUTED,
  19524. UNMUTED: UNMUTED,
  19525. MEMBERS_MUTED: MEMBERS_MUTED,
  19526. MEMBERS_UNMUTED: MEMBERS_UNMUTED,
  19527. MESSAGE: MESSAGE$1,
  19528. MESSAGE_RECALL: MESSAGE_RECALL,
  19529. MESSAGE_UPDATE: MESSAGE_UPDATE,
  19530. LAST_DELIVERED_AT_UPDATE: LAST_DELIVERED_AT_UPDATE,
  19531. LAST_READ_AT_UPDATE: LAST_READ_AT_UPDATE,
  19532. INFO_UPDATED: INFO_UPDATED
  19533. });
  19534. var _rMessageStatus;
  19535. function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  19536. function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  19537. /**
  19538. * 消息状态枚举
  19539. * @enum {Symbol}
  19540. * @since 3.2.0
  19541. * @memberof module:leancloud-realtime
  19542. */
  19543. var MessageStatus = {
  19544. /** 初始状态、未知状态 */
  19545. NONE: Symbol('none'),
  19546. /** 正在发送 */
  19547. SENDING: Symbol('sending'),
  19548. /** 已发送 */
  19549. SENT: Symbol('sent'),
  19550. /** 已送达 */
  19551. DELIVERED: Symbol('delivered'),
  19552. /** 发送失败 */
  19553. FAILED: Symbol('failed')
  19554. };
  19555. Object.freeze(MessageStatus);
  19556. var rMessageStatus = (_rMessageStatus = {}, defineProperty(_rMessageStatus, MessageStatus.NONE, true), defineProperty(_rMessageStatus, MessageStatus.SENDING, true), defineProperty(_rMessageStatus, MessageStatus.SENT, true), defineProperty(_rMessageStatus, MessageStatus.DELIVERED, true), defineProperty(_rMessageStatus, MessageStatus.READ, true), defineProperty(_rMessageStatus, MessageStatus.FAILED, true), _rMessageStatus);
  19557. var Message = /*#__PURE__*/function () {
  19558. /**
  19559. * @implements AVMessage
  19560. * @param {Object|String|ArrayBuffer} content 消息内容
  19561. */
  19562. function Message(content) {
  19563. Object.assign(this, {
  19564. content: content
  19565. }, {
  19566. /**
  19567. * @type {String}
  19568. * @memberof Message#
  19569. */
  19570. id: v4_1(),
  19571. /**
  19572. * 消息所在的 conversation id
  19573. * @memberof Message#
  19574. * @type {String?}
  19575. */
  19576. cid: null,
  19577. /**
  19578. * 消息发送时间
  19579. * @memberof Message#
  19580. * @type {Date}
  19581. */
  19582. timestamp: new Date(),
  19583. /**
  19584. * 消息发送者
  19585. * @memberof Message#
  19586. * @type {String}
  19587. */
  19588. from: undefined,
  19589. /**
  19590. * 消息提及的用户
  19591. * @since 4.0.0
  19592. * @memberof Message#
  19593. * @type {String[]}
  19594. */
  19595. mentionList: [],
  19596. /**
  19597. * 消息是否提及了所有人
  19598. * @since 4.0.0
  19599. * @memberof Message#
  19600. * @type {Boolean}
  19601. */
  19602. mentionedAll: false,
  19603. _mentioned: false
  19604. });
  19605. this._setStatus(MessageStatus.NONE);
  19606. }
  19607. /**
  19608. * 将当前消息的内容序列化为 JSON 对象
  19609. * @private
  19610. * @return {Object}
  19611. */
  19612. var _proto = Message.prototype;
  19613. _proto.getPayload = function getPayload() {
  19614. return this.content;
  19615. };
  19616. _proto._toJSON = function _toJSON() {
  19617. var id = this.id,
  19618. cid = this.cid,
  19619. from = this.from,
  19620. timestamp = this.timestamp,
  19621. deliveredAt = this.deliveredAt,
  19622. updatedAt = this.updatedAt,
  19623. mentionList = this.mentionList,
  19624. mentionedAll = this.mentionedAll,
  19625. mentioned = this.mentioned;
  19626. return {
  19627. id: id,
  19628. cid: cid,
  19629. from: from,
  19630. timestamp: timestamp,
  19631. deliveredAt: deliveredAt,
  19632. updatedAt: updatedAt,
  19633. mentionList: mentionList,
  19634. mentionedAll: mentionedAll,
  19635. mentioned: mentioned
  19636. };
  19637. }
  19638. /**
  19639. * 返回 JSON 格式的消息
  19640. * @return {Object} 返回值是一个 plain Object
  19641. */
  19642. ;
  19643. _proto.toJSON = function toJSON() {
  19644. return _objectSpread$3(_objectSpread$3({}, this._toJSON()), {}, {
  19645. data: this.content
  19646. });
  19647. }
  19648. /**
  19649. * 返回 JSON 格式的消息,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseMessage} 反序列化。
  19650. * @return {Object} 返回值是一个 plain Object
  19651. * @since 4.0.0
  19652. */
  19653. ;
  19654. _proto.toFullJSON = function toFullJSON() {
  19655. var content = this.content,
  19656. id = this.id,
  19657. cid = this.cid,
  19658. from = this.from,
  19659. timestamp = this.timestamp,
  19660. deliveredAt = this.deliveredAt,
  19661. _updatedAt = this._updatedAt,
  19662. mentionList = this.mentionList,
  19663. mentionedAll = this.mentionedAll;
  19664. return {
  19665. data: content,
  19666. id: id,
  19667. cid: cid,
  19668. from: from,
  19669. timestamp: getTime(timestamp),
  19670. deliveredAt: getTime(deliveredAt),
  19671. updatedAt: getTime(_updatedAt),
  19672. mentionList: mentionList,
  19673. mentionedAll: mentionedAll
  19674. };
  19675. }
  19676. /**
  19677. * 消息状态,值为 {@link module:leancloud-realtime.MessageStatus} 之一
  19678. * @type {Symbol}
  19679. * @readonly
  19680. * @since 3.2.0
  19681. */
  19682. ;
  19683. _proto._setStatus = function _setStatus(status) {
  19684. if (!rMessageStatus[status]) {
  19685. throw new Error('Invalid message status');
  19686. }
  19687. this._status = status;
  19688. };
  19689. _proto._updateMentioned = function _updateMentioned(client) {
  19690. this._mentioned = this.from !== client && (this.mentionedAll || this.mentionList.indexOf(client) > -1);
  19691. }
  19692. /**
  19693. * 获取提及用户列表
  19694. * @since 4.0.0
  19695. * @return {String[]} 提及用户的 id 列表
  19696. */
  19697. ;
  19698. _proto.getMentionList = function getMentionList() {
  19699. return this.mentionList;
  19700. }
  19701. /**
  19702. * 设置提及用户列表
  19703. * @since 4.0.0
  19704. * @param {String[]} clients 提及用户的 id 列表
  19705. * @return {this} self
  19706. */
  19707. ;
  19708. _proto.setMentionList = function setMentionList(clients) {
  19709. this.mentionList = ensureArray(clients);
  19710. return this;
  19711. }
  19712. /**
  19713. * 设置是否提及所有人
  19714. * @since 4.0.0
  19715. * @param {Boolean} [value=true]
  19716. * @return {this} self
  19717. */
  19718. ;
  19719. _proto.mentionAll = function mentionAll() {
  19720. var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  19721. this.mentionedAll = Boolean(value);
  19722. return this;
  19723. }
  19724. /**
  19725. * 判断给定的内容是否是有效的 Message,
  19726. * 该方法始终返回 true
  19727. * @private
  19728. * @returns {Boolean}
  19729. * @implements AVMessage.validate
  19730. */
  19731. ;
  19732. Message.validate = function validate() {
  19733. return true;
  19734. }
  19735. /**
  19736. * 解析处理消息内容
  19737. * <pre>
  19738. * 如果子类提供了 message,返回该 message
  19739. * 如果没有提供,将 json 作为 content 实例化一个 Message
  19740. * @private
  19741. * @param {Object} json json 格式的消息内容
  19742. * @param {Message} message 子类提供的 message
  19743. * @return {Message}
  19744. * @implements AVMessage.parse
  19745. */
  19746. ;
  19747. Message.parse = function parse(json, message) {
  19748. return message || new this(json);
  19749. };
  19750. createClass(Message, [{
  19751. key: "status",
  19752. get: function get() {
  19753. return this._status;
  19754. }
  19755. }, {
  19756. key: "timestamp",
  19757. get: function get() {
  19758. return this._timestamp;
  19759. },
  19760. set: function set(value) {
  19761. this._timestamp = decodeDate(value);
  19762. }
  19763. /**
  19764. * 消息送达时间
  19765. * @type {?Date}
  19766. */
  19767. }, {
  19768. key: "deliveredAt",
  19769. get: function get() {
  19770. return this._deliveredAt;
  19771. },
  19772. set: function set(value) {
  19773. this._deliveredAt = decodeDate(value);
  19774. }
  19775. /**
  19776. * 消息修改或撤回时间,可以通过比较其与消息的 timestamp 是否相等判断消息是否被修改过或撤回过。
  19777. * @type {Date}
  19778. * @since 3.5.0
  19779. */
  19780. }, {
  19781. key: "updatedAt",
  19782. get: function get() {
  19783. return this._updatedAt || this.timestamp;
  19784. },
  19785. set: function set(value) {
  19786. this._updatedAt = decodeDate(value);
  19787. }
  19788. /**
  19789. * 当前用户是否在该消息中被提及
  19790. * @type {Boolean}
  19791. * @readonly
  19792. * @since 4.0.0
  19793. */
  19794. }, {
  19795. key: "mentioned",
  19796. get: function get() {
  19797. return this._mentioned;
  19798. }
  19799. }]);
  19800. return Message;
  19801. }();
  19802. /* eslint-disable no-param-reassign */
  19803. var messageType = function messageType(type) {
  19804. if (typeof type !== 'number') {
  19805. throw new TypeError("".concat(type, " is not a Number"));
  19806. }
  19807. return function (target) {
  19808. target.TYPE = type;
  19809. target.validate = function (json) {
  19810. return json._lctype === type;
  19811. };
  19812. target.prototype._getType = function () {
  19813. return {
  19814. _lctype: type
  19815. };
  19816. };
  19817. };
  19818. }; // documented in ../plugin-im.js
  19819. var messageField = function messageField(fields) {
  19820. if (typeof fields !== 'string') {
  19821. if (!Array.isArray(fields)) {
  19822. throw new TypeError("".concat(fields, " is not an Array"));
  19823. } else if (fields.some(function (value) {
  19824. return typeof value !== 'string';
  19825. })) {
  19826. throw new TypeError('fields contains non-string typed member');
  19827. }
  19828. }
  19829. return function (target) {
  19830. // IE10 Hack:
  19831. // static properties in IE10 will not be inherited from super
  19832. // search for parse method and assign it manually
  19833. var originalCustomFields = isIE10 ? getStaticProperty(target, '_customFields') : target._customFields;
  19834. originalCustomFields = Array.isArray(originalCustomFields) ? originalCustomFields : [];
  19835. target._customFields = originalCustomFields.concat(fields);
  19836. };
  19837. }; // IE10 Hack:
  19838. // static properties in IE10 will not be inherited from super
  19839. // search for parse method and assign it manually
  19840. var IE10Compatible = function IE10Compatible(target) {
  19841. if (isIE10) {
  19842. target.parse = getStaticProperty(target, 'parse');
  19843. }
  19844. };
  19845. var _dec, _class$1;
  19846. function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  19847. function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  19848. var // jsdoc-ignore-end
  19849. /**
  19850. * 所有内置的富媒体消息均继承自本类
  19851. * @extends Message
  19852. */
  19853. TypedMessage = (_dec = messageField(['_lctext', '_lcattrs']), _dec(_class$1 = /*#__PURE__*/function (_Message) {
  19854. inheritsLoose(TypedMessage, _Message);
  19855. function TypedMessage() {
  19856. return _Message.apply(this, arguments) || this;
  19857. }
  19858. var _proto = TypedMessage.prototype;
  19859. /**
  19860. * @param {String} text
  19861. * @return {this} self
  19862. */
  19863. _proto.setText = function setText(text) {
  19864. this._lctext = text;
  19865. return this;
  19866. }
  19867. /**
  19868. * @return {String}
  19869. */
  19870. ;
  19871. _proto.getText = function getText() {
  19872. return this._lctext;
  19873. }
  19874. /**
  19875. * @param {Object} attributes
  19876. * @return {this} self
  19877. */
  19878. ;
  19879. _proto.setAttributes = function setAttributes(attributes) {
  19880. this._lcattrs = attributes;
  19881. return this;
  19882. }
  19883. /**
  19884. * @return {Object}
  19885. */
  19886. ;
  19887. _proto.getAttributes = function getAttributes() {
  19888. return this._lcattrs;
  19889. };
  19890. _proto._getCustomFields = function _getCustomFields() {
  19891. var _this = this;
  19892. var fields = Array.isArray(this.constructor._customFields) ? this.constructor._customFields : [];
  19893. return fields.reduce(function (result, field) {
  19894. if (typeof field !== 'string') return result;
  19895. result[field] = _this[field]; // eslint-disable-line no-param-reassign
  19896. return result;
  19897. }, {});
  19898. }
  19899. /* eslint-disable class-methods-use-this */
  19900. ;
  19901. _proto._getType = function _getType() {
  19902. throw new Error('not implemented');
  19903. }
  19904. /* eslint-enable class-methods-use-this */
  19905. ;
  19906. _proto.getPayload = function getPayload() {
  19907. return compact(_objectSpread$4(_objectSpread$4({
  19908. _lctext: this.getText(),
  19909. _lcattrs: this.getAttributes()
  19910. }, this._getCustomFields()), this._getType()));
  19911. };
  19912. _proto.toJSON = function toJSON() {
  19913. var type = this.type,
  19914. text = this.text,
  19915. attributes = this.attributes,
  19916. summary = this.summary;
  19917. return _objectSpread$4(_objectSpread$4({}, _Message.prototype._toJSON.call(this)), {}, {
  19918. type: type,
  19919. text: text,
  19920. attributes: attributes,
  19921. summary: summary
  19922. });
  19923. };
  19924. _proto.toFullJSON = function toFullJSON() {
  19925. return _objectSpread$4(_objectSpread$4({}, _Message.prototype.toFullJSON.call(this)), {}, {
  19926. data: this.getPayload()
  19927. });
  19928. }
  19929. /**
  19930. * 解析处理消息内容
  19931. * <pre>
  19932. * 为给定的 message 设置 text 与 attributes 属性,返回该 message
  19933. * 如果子类没有提供 message,new this()
  19934. * @protected
  19935. * @param {Object} json json 格式的消息内容
  19936. * @param {TypedMessage} message 子类提供的 message
  19937. * @return {TypedMessage}
  19938. * @implements AVMessage.parse
  19939. */
  19940. ;
  19941. TypedMessage.parse = function parse(json) {
  19942. var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new this();
  19943. message.content = json; // eslint-disable-line no-param-reassign
  19944. var customFields = isIE10 ? getStaticProperty(message.constructor, '_customFields') : message.constructor._customFields;
  19945. var fields = Array.isArray(customFields) ? customFields : [];
  19946. fields = fields.reduce(function (result, field) {
  19947. if (typeof field !== 'string') return result;
  19948. result[field] = json[field]; // eslint-disable-line no-param-reassign
  19949. return result;
  19950. }, {});
  19951. Object.assign(message, fields);
  19952. return _Message.parse.call(this, json, message);
  19953. };
  19954. createClass(TypedMessage, [{
  19955. key: "type",
  19956. /**
  19957. * @type {Number}
  19958. * @readonly
  19959. */
  19960. get: function get() {
  19961. return this.constructor.TYPE;
  19962. }
  19963. /** @type {String} */
  19964. }, {
  19965. key: "text",
  19966. set: function set(text) {
  19967. return this.setText(text);
  19968. },
  19969. get: function get() {
  19970. return this.getText();
  19971. }
  19972. /** @type {Object} */
  19973. }, {
  19974. key: "attributes",
  19975. set: function set(attributes) {
  19976. return this.setAttributes(attributes);
  19977. },
  19978. get: function get() {
  19979. return this.getAttributes();
  19980. }
  19981. /**
  19982. * 在客户端需要以文本形式展示该消息时显示的文案,
  19983. * 如 <code>[红包] 新春快乐</code>。
  19984. * 默认值为消息的 text。
  19985. * @type {String}
  19986. * @readonly
  19987. */
  19988. }, {
  19989. key: "summary",
  19990. get: function get() {
  19991. return this.text;
  19992. }
  19993. }]);
  19994. return TypedMessage;
  19995. }(Message)) || _class$1);
  19996. var _dec$1, _class$2;
  19997. var // jsdoc-ignore-end
  19998. /**
  19999. * 已撤回类型消息,当消息被撤回时,SDK 会使用该类型的消息替代原始消息
  20000. * @extends TypedMessage
  20001. */
  20002. RecalledMessage = (_dec$1 = messageType(-127), _dec$1(_class$2 = IE10Compatible(_class$2 = /*#__PURE__*/function (_TypedMessage) {
  20003. inheritsLoose(RecalledMessage, _TypedMessage);
  20004. function RecalledMessage() {
  20005. return _TypedMessage.apply(this, arguments) || this;
  20006. }
  20007. createClass(RecalledMessage, [{
  20008. key: "summary",
  20009. /**
  20010. * 在客户端需要以文本形式展示该消息时显示的文案,值为 <code>[该消息已撤回]</code>
  20011. * @type {String}
  20012. * @readonly
  20013. */
  20014. // eslint-disable-next-line class-methods-use-this
  20015. get: function get() {
  20016. return '[该消息已撤回]';
  20017. }
  20018. }]);
  20019. return RecalledMessage;
  20020. }(TypedMessage)) || _class$2) || _class$2);
  20021. function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  20022. function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  20023. var debug$7 = browser('LC:Conversation');
  20024. var serializeMessage = function serializeMessage(message) {
  20025. var content = message.getPayload();
  20026. var msg;
  20027. var binaryMsg;
  20028. if (content instanceof ArrayBuffer) {
  20029. binaryMsg = content;
  20030. } else if (typeof content !== 'string') {
  20031. msg = JSON.stringify(content);
  20032. } else {
  20033. msg = content;
  20034. }
  20035. return {
  20036. msg: msg,
  20037. binaryMsg: binaryMsg
  20038. };
  20039. };
  20040. var _LogsCommand$QueryDir = LogsCommand.QueryDirection,
  20041. NEW = _LogsCommand$QueryDir.NEW,
  20042. OLD = _LogsCommand$QueryDir.OLD;
  20043. /**
  20044. * 历史消息查询方向枚举
  20045. * @enum {Number}
  20046. * @since 4.0.0
  20047. * @memberof module:leancloud-realtime
  20048. */
  20049. var MessageQueryDirection = {
  20050. /** 从后向前 */
  20051. NEW_TO_OLD: OLD,
  20052. /** 从前向后 */
  20053. OLD_TO_NEW: NEW
  20054. };
  20055. Object.freeze(MessageQueryDirection);
  20056. var ConversationBase = /*#__PURE__*/function (_EventEmitter) {
  20057. inheritsLoose(ConversationBase, _EventEmitter);
  20058. /**
  20059. * @extends EventEmitter
  20060. * @private
  20061. * @abstract
  20062. */
  20063. function ConversationBase(_ref, client) {
  20064. var _this;
  20065. var id = _ref.id,
  20066. lastMessageAt = _ref.lastMessageAt,
  20067. lastMessage = _ref.lastMessage,
  20068. lastDeliveredAt = _ref.lastDeliveredAt,
  20069. lastReadAt = _ref.lastReadAt,
  20070. _ref$unreadMessagesCo = _ref.unreadMessagesCount,
  20071. unreadMessagesCount = _ref$unreadMessagesCo === void 0 ? 0 : _ref$unreadMessagesCo,
  20072. _ref$members = _ref.members,
  20073. members = _ref$members === void 0 ? [] : _ref$members,
  20074. _ref$mentioned = _ref.mentioned,
  20075. mentioned = _ref$mentioned === void 0 ? false : _ref$mentioned,
  20076. properties = objectWithoutProperties(_ref, ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"]);
  20077. _this = _EventEmitter.call(this) || this;
  20078. Object.assign(assertThisInitialized(_this), _objectSpread$5({
  20079. /**
  20080. * 对话 id,对应 _Conversation 表中的 objectId
  20081. * @memberof ConversationBase#
  20082. * @type {String}
  20083. */
  20084. id: id,
  20085. /**
  20086. * 最后一条消息时间
  20087. * @memberof ConversationBase#
  20088. * @type {?Date}
  20089. */
  20090. lastMessageAt: lastMessageAt,
  20091. /**
  20092. * 最后一条消息
  20093. * @memberof ConversationBase#
  20094. * @type {?Message}
  20095. */
  20096. lastMessage: lastMessage,
  20097. /**
  20098. * 参与该对话的用户列表
  20099. * @memberof ConversationBase#
  20100. * @type {String[]}
  20101. */
  20102. members: members
  20103. }, properties));
  20104. _this.members = Array.from(new Set(_this.members));
  20105. Object.assign(internal(assertThisInitialized(_this)), {
  20106. messagesWaitingForReceipt: {},
  20107. lastDeliveredAt: lastDeliveredAt,
  20108. lastReadAt: lastReadAt,
  20109. unreadMessagesCount: unreadMessagesCount,
  20110. mentioned: mentioned
  20111. });
  20112. _this._client = client;
  20113. if (debug$7.enabled) {
  20114. values_1(IMEvent).forEach(function (event) {
  20115. return _this.on(event, function () {
  20116. for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
  20117. payload[_key] = arguments[_key];
  20118. }
  20119. return _this._debug("".concat(event, " event emitted. %o"), payload);
  20120. });
  20121. });
  20122. } // onConversationCreate hook
  20123. applyDecorators(_this._client._plugins.onConversationCreate, assertThisInitialized(_this));
  20124. return _this;
  20125. }
  20126. /**
  20127. * 当前用户是否在该对话的未读消息中被提及
  20128. * @type {Boolean}
  20129. * @since 4.0.0
  20130. */
  20131. var _proto = ConversationBase.prototype;
  20132. _proto._setUnreadMessagesMentioned = function _setUnreadMessagesMentioned(value) {
  20133. internal(this).unreadMessagesMentioned = Boolean(value);
  20134. };
  20135. _proto._setLastDeliveredAt = function _setLastDeliveredAt(value) {
  20136. var date = decodeDate(value);
  20137. if (!(date < internal(this).lastDeliveredAt)) {
  20138. internal(this).lastDeliveredAt = date;
  20139. /**
  20140. * 最后消息送达时间更新
  20141. * @event ConversationBase#LAST_DELIVERED_AT_UPDATE
  20142. * @since 3.4.0
  20143. */
  20144. this.emit(LAST_DELIVERED_AT_UPDATE);
  20145. }
  20146. }
  20147. /**
  20148. * 最后消息被阅读时间,常用来实现发送消息的「已读」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
  20149. * @type {?Date}
  20150. * @since 3.4.0
  20151. */
  20152. ;
  20153. _proto._setLastReadAt = function _setLastReadAt(value) {
  20154. var date = decodeDate(value);
  20155. if (!(date < internal(this).lastReadAt)) {
  20156. internal(this).lastReadAt = date;
  20157. /**
  20158. * 最后消息被阅读时间更新
  20159. * @event ConversationBase#LAST_READ_AT_UPDATE
  20160. * @since 3.4.0
  20161. */
  20162. this.emit(LAST_READ_AT_UPDATE);
  20163. }
  20164. }
  20165. /**
  20166. * 返回 JSON 格式的对话,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseConversation} 反序列化。
  20167. * @return {Object} 返回值是一个 plain Object
  20168. * @since 4.0.0
  20169. */
  20170. ;
  20171. _proto.toFullJSON = function toFullJSON() {
  20172. var id = this.id,
  20173. members = this.members,
  20174. lastMessageAt = this.lastMessageAt,
  20175. lastDeliveredAt = this.lastDeliveredAt,
  20176. lastReadAt = this.lastReadAt,
  20177. lastMessage = this.lastMessage,
  20178. unreadMessagesCount = this.unreadMessagesCount;
  20179. return {
  20180. id: id,
  20181. members: members,
  20182. lastMessageAt: getTime(lastMessageAt),
  20183. lastDeliveredAt: getTime(lastDeliveredAt),
  20184. lastReadAt: getTime(lastReadAt),
  20185. lastMessage: lastMessage ? lastMessage.toFullJSON() : undefined,
  20186. unreadMessagesCount: unreadMessagesCount
  20187. };
  20188. }
  20189. /**
  20190. * 返回 JSON 格式的对话
  20191. * @return {Object} 返回值是一个 plain Object
  20192. * @since 4.0.0
  20193. */
  20194. ;
  20195. _proto.toJSON = function toJSON() {
  20196. var id = this.id,
  20197. members = this.members,
  20198. lastMessageAt = this.lastMessageAt,
  20199. lastDeliveredAt = this.lastDeliveredAt,
  20200. lastReadAt = this.lastReadAt,
  20201. lastMessage = this.lastMessage,
  20202. unreadMessagesCount = this.unreadMessagesCount,
  20203. unreadMessagesMentioned = this.unreadMessagesMentioned;
  20204. return {
  20205. id: id,
  20206. members: members,
  20207. lastMessageAt: lastMessageAt,
  20208. lastDeliveredAt: lastDeliveredAt,
  20209. lastReadAt: lastReadAt,
  20210. lastMessage: lastMessage ? lastMessage.toJSON() : undefined,
  20211. unreadMessagesCount: unreadMessagesCount,
  20212. unreadMessagesMentioned: unreadMessagesMentioned
  20213. };
  20214. };
  20215. _proto._debug = function _debug() {
  20216. for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  20217. params[_key2] = arguments[_key2];
  20218. }
  20219. debug$7.apply(void 0, params.concat(["[".concat(this.id, "]")]));
  20220. };
  20221. _proto._send = function _send(command) {
  20222. var _this$_client;
  20223. /* eslint-disable no-param-reassign */
  20224. if (command.cmd === null) {
  20225. command.cmd = 'conv';
  20226. }
  20227. if (command.cmd === 'conv' && command.convMessage === null) {
  20228. command.convMessage = new ConvCommand();
  20229. }
  20230. if (command.convMessage && command.convMessage.cid === null) {
  20231. command.convMessage.cid = this.id;
  20232. }
  20233. /* eslint-enable no-param-reassign */
  20234. for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  20235. args[_key3 - 1] = arguments[_key3];
  20236. }
  20237. return (_this$_client = this._client)._send.apply(_this$_client, [command].concat(args));
  20238. }
  20239. /**
  20240. * 发送消息
  20241. * @param {Message} message 消息,Message 及其子类的实例
  20242. * @param {Object} [options] since v3.3.0,发送选项
  20243. * @param {Boolean} [options.transient] since v3.3.1,是否作为暂态消息发送
  20244. * @param {Boolean} [options.receipt] 是否需要回执,仅在普通对话中有效
  20245. * @param {Boolean} [options.will] since v3.4.0,是否指定该消息作为「掉线消息」发送,
  20246. * 「掉线消息」会延迟到当前用户掉线后发送,常用来实现「下线通知」功能
  20247. * @param {MessagePriority} [options.priority] 消息优先级,仅在暂态对话中有效,
  20248. * see: {@link module:leancloud-realtime.MessagePriority MessagePriority}
  20249. * @param {Object} [options.pushData] 消息对应的离线推送内容,如果消息接收方不在线,会推送指定的内容。其结构说明参见: {@link https://url.leanapp.cn/pushData 推送消息内容}
  20250. * @return {Promise.<Message>} 发送的消息
  20251. */
  20252. ;
  20253. _proto.send =
  20254. /*#__PURE__*/
  20255. function () {
  20256. var _send2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(message, options) {
  20257. var _message$constructor$, _transient, receipt, priority, pushData, will, _serializeMessage, msg, binaryMsg, command, resCommand, _resCommand$ackMessag, uid, t, code, reason, appCode;
  20258. return regenerator.wrap(function _callee$(_context) {
  20259. while (1) {
  20260. switch (_context.prev = _context.next) {
  20261. case 0:
  20262. this._debug(message, 'send');
  20263. if (message instanceof Message) {
  20264. _context.next = 3;
  20265. break;
  20266. }
  20267. throw new TypeError("".concat(message, " is not a Message"));
  20268. case 3:
  20269. _message$constructor$ = _objectSpread$5(_objectSpread$5(_objectSpread$5({}, message.constructor.sendOptions), typeof message.constructor.getSendOptions === 'function' ? message.constructor.getSendOptions(message) : {}), options), _transient = _message$constructor$["transient"], receipt = _message$constructor$.receipt, priority = _message$constructor$.priority, pushData = _message$constructor$.pushData, will = _message$constructor$.will;
  20270. if (receipt) {
  20271. if (this["transient"]) {
  20272. console.warn('receipt option is ignored as the conversation is transient.');
  20273. } else if (_transient) {
  20274. console.warn('receipt option is ignored as the message is sent transiently.');
  20275. } else if (this.members.length > 2) {
  20276. console.warn('receipt option is recommended to be used in one-on-one conversation.'); // eslint-disable-line max-len
  20277. }
  20278. }
  20279. if (priority && !this["transient"]) {
  20280. console.warn('priority option is ignored as the conversation is not transient.');
  20281. }
  20282. Object.assign(message, {
  20283. cid: this.id,
  20284. from: this._client.id
  20285. });
  20286. message._setStatus(MessageStatus.SENDING);
  20287. _serializeMessage = serializeMessage(message), msg = _serializeMessage.msg, binaryMsg = _serializeMessage.binaryMsg;
  20288. command = new GenericCommand({
  20289. cmd: 'direct',
  20290. directMessage: new DirectCommand({
  20291. msg: msg,
  20292. binaryMsg: binaryMsg,
  20293. cid: this.id,
  20294. r: receipt,
  20295. "transient": _transient,
  20296. dt: message.id,
  20297. pushData: JSON.stringify(pushData),
  20298. will: will,
  20299. mentionPids: message.mentionList,
  20300. mentionAll: message.mentionedAll
  20301. }),
  20302. priority: priority
  20303. });
  20304. _context.prev = 10;
  20305. _context.next = 13;
  20306. return this._send(command);
  20307. case 13:
  20308. resCommand = _context.sent;
  20309. _resCommand$ackMessag = resCommand.ackMessage, uid = _resCommand$ackMessag.uid, t = _resCommand$ackMessag.t, code = _resCommand$ackMessag.code, reason = _resCommand$ackMessag.reason, appCode = _resCommand$ackMessag.appCode;
  20310. if (!(code !== null)) {
  20311. _context.next = 17;
  20312. break;
  20313. }
  20314. throw createError({
  20315. code: code,
  20316. reason: reason,
  20317. appCode: appCode
  20318. });
  20319. case 17:
  20320. Object.assign(message, {
  20321. id: uid,
  20322. timestamp: t
  20323. });
  20324. if (!_transient) {
  20325. this.lastMessage = message;
  20326. this.lastMessageAt = message.timestamp;
  20327. }
  20328. message._setStatus(MessageStatus.SENT);
  20329. if (receipt) {
  20330. internal(this).messagesWaitingForReceipt[message.id] = message;
  20331. }
  20332. return _context.abrupt("return", message);
  20333. case 24:
  20334. _context.prev = 24;
  20335. _context.t0 = _context["catch"](10);
  20336. message._setStatus(MessageStatus.FAILED);
  20337. throw _context.t0;
  20338. case 28:
  20339. case "end":
  20340. return _context.stop();
  20341. }
  20342. }
  20343. }, _callee, this, [[10, 24]]);
  20344. }));
  20345. function send(_x, _x2) {
  20346. return _send2.apply(this, arguments);
  20347. }
  20348. return send;
  20349. }();
  20350. _proto._update = /*#__PURE__*/function () {
  20351. var _update2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message, newMessage, recall) {
  20352. var msg, binaryMsg, content, id, cid, timestamp, from, _status;
  20353. return regenerator.wrap(function _callee2$(_context2) {
  20354. while (1) {
  20355. switch (_context2.prev = _context2.next) {
  20356. case 0:
  20357. this._debug('patch %O %O %O', message, newMessage, recall);
  20358. if (!(message instanceof Message)) {
  20359. _context2.next = 8;
  20360. break;
  20361. }
  20362. if (!(message.from !== this._client.id)) {
  20363. _context2.next = 4;
  20364. break;
  20365. }
  20366. throw new Error('Updating message from others is not allowed');
  20367. case 4:
  20368. if (!(message.status !== MessageStatus.SENT && message.status !== MessageStatus.DELIVERED)) {
  20369. _context2.next = 6;
  20370. break;
  20371. }
  20372. throw new Error('Message is not sent');
  20373. case 6:
  20374. _context2.next = 10;
  20375. break;
  20376. case 8:
  20377. if (message.id && message.timestamp) {
  20378. _context2.next = 10;
  20379. break;
  20380. }
  20381. throw new TypeError("".concat(message, " is not a Message"));
  20382. case 10:
  20383. if (!recall) {
  20384. content = serializeMessage(newMessage);
  20385. msg = content.msg;
  20386. binaryMsg = content.binaryMsg;
  20387. }
  20388. _context2.next = 13;
  20389. return this._send(new GenericCommand({
  20390. cmd: CommandType.patch,
  20391. op: OpType.modify,
  20392. patchMessage: new PatchCommand({
  20393. patches: [new PatchItem({
  20394. cid: this.id,
  20395. mid: message.id,
  20396. timestamp: Number(message.timestamp),
  20397. recall: recall,
  20398. data: msg,
  20399. binaryMsg: binaryMsg,
  20400. mentionPids: newMessage.mentionList,
  20401. mentionAll: newMessage.mentionedAll
  20402. })],
  20403. lastPatchTime: this._client._lastPatchTime
  20404. })
  20405. }));
  20406. case 13:
  20407. id = message.id, cid = message.cid, timestamp = message.timestamp, from = message.from, _status = message._status;
  20408. Object.assign(newMessage, {
  20409. id: id,
  20410. cid: cid,
  20411. timestamp: timestamp,
  20412. from: from,
  20413. _status: _status
  20414. });
  20415. if (this.lastMessage && this.lastMessage.id === newMessage.id) {
  20416. this.lastMessage = newMessage;
  20417. }
  20418. return _context2.abrupt("return", newMessage);
  20419. case 17:
  20420. case "end":
  20421. return _context2.stop();
  20422. }
  20423. }
  20424. }, _callee2, this);
  20425. }));
  20426. function _update(_x3, _x4, _x5) {
  20427. return _update2.apply(this, arguments);
  20428. }
  20429. return _update;
  20430. }()
  20431. /**
  20432. * 获取对话人数,或暂态对话的在线人数
  20433. * @return {Promise.<Number>}
  20434. */
  20435. ;
  20436. _proto.count =
  20437. /*#__PURE__*/
  20438. function () {
  20439. var _count = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
  20440. var resCommand;
  20441. return regenerator.wrap(function _callee3$(_context3) {
  20442. while (1) {
  20443. switch (_context3.prev = _context3.next) {
  20444. case 0:
  20445. this._debug('count');
  20446. _context3.next = 3;
  20447. return this._send(new GenericCommand({
  20448. op: 'count'
  20449. }));
  20450. case 3:
  20451. resCommand = _context3.sent;
  20452. return _context3.abrupt("return", resCommand.convMessage.count);
  20453. case 5:
  20454. case "end":
  20455. return _context3.stop();
  20456. }
  20457. }
  20458. }, _callee3, this);
  20459. }));
  20460. function count() {
  20461. return _count.apply(this, arguments);
  20462. }
  20463. return count;
  20464. }()
  20465. /**
  20466. * 应用增加成员的操作,产生副作用
  20467. * @param {string[]} members
  20468. * @abstract
  20469. * @private
  20470. */
  20471. ;
  20472. _proto._addMembers = function _addMembers() {}
  20473. /**
  20474. * 应用减少成员的操作,产生副作用
  20475. * @param {string[]} members
  20476. * @abstract
  20477. * @private
  20478. */
  20479. ;
  20480. _proto._removeMembers = function _removeMembers() {}
  20481. /**
  20482. * 修改已发送的消息
  20483. * @param {AVMessage} message 要修改的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
  20484. * @param {AVMessage} newMessage 新的消息
  20485. * @return {Promise.<AVMessage>} 更新后的消息
  20486. */
  20487. ;
  20488. _proto.update =
  20489. /*#__PURE__*/
  20490. function () {
  20491. var _update3 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message, newMessage) {
  20492. return regenerator.wrap(function _callee4$(_context4) {
  20493. while (1) {
  20494. switch (_context4.prev = _context4.next) {
  20495. case 0:
  20496. if (newMessage instanceof Message) {
  20497. _context4.next = 2;
  20498. break;
  20499. }
  20500. throw new TypeError("".concat(newMessage, " is not a Message"));
  20501. case 2:
  20502. return _context4.abrupt("return", this._update(message, newMessage, false));
  20503. case 3:
  20504. case "end":
  20505. return _context4.stop();
  20506. }
  20507. }
  20508. }, _callee4, this);
  20509. }));
  20510. function update(_x6, _x7) {
  20511. return _update3.apply(this, arguments);
  20512. }
  20513. return update;
  20514. }()
  20515. /**
  20516. * 撤回已发送的消息
  20517. * @param {AVMessage} message 要撤回的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
  20518. * @return {Promise.<RecalledMessage>} 一条已撤回的消息
  20519. */
  20520. ;
  20521. _proto.recall =
  20522. /*#__PURE__*/
  20523. function () {
  20524. var _recall = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(message) {
  20525. return regenerator.wrap(function _callee5$(_context5) {
  20526. while (1) {
  20527. switch (_context5.prev = _context5.next) {
  20528. case 0:
  20529. return _context5.abrupt("return", this._update(message, new RecalledMessage(), true));
  20530. case 1:
  20531. case "end":
  20532. return _context5.stop();
  20533. }
  20534. }
  20535. }, _callee5, this);
  20536. }));
  20537. function recall(_x8) {
  20538. return _recall.apply(this, arguments);
  20539. }
  20540. return recall;
  20541. }()
  20542. /**
  20543. * 查询消息记录
  20544. * 如果仅需实现消息向前记录翻页查询需求,建议使用 {@link Conversation#createMessagesIterator}。
  20545. * 不论何种方向,获得的消息都是按照时间升序排列的。
  20546. * startClosed 与 endClosed 用于指定查询区间的开闭。
  20547. *
  20548. * @param {Object} [options]
  20549. * @param {Number} [options.limit] 限制查询结果的数量,目前服务端默认为 20
  20550. * @param {Number} [options.type] 指定查询的富媒体消息类型,不指定则查询所有消息。
  20551. * @param {MessageQueryDirection} [options.direction] 查询的方向。
  20552. * 在不指定的情况下如果 startTime 大于 endTime,则为从新到旧查询,可以实现加载聊天记录等场景。
  20553. * 如果 startTime 小于 endTime,则为从旧到新查询,可以实现弹幕等场景。
  20554. * @param {Date} [options.startTime] 从该时间开始查询,不传则从当前时间开始查询
  20555. * @param {String} [options.startMessageId] 从该消息之前开始查询,需要与 startTime 同时使用,为防止某时刻有重复消息
  20556. * @param {Boolean}[options.startClosed] 指定查询范围是否包括开始的时间点,默认不包括
  20557. * @param {Date} [options.endTime] 查询到该时间为止,不传则查询最早消息为止
  20558. * @param {String} [options.endMessageId] 查询到该消息为止,需要与 endTime 同时使用,为防止某时刻有重复消息
  20559. * @param {Boolean}[options.endClosed] 指定查询范围是否包括结束的时间点,默认不包括
  20560. *
  20561. * @param {Date} [options.beforeTime] DEPRECATED: 使用 startTime 代替。限制查询结果为小于该时间之前的消息,不传则为当前时间
  20562. * @param {String} [options.beforeMessageId] DEPRECATED: 使用 startMessageId 代替。
  20563. * 限制查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
  20564. * @param {Date} [options.afterTime] DEPRECATED: 使用 endTime 代替。限制查询结果为大于该时间之前的消息
  20565. * @param {String} [options.afterMessageId] DEPRECATED: 使用 endMessageId 代替。
  20566. * 限制查询结果为该消息之后的消息,需要与 afterTime 同时使用,为防止某时刻有重复消息
  20567. * @return {Promise.<Message[]>} 消息列表
  20568. */
  20569. ;
  20570. _proto.queryMessages =
  20571. /*#__PURE__*/
  20572. function () {
  20573. var _queryMessages = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7() {
  20574. var _this2 = this;
  20575. var options,
  20576. beforeTime,
  20577. beforeMessageId,
  20578. afterTime,
  20579. afterMessageId,
  20580. limit,
  20581. direction,
  20582. type,
  20583. startTime,
  20584. startMessageId,
  20585. startClosed,
  20586. endTime,
  20587. endMessageId,
  20588. endClosed,
  20589. conditions,
  20590. resCommand,
  20591. _args7 = arguments;
  20592. return regenerator.wrap(function _callee7$(_context7) {
  20593. while (1) {
  20594. switch (_context7.prev = _context7.next) {
  20595. case 0:
  20596. options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
  20597. this._debug('query messages %O', options);
  20598. beforeTime = options.beforeTime, beforeMessageId = options.beforeMessageId, afterTime = options.afterTime, afterMessageId = options.afterMessageId, limit = options.limit, direction = options.direction, type = options.type, startTime = options.startTime, startMessageId = options.startMessageId, startClosed = options.startClosed, endTime = options.endTime, endMessageId = options.endMessageId, endClosed = options.endClosed;
  20599. if (!(beforeMessageId || beforeTime || afterMessageId || afterTime)) {
  20600. _context7.next = 6;
  20601. break;
  20602. }
  20603. console.warn('DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId.');
  20604. return _context7.abrupt("return", this.queryMessages({
  20605. startTime: beforeTime,
  20606. startMessageId: beforeMessageId,
  20607. endTime: afterTime,
  20608. endMessageId: afterMessageId,
  20609. limit: limit
  20610. }));
  20611. case 6:
  20612. if (!(startMessageId && !startTime)) {
  20613. _context7.next = 8;
  20614. break;
  20615. }
  20616. throw new Error('query option startMessageId must be used with option startTime');
  20617. case 8:
  20618. if (!(endMessageId && !endTime)) {
  20619. _context7.next = 10;
  20620. break;
  20621. }
  20622. throw new Error('query option endMessageId must be used with option endTime');
  20623. case 10:
  20624. conditions = {
  20625. t: startTime,
  20626. mid: startMessageId,
  20627. tIncluded: startClosed,
  20628. tt: endTime,
  20629. tmid: endMessageId,
  20630. ttIncluded: endClosed,
  20631. l: limit,
  20632. lctype: type
  20633. };
  20634. if (conditions.t instanceof Date) {
  20635. conditions.t = conditions.t.getTime();
  20636. }
  20637. if (conditions.tt instanceof Date) {
  20638. conditions.tt = conditions.tt.getTime();
  20639. }
  20640. if (direction !== undefined) {
  20641. conditions.direction = direction;
  20642. } else if (conditions.tt > conditions.t) {
  20643. conditions.direction = MessageQueryDirection.OLD_TO_NEW;
  20644. }
  20645. _context7.next = 16;
  20646. return this._send(new GenericCommand({
  20647. cmd: 'logs',
  20648. logsMessage: new LogsCommand(Object.assign(conditions, {
  20649. cid: this.id
  20650. }))
  20651. }));
  20652. case 16:
  20653. resCommand = _context7.sent;
  20654. return _context7.abrupt("return", Promise.all(resCommand.logsMessage.logs.map( /*#__PURE__*/function () {
  20655. var _ref3 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(_ref2) {
  20656. var msgId, timestamp, patchTimestamp, from, ackAt, readAt, data, mentionAll, mentionPids, bin, messageData, message, status;
  20657. return regenerator.wrap(function _callee6$(_context6) {
  20658. while (1) {
  20659. switch (_context6.prev = _context6.next) {
  20660. case 0:
  20661. msgId = _ref2.msgId, timestamp = _ref2.timestamp, patchTimestamp = _ref2.patchTimestamp, from = _ref2.from, ackAt = _ref2.ackAt, readAt = _ref2.readAt, data = _ref2.data, mentionAll = _ref2.mentionAll, mentionPids = _ref2.mentionPids, bin = _ref2.bin;
  20662. messageData = {
  20663. data: data,
  20664. bin: bin,
  20665. id: msgId,
  20666. cid: _this2.id,
  20667. timestamp: timestamp,
  20668. from: from,
  20669. deliveredAt: ackAt,
  20670. updatedAt: patchTimestamp,
  20671. mentionList: mentionPids,
  20672. mentionedAll: mentionAll
  20673. };
  20674. _context6.next = 4;
  20675. return _this2._client.parseMessage(messageData);
  20676. case 4:
  20677. message = _context6.sent;
  20678. status = MessageStatus.SENT;
  20679. if (_this2.members.length === 2) {
  20680. if (ackAt) status = MessageStatus.DELIVERED;
  20681. if (ackAt) _this2._setLastDeliveredAt(ackAt);
  20682. if (readAt) _this2._setLastReadAt(readAt);
  20683. }
  20684. message._setStatus(status);
  20685. return _context6.abrupt("return", message);
  20686. case 9:
  20687. case "end":
  20688. return _context6.stop();
  20689. }
  20690. }
  20691. }, _callee6);
  20692. }));
  20693. return function (_x9) {
  20694. return _ref3.apply(this, arguments);
  20695. };
  20696. }())));
  20697. case 18:
  20698. case "end":
  20699. return _context7.stop();
  20700. }
  20701. }
  20702. }, _callee7, this);
  20703. }));
  20704. function queryMessages() {
  20705. return _queryMessages.apply(this, arguments);
  20706. }
  20707. return queryMessages;
  20708. }()
  20709. /**
  20710. * 获取消息翻页迭代器
  20711. * @param {Object} [options]
  20712. * @param {Date} [options.beforeTime] 限制起始查询结果为小于该时间之前的消息,不传则为当前时间
  20713. * @param {String} [options.beforeMessageId] 限制起始查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
  20714. * @param {Number} [options.limit] 限制每页查询结果的数量,目前服务端默认为 20
  20715. * @return {AsyncIterater.<Promise.<IteratorResult<Message[]>>>} [AsyncIterator]{@link https://github.com/tc39/proposal-async-iteration},调用其 next 方法返回获取下一页消息的 Promise
  20716. * @example
  20717. * var messageIterator = conversation.createMessagesIterator({ limit: 10 });
  20718. * messageIterator.next().then(function(result) {
  20719. * // result: {
  20720. * // value: [message1, ..., message10],
  20721. * // done: false,
  20722. * // }
  20723. * });
  20724. * messageIterator.next().then(function(result) {
  20725. * // result: {
  20726. * // value: [message11, ..., message20],
  20727. * // done: false,
  20728. * // }
  20729. * });
  20730. * messageIterator.next().then(function(result) {
  20731. * // No more messages
  20732. * // result: { value: [], done: true }
  20733. * });
  20734. */
  20735. ;
  20736. _proto.createMessagesIterator = function createMessagesIterator() {
  20737. var _this3 = this;
  20738. var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  20739. beforeTime = _ref4.beforeTime,
  20740. beforeMessageId = _ref4.beforeMessageId,
  20741. limit = _ref4.limit;
  20742. var promise;
  20743. return {
  20744. next: function next() {
  20745. if (promise === undefined) {
  20746. // first call
  20747. promise = _this3.queryMessages({
  20748. limit: limit,
  20749. startTime: beforeTime,
  20750. startMessageId: beforeMessageId
  20751. });
  20752. } else {
  20753. promise = promise.then(function (prevMessages) {
  20754. if (prevMessages.length === 0 || prevMessages.length < limit) {
  20755. // no more messages
  20756. return [];
  20757. }
  20758. return _this3.queryMessages({
  20759. startTime: prevMessages[0].timestamp,
  20760. startMessageId: prevMessages[0].id,
  20761. limit: limit
  20762. });
  20763. });
  20764. }
  20765. return promise.then(function (value) {
  20766. return {
  20767. value: Array.from(value),
  20768. done: value.length === 0 || value.length < limit
  20769. };
  20770. });
  20771. }
  20772. };
  20773. }
  20774. /**
  20775. * 将该会话标记为已读
  20776. * @return {Promise.<this>} self
  20777. */
  20778. ;
  20779. _proto.read =
  20780. /*#__PURE__*/
  20781. function () {
  20782. var _read = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() {
  20783. var client;
  20784. return regenerator.wrap(function _callee8$(_context8) {
  20785. while (1) {
  20786. switch (_context8.prev = _context8.next) {
  20787. case 0:
  20788. this.unreadMessagesCount = 0;
  20789. this._setUnreadMessagesMentioned(false); // 跳过暂态会话
  20790. if (!this["transient"]) {
  20791. _context8.next = 4;
  20792. break;
  20793. }
  20794. return _context8.abrupt("return", this);
  20795. case 4:
  20796. client = this._client;
  20797. if (!internal(client).readConversationsBuffer) {
  20798. internal(client).readConversationsBuffer = new Set();
  20799. }
  20800. internal(client).readConversationsBuffer.add(this);
  20801. client._doSendRead();
  20802. return _context8.abrupt("return", this);
  20803. case 9:
  20804. case "end":
  20805. return _context8.stop();
  20806. }
  20807. }
  20808. }, _callee8, this);
  20809. }));
  20810. function read() {
  20811. return _read.apply(this, arguments);
  20812. }
  20813. return read;
  20814. }();
  20815. _proto._handleReceipt = function _handleReceipt(_ref5) {
  20816. var messageId = _ref5.messageId,
  20817. timestamp = _ref5.timestamp,
  20818. read = _ref5.read;
  20819. if (read) {
  20820. this._setLastReadAt(timestamp);
  20821. } else {
  20822. this._setLastDeliveredAt(timestamp);
  20823. }
  20824. var _internal = internal(this),
  20825. messagesWaitingForReceipt = _internal.messagesWaitingForReceipt;
  20826. var message = messagesWaitingForReceipt[messageId];
  20827. if (!message) return;
  20828. message._setStatus(MessageStatus.DELIVERED);
  20829. message.deliveredAt = timestamp;
  20830. delete messagesWaitingForReceipt[messageId];
  20831. }
  20832. /**
  20833. * 更新对话的最新回执时间戳(lastDeliveredAt、lastReadAt)
  20834. * @since 3.4.0
  20835. * @return {Promise.<this>} this
  20836. */
  20837. ;
  20838. _proto.fetchReceiptTimestamps =
  20839. /*#__PURE__*/
  20840. function () {
  20841. var _fetchReceiptTimestamps = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
  20842. var _yield$this$_send, _yield$this$_send$con, maxReadTimestamp, maxAckTimestamp;
  20843. return regenerator.wrap(function _callee9$(_context9) {
  20844. while (1) {
  20845. switch (_context9.prev = _context9.next) {
  20846. case 0:
  20847. if (!(this["transient"] || this.system)) {
  20848. _context9.next = 2;
  20849. break;
  20850. }
  20851. return _context9.abrupt("return", this);
  20852. case 2:
  20853. _context9.next = 4;
  20854. return this._send(new GenericCommand({
  20855. op: 'max_read'
  20856. }));
  20857. case 4:
  20858. _yield$this$_send = _context9.sent;
  20859. _yield$this$_send$con = _yield$this$_send.convMessage;
  20860. maxReadTimestamp = _yield$this$_send$con.maxReadTimestamp;
  20861. maxAckTimestamp = _yield$this$_send$con.maxAckTimestamp;
  20862. this._setLastDeliveredAt(maxAckTimestamp);
  20863. this._setLastReadAt(maxReadTimestamp);
  20864. return _context9.abrupt("return", this);
  20865. case 11:
  20866. case "end":
  20867. return _context9.stop();
  20868. }
  20869. }
  20870. }, _callee9, this);
  20871. }));
  20872. function fetchReceiptTimestamps() {
  20873. return _fetchReceiptTimestamps.apply(this, arguments);
  20874. }
  20875. return fetchReceiptTimestamps;
  20876. }();
  20877. _proto._fetchAllReceiptTimestamps = function _fetchAllReceiptTimestamps() {
  20878. // 暂态/系统会话不支持回执
  20879. if (this["transient"] || this.system) return this;
  20880. var convMessage = new ConvCommand({
  20881. queryAllMembers: true
  20882. });
  20883. return this._send(new GenericCommand({
  20884. op: 'max_read',
  20885. convMessage: convMessage
  20886. })).then(function (_ref6) {
  20887. var maxReadTuples = _ref6.convMessage.maxReadTuples;
  20888. return maxReadTuples.filter(function (maxReadTuple) {
  20889. return maxReadTuple.maxAckTimestamp || maxReadTuple.maxReadTimestamp;
  20890. }).map(function (_ref7) {
  20891. var pid = _ref7.pid,
  20892. maxAckTimestamp = _ref7.maxAckTimestamp,
  20893. maxReadTimestamp = _ref7.maxReadTimestamp;
  20894. return {
  20895. pid: pid,
  20896. lastDeliveredAt: decodeDate(maxAckTimestamp),
  20897. lastReadAt: decodeDate(maxReadTimestamp)
  20898. };
  20899. });
  20900. });
  20901. };
  20902. createClass(ConversationBase, [{
  20903. key: "unreadMessagesMentioned",
  20904. get: function get() {
  20905. return internal(this).unreadMessagesMentioned;
  20906. }
  20907. }, {
  20908. key: "unreadMessagesCount",
  20909. set: function set(value) {
  20910. if (value !== this.unreadMessagesCount) {
  20911. internal(this).unreadMessagesCount = value;
  20912. this._client.emit(UNREAD_MESSAGES_COUNT_UPDATE, [this]);
  20913. }
  20914. }
  20915. /**
  20916. * 当前用户在该对话的未读消息数
  20917. * @type {Number}
  20918. */
  20919. ,
  20920. get: function get() {
  20921. return internal(this).unreadMessagesCount;
  20922. }
  20923. }, {
  20924. key: "lastMessageAt",
  20925. set: function set(value) {
  20926. var time = decodeDate(value);
  20927. if (time <= this._lastMessageAt) return;
  20928. this._lastMessageAt = time;
  20929. },
  20930. get: function get() {
  20931. return this._lastMessageAt;
  20932. }
  20933. /**
  20934. * 最后消息送达时间,常用来实现消息的「已送达」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
  20935. * @type {?Date}
  20936. * @since 3.4.0
  20937. */
  20938. }, {
  20939. key: "lastDeliveredAt",
  20940. get: function get() {
  20941. if (this.members.length !== 2) return null;
  20942. return internal(this).lastDeliveredAt;
  20943. }
  20944. }, {
  20945. key: "lastReadAt",
  20946. get: function get() {
  20947. if (this.members.length !== 2) return null;
  20948. return internal(this).lastReadAt;
  20949. }
  20950. }]);
  20951. return ConversationBase;
  20952. }(eventemitter3);
  20953. var debug$8 = browser('LC:SignatureFactoryRunner');
  20954. function _validateSignature() {
  20955. var signatureResult = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  20956. var signature = signatureResult.signature,
  20957. timestamp = signatureResult.timestamp,
  20958. nonce = signatureResult.nonce;
  20959. if (typeof signature !== 'string' || typeof timestamp !== 'number' || typeof nonce !== 'string') {
  20960. throw new Error('malformed signature');
  20961. }
  20962. return {
  20963. signature: signature,
  20964. timestamp: timestamp,
  20965. nonce: nonce
  20966. };
  20967. }
  20968. var runSignatureFactory = (function (signatureFactory, params) {
  20969. return Promise.resolve().then(function () {
  20970. debug$8('call signatureFactory with %O', params);
  20971. return signatureFactory.apply(void 0, toConsumableArray(params));
  20972. }).then(tap(function (signatureResult) {
  20973. return debug$8('sign result %O', signatureResult);
  20974. }), function (error) {
  20975. // eslint-disable-next-line no-param-reassign
  20976. error.message = "sign error: ".concat(error.message);
  20977. debug$8(error);
  20978. throw error;
  20979. }).then(_validateSignature);
  20980. });
  20981. function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  20982. function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  20983. /**
  20984. * 部分失败异常
  20985. * @typedef OperationFailureError
  20986. * @type {Error}
  20987. * @property {string} message 异常信息
  20988. * @property {string[]} clientIds 因为该原因失败的 client id 列表
  20989. * @property {number} [code] 错误码
  20990. * @property {string} [detail] 详细信息
  20991. */
  20992. /**
  20993. * 部分成功的结果
  20994. * @typedef PartiallySuccess
  20995. * @type {Object}
  20996. * @property {string[]} successfulClientIds 成功的 client id 列表
  20997. * @property {OperationFailureError[]} failures 失败的异常列表
  20998. */
  20999. /**
  21000. * 分页查询结果
  21001. * @typedef PagedResults
  21002. * @type {Object}
  21003. * @property {T[]} results 查询结果
  21004. * @property {string} [next] 存在表示还有更多结果,在下次查询中带上可实现翻页。
  21005. */
  21006. var createPartiallySuccess = function createPartiallySuccess(_ref) {
  21007. var allowedPids = _ref.allowedPids,
  21008. failedPids = _ref.failedPids;
  21009. return {
  21010. successfulClientIds: allowedPids,
  21011. failures: failedPids.map(function (_ref2) {
  21012. var pids = _ref2.pids,
  21013. error = objectWithoutProperties(_ref2, ["pids"]);
  21014. return Object.assign(createError(error), {
  21015. clientIds: pids
  21016. });
  21017. })
  21018. };
  21019. };
  21020. /**
  21021. * @extends ConversationBase
  21022. * @private
  21023. * @abstract
  21024. */
  21025. var PersistentConversation = /*#__PURE__*/function (_ConversationBase) {
  21026. inheritsLoose(PersistentConversation, _ConversationBase);
  21027. function PersistentConversation(data, _ref3, client) {
  21028. var _this;
  21029. var creator = _ref3.creator,
  21030. createdAt = _ref3.createdAt,
  21031. updatedAt = _ref3.updatedAt,
  21032. _ref3$transient = _ref3["transient"],
  21033. _transient = _ref3$transient === void 0 ? false : _ref3$transient,
  21034. _ref3$system = _ref3.system,
  21035. system = _ref3$system === void 0 ? false : _ref3$system,
  21036. _ref3$muted = _ref3.muted,
  21037. muted = _ref3$muted === void 0 ? false : _ref3$muted,
  21038. _ref3$mutedMembers = _ref3.mutedMembers,
  21039. mutedMembers = _ref3$mutedMembers === void 0 ? [] : _ref3$mutedMembers,
  21040. attributes = objectWithoutProperties(_ref3, ["creator", "createdAt", "updatedAt", "transient", "system", "muted", "mutedMembers"]);
  21041. _this = _ConversationBase.call(this, _objectSpread$6(_objectSpread$6({}, data), {}, {
  21042. /**
  21043. * 对话创建者
  21044. * @memberof PersistentConversation#
  21045. * @type {String}
  21046. */
  21047. creator: creator,
  21048. /**
  21049. * 对话创建时间
  21050. * @memberof PersistentConversation#
  21051. * @type {Date}
  21052. */
  21053. createdAt: createdAt,
  21054. /**
  21055. * 对话更新时间
  21056. * @memberof PersistentConversation#
  21057. * @type {Date}
  21058. */
  21059. updatedAt: updatedAt,
  21060. /**
  21061. * 对该对话设置了静音的用户列表
  21062. * @memberof PersistentConversation#
  21063. * @type {?String[]}
  21064. */
  21065. mutedMembers: mutedMembers,
  21066. /**
  21067. * 暂态对话标记
  21068. * @memberof PersistentConversation#
  21069. * @type {Boolean}
  21070. */
  21071. "transient": _transient,
  21072. /**
  21073. * 系统对话标记
  21074. * @memberof PersistentConversation#
  21075. * @type {Boolean}
  21076. * @since 3.3.0
  21077. */
  21078. system: system,
  21079. /**
  21080. * 当前用户静音该对话标记
  21081. * @memberof PersistentConversation#
  21082. * @type {Boolean}
  21083. */
  21084. muted: muted,
  21085. _attributes: attributes
  21086. }), client) || this;
  21087. _this._reset();
  21088. return _this;
  21089. }
  21090. var _proto = PersistentConversation.prototype;
  21091. /**
  21092. * 获取对话的自定义属性
  21093. * @since 3.2.0
  21094. * @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
  21095. * @return {Any} 属性的值
  21096. */
  21097. _proto.get = function get(key) {
  21098. return get_1(internal(this).currentAttributes, key);
  21099. }
  21100. /**
  21101. * 设置对话的自定义属性
  21102. * @since 3.2.0
  21103. * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
  21104. * @param {Any} value 属性的值
  21105. * @return {this} self
  21106. * @example
  21107. *
  21108. * // 设置对话的 color 属性
  21109. * conversation.set('color', {
  21110. * text: '#000',
  21111. * background: '#DDD',
  21112. * });
  21113. * // 设置对话的 color.text 属性
  21114. * conversation.set('color.text', '#333');
  21115. */
  21116. ;
  21117. _proto.set = function set(key, value) {
  21118. this._debug("set [".concat(key, "]: ").concat(value));
  21119. var _internal = internal(this),
  21120. pendingAttributes = _internal.pendingAttributes;
  21121. var pendingKeys = Object.keys(pendingAttributes); // suppose pendingAttributes = { 'a.b': {} }
  21122. // set 'a' or 'a.b': delete 'a.b'
  21123. var re = new RegExp("^".concat(key));
  21124. var childKeys = pendingKeys.filter(re.test.bind(re));
  21125. childKeys.forEach(function (k) {
  21126. delete pendingAttributes[k];
  21127. });
  21128. if (childKeys.length) {
  21129. pendingAttributes[key] = value;
  21130. } else {
  21131. // set 'a.c': nothing to do
  21132. // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
  21133. var parentKey = find_1(pendingKeys, function (k) {
  21134. return key.indexOf(k) === 0;
  21135. }); // 'a.b'
  21136. if (parentKey) {
  21137. setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
  21138. } else {
  21139. pendingAttributes[key] = value;
  21140. }
  21141. }
  21142. this._buildCurrentAttributes();
  21143. return this;
  21144. };
  21145. _proto._buildCurrentAttributes = function _buildCurrentAttributes() {
  21146. var _internal2 = internal(this),
  21147. pendingAttributes = _internal2.pendingAttributes;
  21148. internal(this).currentAttributes = Object.keys(pendingAttributes).reduce(function (target, k) {
  21149. return setValue(target, k, pendingAttributes[k]);
  21150. }, cloneDeep_1(this._attributes));
  21151. };
  21152. _proto._updateServerAttributes = function _updateServerAttributes(attributes) {
  21153. var _this2 = this;
  21154. Object.keys(attributes).forEach(function (key) {
  21155. return setValue(_this2._attributes, key, attributes[key]);
  21156. });
  21157. this._buildCurrentAttributes();
  21158. };
  21159. _proto._reset = function _reset() {
  21160. Object.assign(internal(this), {
  21161. pendingAttributes: {},
  21162. currentAttributes: this._attributes
  21163. });
  21164. }
  21165. /**
  21166. * 保存当前对话的属性至服务器
  21167. * @return {Promise.<this>} self
  21168. */
  21169. ;
  21170. _proto.save =
  21171. /*#__PURE__*/
  21172. function () {
  21173. var _save = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
  21174. var attr, convMessage, resCommand;
  21175. return regenerator.wrap(function _callee$(_context) {
  21176. while (1) {
  21177. switch (_context.prev = _context.next) {
  21178. case 0:
  21179. this._debug('save');
  21180. attr = internal(this).pendingAttributes;
  21181. if (!isEmpty_1(attr)) {
  21182. _context.next = 5;
  21183. break;
  21184. }
  21185. this._debug('nothing touched, resolve with self');
  21186. return _context.abrupt("return", this);
  21187. case 5:
  21188. this._debug('attr: %O', attr);
  21189. convMessage = new ConvCommand({
  21190. attr: new JsonObjectMessage({
  21191. data: JSON.stringify(encode(attr))
  21192. })
  21193. });
  21194. _context.next = 9;
  21195. return this._send(new GenericCommand({
  21196. op: 'update',
  21197. convMessage: convMessage
  21198. }));
  21199. case 9:
  21200. resCommand = _context.sent;
  21201. this.updatedAt = resCommand.convMessage.udate;
  21202. this._attributes = internal(this).currentAttributes;
  21203. internal(this).pendingAttributes = {};
  21204. return _context.abrupt("return", this);
  21205. case 14:
  21206. case "end":
  21207. return _context.stop();
  21208. }
  21209. }
  21210. }, _callee, this);
  21211. }));
  21212. function save() {
  21213. return _save.apply(this, arguments);
  21214. }
  21215. return save;
  21216. }()
  21217. /**
  21218. * 从服务器更新对话的属性
  21219. * @return {Promise.<this>} self
  21220. */
  21221. ;
  21222. _proto.fetch =
  21223. /*#__PURE__*/
  21224. function () {
  21225. var _fetch = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  21226. var query;
  21227. return regenerator.wrap(function _callee2$(_context2) {
  21228. while (1) {
  21229. switch (_context2.prev = _context2.next) {
  21230. case 0:
  21231. query = this._client.getQuery().equalTo('objectId', this.id);
  21232. _context2.next = 3;
  21233. return query.find();
  21234. case 3:
  21235. return _context2.abrupt("return", this);
  21236. case 4:
  21237. case "end":
  21238. return _context2.stop();
  21239. }
  21240. }
  21241. }, _callee2, this);
  21242. }));
  21243. function fetch() {
  21244. return _fetch.apply(this, arguments);
  21245. }
  21246. return fetch;
  21247. }()
  21248. /**
  21249. * 静音,客户端拒绝收到服务器端的离线推送通知
  21250. * @return {Promise.<this>} self
  21251. */
  21252. ;
  21253. _proto.mute =
  21254. /*#__PURE__*/
  21255. function () {
  21256. var _mute = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
  21257. return regenerator.wrap(function _callee3$(_context3) {
  21258. while (1) {
  21259. switch (_context3.prev = _context3.next) {
  21260. case 0:
  21261. this._debug('mute');
  21262. _context3.next = 3;
  21263. return this._send(new GenericCommand({
  21264. op: 'mute'
  21265. }));
  21266. case 3:
  21267. if (!this["transient"]) {
  21268. this.muted = true;
  21269. this.mutedMembers = union(this.mutedMembers, [this._client.id]);
  21270. }
  21271. return _context3.abrupt("return", this);
  21272. case 5:
  21273. case "end":
  21274. return _context3.stop();
  21275. }
  21276. }
  21277. }, _callee3, this);
  21278. }));
  21279. function mute() {
  21280. return _mute.apply(this, arguments);
  21281. }
  21282. return mute;
  21283. }()
  21284. /**
  21285. * 取消静音
  21286. * @return {Promise.<this>} self
  21287. */
  21288. ;
  21289. _proto.unmute =
  21290. /*#__PURE__*/
  21291. function () {
  21292. var _unmute = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4() {
  21293. return regenerator.wrap(function _callee4$(_context4) {
  21294. while (1) {
  21295. switch (_context4.prev = _context4.next) {
  21296. case 0:
  21297. this._debug('unmute');
  21298. _context4.next = 3;
  21299. return this._send(new GenericCommand({
  21300. op: 'unmute'
  21301. }));
  21302. case 3:
  21303. if (!this["transient"]) {
  21304. this.muted = false;
  21305. this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
  21306. }
  21307. return _context4.abrupt("return", this);
  21308. case 5:
  21309. case "end":
  21310. return _context4.stop();
  21311. }
  21312. }
  21313. }, _callee4, this);
  21314. }));
  21315. function unmute() {
  21316. return _unmute.apply(this, arguments);
  21317. }
  21318. return unmute;
  21319. }();
  21320. _proto._appendConversationSignature = /*#__PURE__*/function () {
  21321. var _appendConversationSignature2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(command, action, clientIds) {
  21322. var params, signatureResult;
  21323. return regenerator.wrap(function _callee5$(_context5) {
  21324. while (1) {
  21325. switch (_context5.prev = _context5.next) {
  21326. case 0:
  21327. if (!this._client.options.conversationSignatureFactory) {
  21328. _context5.next = 6;
  21329. break;
  21330. }
  21331. params = [this.id, this._client.id, clientIds.sort(), action];
  21332. _context5.next = 4;
  21333. return runSignatureFactory(this._client.options.conversationSignatureFactory, params);
  21334. case 4:
  21335. signatureResult = _context5.sent;
  21336. Object.assign(command.convMessage, keyRemap({
  21337. signature: 's',
  21338. timestamp: 't',
  21339. nonce: 'n'
  21340. }, signatureResult));
  21341. case 6:
  21342. case "end":
  21343. return _context5.stop();
  21344. }
  21345. }
  21346. }, _callee5, this);
  21347. }));
  21348. function _appendConversationSignature(_x, _x2, _x3) {
  21349. return _appendConversationSignature2.apply(this, arguments);
  21350. }
  21351. return _appendConversationSignature;
  21352. }();
  21353. _proto._appendBlacklistSignature = /*#__PURE__*/function () {
  21354. var _appendBlacklistSignature2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(command, action, clientIds) {
  21355. var params, signatureResult;
  21356. return regenerator.wrap(function _callee6$(_context6) {
  21357. while (1) {
  21358. switch (_context6.prev = _context6.next) {
  21359. case 0:
  21360. if (!this._client.options.blacklistSignatureFactory) {
  21361. _context6.next = 6;
  21362. break;
  21363. }
  21364. params = [this.id, this._client.id, clientIds.sort(), action];
  21365. _context6.next = 4;
  21366. return runSignatureFactory(this._client.options.blacklistSignatureFactory, params);
  21367. case 4:
  21368. signatureResult = _context6.sent;
  21369. Object.assign(command.blacklistMessage, keyRemap({
  21370. signature: 's',
  21371. timestamp: 't',
  21372. nonce: 'n'
  21373. }, signatureResult));
  21374. case 6:
  21375. case "end":
  21376. return _context6.stop();
  21377. }
  21378. }
  21379. }, _callee6, this);
  21380. }));
  21381. function _appendBlacklistSignature(_x4, _x5, _x6) {
  21382. return _appendBlacklistSignature2.apply(this, arguments);
  21383. }
  21384. return _appendBlacklistSignature;
  21385. }()
  21386. /**
  21387. * 增加成员
  21388. * @param {String|String[]} clientIds 新增成员 client id
  21389. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21390. */
  21391. ;
  21392. _proto.add =
  21393. /*#__PURE__*/
  21394. function () {
  21395. var _add = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(clientIds) {
  21396. var command, _yield$this$_send, convMessage, allowedPids;
  21397. return regenerator.wrap(function _callee7$(_context7) {
  21398. while (1) {
  21399. switch (_context7.prev = _context7.next) {
  21400. case 0:
  21401. this._debug('add', clientIds);
  21402. if (typeof clientIds === 'string') {
  21403. clientIds = [clientIds]; // eslint-disable-line no-param-reassign
  21404. }
  21405. command = new GenericCommand({
  21406. op: 'add',
  21407. convMessage: new ConvCommand({
  21408. m: clientIds
  21409. })
  21410. });
  21411. _context7.next = 5;
  21412. return this._appendConversationSignature(command, 'invite', clientIds);
  21413. case 5:
  21414. _context7.next = 7;
  21415. return this._send(command);
  21416. case 7:
  21417. _yield$this$_send = _context7.sent;
  21418. convMessage = _yield$this$_send.convMessage;
  21419. allowedPids = _yield$this$_send.convMessage.allowedPids;
  21420. this._addMembers(allowedPids);
  21421. return _context7.abrupt("return", createPartiallySuccess(convMessage));
  21422. case 12:
  21423. case "end":
  21424. return _context7.stop();
  21425. }
  21426. }
  21427. }, _callee7, this);
  21428. }));
  21429. function add(_x7) {
  21430. return _add.apply(this, arguments);
  21431. }
  21432. return add;
  21433. }()
  21434. /**
  21435. * 剔除成员
  21436. * @param {String|String[]} clientIds 成员 client id
  21437. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21438. */
  21439. ;
  21440. _proto.remove =
  21441. /*#__PURE__*/
  21442. function () {
  21443. var _remove = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(clientIds) {
  21444. var command, _yield$this$_send2, convMessage, allowedPids;
  21445. return regenerator.wrap(function _callee8$(_context8) {
  21446. while (1) {
  21447. switch (_context8.prev = _context8.next) {
  21448. case 0:
  21449. this._debug('remove', clientIds);
  21450. if (typeof clientIds === 'string') {
  21451. clientIds = [clientIds]; // eslint-disable-line no-param-reassign
  21452. }
  21453. command = new GenericCommand({
  21454. op: 'remove',
  21455. convMessage: new ConvCommand({
  21456. m: clientIds
  21457. })
  21458. });
  21459. _context8.next = 5;
  21460. return this._appendConversationSignature(command, 'kick', clientIds);
  21461. case 5:
  21462. _context8.next = 7;
  21463. return this._send(command);
  21464. case 7:
  21465. _yield$this$_send2 = _context8.sent;
  21466. convMessage = _yield$this$_send2.convMessage;
  21467. allowedPids = _yield$this$_send2.convMessage.allowedPids;
  21468. this._removeMembers(allowedPids);
  21469. return _context8.abrupt("return", createPartiallySuccess(convMessage));
  21470. case 12:
  21471. case "end":
  21472. return _context8.stop();
  21473. }
  21474. }
  21475. }, _callee8, this);
  21476. }));
  21477. function remove(_x8) {
  21478. return _remove.apply(this, arguments);
  21479. }
  21480. return remove;
  21481. }()
  21482. /**
  21483. * (当前用户)加入该对话
  21484. * @return {Promise.<this>} self
  21485. */
  21486. ;
  21487. _proto.join =
  21488. /*#__PURE__*/
  21489. function () {
  21490. var _join = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
  21491. var _this3 = this;
  21492. return regenerator.wrap(function _callee9$(_context9) {
  21493. while (1) {
  21494. switch (_context9.prev = _context9.next) {
  21495. case 0:
  21496. this._debug('join');
  21497. return _context9.abrupt("return", this.add(this._client.id).then(function (_ref4) {
  21498. var failures = _ref4.failures;
  21499. if (failures[0]) throw failures[0];
  21500. return _this3;
  21501. }));
  21502. case 2:
  21503. case "end":
  21504. return _context9.stop();
  21505. }
  21506. }
  21507. }, _callee9, this);
  21508. }));
  21509. function join() {
  21510. return _join.apply(this, arguments);
  21511. }
  21512. return join;
  21513. }()
  21514. /**
  21515. * (当前用户)退出该对话
  21516. * @return {Promise.<this>} self
  21517. */
  21518. ;
  21519. _proto.quit =
  21520. /*#__PURE__*/
  21521. function () {
  21522. var _quit = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
  21523. var _this4 = this;
  21524. return regenerator.wrap(function _callee10$(_context10) {
  21525. while (1) {
  21526. switch (_context10.prev = _context10.next) {
  21527. case 0:
  21528. this._debug('quit');
  21529. return _context10.abrupt("return", this.remove(this._client.id).then(function (_ref5) {
  21530. var failures = _ref5.failures;
  21531. if (failures[0]) throw failures[0];
  21532. return _this4;
  21533. }));
  21534. case 2:
  21535. case "end":
  21536. return _context10.stop();
  21537. }
  21538. }
  21539. }, _callee10, this);
  21540. }));
  21541. function quit() {
  21542. return _quit.apply(this, arguments);
  21543. }
  21544. return quit;
  21545. }()
  21546. /**
  21547. * 在该对话中禁言成员
  21548. * @param {String|String[]} clientIds 成员 client id
  21549. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21550. */
  21551. ;
  21552. _proto.muteMembers =
  21553. /*#__PURE__*/
  21554. function () {
  21555. var _muteMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
  21556. var command, _yield$this$_send3, convMessage;
  21557. return regenerator.wrap(function _callee11$(_context11) {
  21558. while (1) {
  21559. switch (_context11.prev = _context11.next) {
  21560. case 0:
  21561. this._debug('mute', clientIds);
  21562. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  21563. command = new GenericCommand({
  21564. op: OpType.add_shutup,
  21565. convMessage: new ConvCommand({
  21566. m: clientIds
  21567. })
  21568. });
  21569. _context11.next = 5;
  21570. return this._send(command);
  21571. case 5:
  21572. _yield$this$_send3 = _context11.sent;
  21573. convMessage = _yield$this$_send3.convMessage;
  21574. return _context11.abrupt("return", createPartiallySuccess(convMessage));
  21575. case 8:
  21576. case "end":
  21577. return _context11.stop();
  21578. }
  21579. }
  21580. }, _callee11, this);
  21581. }));
  21582. function muteMembers(_x9) {
  21583. return _muteMembers.apply(this, arguments);
  21584. }
  21585. return muteMembers;
  21586. }()
  21587. /**
  21588. * 在该对话中解除成员禁言
  21589. * @param {String|String[]} clientIds 成员 client id
  21590. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21591. */
  21592. ;
  21593. _proto.unmuteMembers =
  21594. /*#__PURE__*/
  21595. function () {
  21596. var _unmuteMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(clientIds) {
  21597. var command, _yield$this$_send4, convMessage;
  21598. return regenerator.wrap(function _callee12$(_context12) {
  21599. while (1) {
  21600. switch (_context12.prev = _context12.next) {
  21601. case 0:
  21602. this._debug('unmute', clientIds);
  21603. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  21604. command = new GenericCommand({
  21605. op: OpType.remove_shutup,
  21606. convMessage: new ConvCommand({
  21607. m: clientIds
  21608. })
  21609. });
  21610. _context12.next = 5;
  21611. return this._send(command);
  21612. case 5:
  21613. _yield$this$_send4 = _context12.sent;
  21614. convMessage = _yield$this$_send4.convMessage;
  21615. return _context12.abrupt("return", createPartiallySuccess(convMessage));
  21616. case 8:
  21617. case "end":
  21618. return _context12.stop();
  21619. }
  21620. }
  21621. }, _callee12, this);
  21622. }));
  21623. function unmuteMembers(_x10) {
  21624. return _unmuteMembers.apply(this, arguments);
  21625. }
  21626. return unmuteMembers;
  21627. }()
  21628. /**
  21629. * 查询该对话禁言成员列表
  21630. * @param {Object} [options]
  21631. * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
  21632. * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
  21633. * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
  21634. */
  21635. ;
  21636. _proto.queryMutedMembers =
  21637. /*#__PURE__*/
  21638. function () {
  21639. var _queryMutedMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13() {
  21640. var _ref6,
  21641. limit,
  21642. next,
  21643. command,
  21644. _yield$this$_send5,
  21645. _yield$this$_send5$co,
  21646. m,
  21647. newNext,
  21648. _args13 = arguments;
  21649. return regenerator.wrap(function _callee13$(_context13) {
  21650. while (1) {
  21651. switch (_context13.prev = _context13.next) {
  21652. case 0:
  21653. _ref6 = _args13.length > 0 && _args13[0] !== undefined ? _args13[0] : {}, limit = _ref6.limit, next = _ref6.next;
  21654. this._debug('query muted: limit %O, next: %O', limit, next);
  21655. command = new GenericCommand({
  21656. op: OpType.query_shutup,
  21657. convMessage: new ConvCommand({
  21658. limit: limit,
  21659. next: next
  21660. })
  21661. });
  21662. _context13.next = 5;
  21663. return this._send(command);
  21664. case 5:
  21665. _yield$this$_send5 = _context13.sent;
  21666. _yield$this$_send5$co = _yield$this$_send5.convMessage;
  21667. m = _yield$this$_send5$co.m;
  21668. newNext = _yield$this$_send5$co.next;
  21669. return _context13.abrupt("return", {
  21670. results: m,
  21671. next: newNext
  21672. });
  21673. case 10:
  21674. case "end":
  21675. return _context13.stop();
  21676. }
  21677. }
  21678. }, _callee13, this);
  21679. }));
  21680. function queryMutedMembers() {
  21681. return _queryMutedMembers.apply(this, arguments);
  21682. }
  21683. return queryMutedMembers;
  21684. }()
  21685. /**
  21686. * 将用户加入该对话黑名单
  21687. * @param {String|String[]} clientIds 成员 client id
  21688. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21689. */
  21690. ;
  21691. _proto.blockMembers =
  21692. /*#__PURE__*/
  21693. function () {
  21694. var _blockMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(clientIds) {
  21695. var command, _yield$this$_send6, blacklistMessage;
  21696. return regenerator.wrap(function _callee14$(_context14) {
  21697. while (1) {
  21698. switch (_context14.prev = _context14.next) {
  21699. case 0:
  21700. this._debug('block', clientIds);
  21701. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  21702. command = new GenericCommand({
  21703. cmd: 'blacklist',
  21704. op: OpType.block,
  21705. blacklistMessage: new BlacklistCommand({
  21706. srcCid: this.id,
  21707. toPids: clientIds
  21708. })
  21709. });
  21710. _context14.next = 5;
  21711. return this._appendBlacklistSignature(command, 'conversation-block-clients', clientIds);
  21712. case 5:
  21713. _context14.next = 7;
  21714. return this._send(command);
  21715. case 7:
  21716. _yield$this$_send6 = _context14.sent;
  21717. blacklistMessage = _yield$this$_send6.blacklistMessage;
  21718. return _context14.abrupt("return", createPartiallySuccess(blacklistMessage));
  21719. case 10:
  21720. case "end":
  21721. return _context14.stop();
  21722. }
  21723. }
  21724. }, _callee14, this);
  21725. }));
  21726. function blockMembers(_x11) {
  21727. return _blockMembers.apply(this, arguments);
  21728. }
  21729. return blockMembers;
  21730. }()
  21731. /**
  21732. * 将用户移出该对话黑名单
  21733. * @param {String|String[]} clientIds 成员 client id
  21734. * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
  21735. */
  21736. ;
  21737. _proto.unblockMembers =
  21738. /*#__PURE__*/
  21739. function () {
  21740. var _unblockMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(clientIds) {
  21741. var command, _yield$this$_send7, blacklistMessage;
  21742. return regenerator.wrap(function _callee15$(_context15) {
  21743. while (1) {
  21744. switch (_context15.prev = _context15.next) {
  21745. case 0:
  21746. this._debug('unblock', clientIds);
  21747. clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
  21748. command = new GenericCommand({
  21749. cmd: 'blacklist',
  21750. op: OpType.unblock,
  21751. blacklistMessage: new BlacklistCommand({
  21752. srcCid: this.id,
  21753. toPids: clientIds
  21754. })
  21755. });
  21756. _context15.next = 5;
  21757. return this._appendBlacklistSignature(command, 'conversation-unblock-clients', clientIds);
  21758. case 5:
  21759. _context15.next = 7;
  21760. return this._send(command);
  21761. case 7:
  21762. _yield$this$_send7 = _context15.sent;
  21763. blacklistMessage = _yield$this$_send7.blacklistMessage;
  21764. return _context15.abrupt("return", createPartiallySuccess(blacklistMessage));
  21765. case 10:
  21766. case "end":
  21767. return _context15.stop();
  21768. }
  21769. }
  21770. }, _callee15, this);
  21771. }));
  21772. function unblockMembers(_x12) {
  21773. return _unblockMembers.apply(this, arguments);
  21774. }
  21775. return unblockMembers;
  21776. }()
  21777. /**
  21778. * 查询该对话黑名单
  21779. * @param {Object} [options]
  21780. * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
  21781. * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
  21782. * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
  21783. */
  21784. ;
  21785. _proto.queryBlockedMembers =
  21786. /*#__PURE__*/
  21787. function () {
  21788. var _queryBlockedMembers = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16() {
  21789. var _ref7,
  21790. limit,
  21791. next,
  21792. command,
  21793. _yield$this$_send8,
  21794. _yield$this$_send8$bl,
  21795. blockedPids,
  21796. newNext,
  21797. _args16 = arguments;
  21798. return regenerator.wrap(function _callee16$(_context16) {
  21799. while (1) {
  21800. switch (_context16.prev = _context16.next) {
  21801. case 0:
  21802. _ref7 = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : {}, limit = _ref7.limit, next = _ref7.next;
  21803. this._debug('query blocked: limit %O, next: %O', limit, next);
  21804. command = new GenericCommand({
  21805. cmd: 'blacklist',
  21806. op: OpType.query,
  21807. blacklistMessage: new BlacklistCommand({
  21808. srcCid: this.id,
  21809. limit: limit,
  21810. next: next
  21811. })
  21812. });
  21813. _context16.next = 5;
  21814. return this._send(command);
  21815. case 5:
  21816. _yield$this$_send8 = _context16.sent;
  21817. _yield$this$_send8$bl = _yield$this$_send8.blacklistMessage;
  21818. blockedPids = _yield$this$_send8$bl.blockedPids;
  21819. newNext = _yield$this$_send8$bl.next;
  21820. return _context16.abrupt("return", {
  21821. results: blockedPids,
  21822. next: newNext
  21823. });
  21824. case 10:
  21825. case "end":
  21826. return _context16.stop();
  21827. }
  21828. }
  21829. }, _callee16, this);
  21830. }));
  21831. function queryBlockedMembers() {
  21832. return _queryBlockedMembers.apply(this, arguments);
  21833. }
  21834. return queryBlockedMembers;
  21835. }();
  21836. _proto.toFullJSON = function toFullJSON() {
  21837. var creator = this.creator,
  21838. system = this.system,
  21839. _transient2 = this["transient"],
  21840. createdAt = this.createdAt,
  21841. updatedAt = this.updatedAt,
  21842. _attributes = this._attributes;
  21843. return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
  21844. creator: creator,
  21845. system: system,
  21846. "transient": _transient2,
  21847. createdAt: getTime(createdAt),
  21848. updatedAt: getTime(updatedAt)
  21849. }, _attributes);
  21850. };
  21851. _proto.toJSON = function toJSON() {
  21852. var creator = this.creator,
  21853. system = this.system,
  21854. _transient3 = this["transient"],
  21855. muted = this.muted,
  21856. mutedMembers = this.mutedMembers,
  21857. createdAt = this.createdAt,
  21858. updatedAt = this.updatedAt,
  21859. _attributes = this._attributes;
  21860. return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
  21861. creator: creator,
  21862. system: system,
  21863. "transient": _transient3,
  21864. muted: muted,
  21865. mutedMembers: mutedMembers,
  21866. createdAt: createdAt,
  21867. updatedAt: updatedAt
  21868. }, _attributes);
  21869. };
  21870. createClass(PersistentConversation, [{
  21871. key: "createdAt",
  21872. set: function set(value) {
  21873. this._createdAt = decodeDate(value);
  21874. },
  21875. get: function get() {
  21876. return this._createdAt;
  21877. }
  21878. }, {
  21879. key: "updatedAt",
  21880. set: function set(value) {
  21881. this._updatedAt = decodeDate(value);
  21882. },
  21883. get: function get() {
  21884. return this._updatedAt;
  21885. }
  21886. /**
  21887. * 对话名字,对应 _Conversation 表中的 name
  21888. * @type {String}
  21889. */
  21890. }, {
  21891. key: "name",
  21892. get: function get() {
  21893. return this.get('name');
  21894. },
  21895. set: function set(value) {
  21896. this.set('name', value);
  21897. }
  21898. }]);
  21899. return PersistentConversation;
  21900. }(ConversationBase);
  21901. /**
  21902. * 对话成员角色枚举
  21903. * @enum {String}
  21904. * @since 4.0.0
  21905. * @memberof module:leancloud-realtime
  21906. */
  21907. var ConversationMemberRole = {
  21908. /** 所有者 */
  21909. OWNER: 'Owner',
  21910. /** 管理员 */
  21911. MANAGER: 'Manager',
  21912. /** 成员 */
  21913. MEMBER: 'Member'
  21914. };
  21915. Object.freeze(ConversationMemberRole);
  21916. var ConversationMemberInfo = /*#__PURE__*/function () {
  21917. /**
  21918. * 对话成员属性,保存了成员与某个对话相关的属性,对应 _ConversationMemberInfo 表
  21919. * @since 4.0.0
  21920. */
  21921. function ConversationMemberInfo(_ref) {
  21922. var conversation = _ref.conversation,
  21923. memberId = _ref.memberId,
  21924. role = _ref.role;
  21925. if (!conversation) throw new Error('conversation requried');
  21926. if (!memberId) throw new Error('memberId requried');
  21927. Object.assign(internal(this), {
  21928. conversation: conversation,
  21929. memberId: memberId,
  21930. role: role
  21931. });
  21932. }
  21933. /**
  21934. * 对话 Id
  21935. * @type {String}
  21936. * @readonly
  21937. */
  21938. var _proto = ConversationMemberInfo.prototype;
  21939. _proto.toJSON = function toJSON() {
  21940. var conversationId = this.conversationId,
  21941. memberId = this.memberId,
  21942. role = this.role,
  21943. isOwner = this.isOwner;
  21944. return {
  21945. conversationId: conversationId,
  21946. memberId: memberId,
  21947. role: role,
  21948. isOwner: isOwner
  21949. };
  21950. };
  21951. createClass(ConversationMemberInfo, [{
  21952. key: "conversationId",
  21953. get: function get() {
  21954. return internal(this).conversation.id;
  21955. }
  21956. /**
  21957. * 成员 Id
  21958. * @type {String}
  21959. * @readonly
  21960. */
  21961. }, {
  21962. key: "memberId",
  21963. get: function get() {
  21964. return internal(this).memberId;
  21965. }
  21966. /**
  21967. * 角色
  21968. * @type {module:leancloud-realtime.ConversationMemberRole | String}
  21969. * @readonly
  21970. */
  21971. }, {
  21972. key: "role",
  21973. get: function get() {
  21974. if (this.isOwner) return ConversationMemberRole.OWNER;
  21975. return internal(this).role;
  21976. }
  21977. /**
  21978. * 是否是管理员
  21979. * @type {Boolean}
  21980. * @readonly
  21981. */
  21982. }, {
  21983. key: "isOwner",
  21984. get: function get() {
  21985. return this.memberId === internal(this).conversation.creator;
  21986. }
  21987. }]);
  21988. return ConversationMemberInfo;
  21989. }();
  21990. /**
  21991. * 普通对话
  21992. *
  21993. * 无法直接实例化,请使用 {@link IMClient#createConversation} 创建新的普通对话。
  21994. * @extends PersistentConversation
  21995. * @public
  21996. */
  21997. var Conversation = /*#__PURE__*/function (_PersistentConversati) {
  21998. inheritsLoose(Conversation, _PersistentConversati);
  21999. function Conversation() {
  22000. return _PersistentConversati.apply(this, arguments) || this;
  22001. }
  22002. var _proto = Conversation.prototype;
  22003. _proto._addMembers = function _addMembers(members) {
  22004. var _this = this;
  22005. _PersistentConversati.prototype._addMembers.call(this, members);
  22006. this.members = union(this.members, members);
  22007. var _internal = internal(this),
  22008. memberInfoMap = _internal.memberInfoMap;
  22009. if (!memberInfoMap) return;
  22010. members.forEach(function (memberId) {
  22011. memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
  22012. conversation: _this,
  22013. memberId: memberId,
  22014. role: ConversationMemberRole.MEMBER
  22015. });
  22016. });
  22017. };
  22018. _proto._removeMembers = function _removeMembers(members) {
  22019. _PersistentConversati.prototype._removeMembers.call(this, members);
  22020. this.members = difference(this.members, members);
  22021. var _internal2 = internal(this),
  22022. memberInfoMap = _internal2.memberInfoMap;
  22023. if (!memberInfoMap) return;
  22024. members.forEach(function (memberId) {
  22025. delete memberInfoMap[memberId];
  22026. });
  22027. };
  22028. _proto._fetchAllMemberInfo = /*#__PURE__*/function () {
  22029. var _fetchAllMemberInfo2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
  22030. var _this2 = this;
  22031. var response, memberInfos, memberInfoMap;
  22032. return regenerator.wrap(function _callee$(_context) {
  22033. while (1) {
  22034. switch (_context.prev = _context.next) {
  22035. case 0:
  22036. _context.next = 2;
  22037. return this._client._requestWithSessionToken({
  22038. method: 'GET',
  22039. path: '/classes/_ConversationMemberInfo',
  22040. query: {
  22041. where: {
  22042. cid: this.id
  22043. }
  22044. }
  22045. });
  22046. case 2:
  22047. response = _context.sent;
  22048. memberInfos = response.results.map(function (info) {
  22049. return new ConversationMemberInfo({
  22050. conversation: _this2,
  22051. memberId: info.clientId,
  22052. role: info.role
  22053. });
  22054. });
  22055. memberInfoMap = {};
  22056. memberInfos.forEach(function (memberInfo) {
  22057. memberInfoMap[memberInfo.memberId] = memberInfo;
  22058. });
  22059. this.members.forEach(function (memberId) {
  22060. memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
  22061. conversation: _this2,
  22062. memberId: memberId,
  22063. role: ConversationMemberRole.MEMBER
  22064. });
  22065. });
  22066. internal(this).memberInfoMap = memberInfoMap;
  22067. return _context.abrupt("return", memberInfoMap);
  22068. case 9:
  22069. case "end":
  22070. return _context.stop();
  22071. }
  22072. }
  22073. }, _callee, this);
  22074. }));
  22075. function _fetchAllMemberInfo() {
  22076. return _fetchAllMemberInfo2.apply(this, arguments);
  22077. }
  22078. return _fetchAllMemberInfo;
  22079. }()
  22080. /**
  22081. * 获取所有成员的对话属性
  22082. * @since 4.0.0
  22083. * @return {Promise.<ConversationMemberInfo[]>} 所有成员的对话属性列表
  22084. */
  22085. ;
  22086. _proto.getAllMemberInfo =
  22087. /*#__PURE__*/
  22088. function () {
  22089. var _getAllMemberInfo = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  22090. var _ref,
  22091. _ref$noCache,
  22092. noCache,
  22093. _internal3,
  22094. memberInfoMap,
  22095. _args2 = arguments;
  22096. return regenerator.wrap(function _callee2$(_context2) {
  22097. while (1) {
  22098. switch (_context2.prev = _context2.next) {
  22099. case 0:
  22100. _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$noCache = _ref.noCache, noCache = _ref$noCache === void 0 ? false : _ref$noCache;
  22101. _internal3 = internal(this), memberInfoMap = _internal3.memberInfoMap;
  22102. if (!(!memberInfoMap || noCache)) {
  22103. _context2.next = 6;
  22104. break;
  22105. }
  22106. _context2.next = 5;
  22107. return this._fetchAllMemberInfo();
  22108. case 5:
  22109. memberInfoMap = _context2.sent;
  22110. case 6:
  22111. return _context2.abrupt("return", this.members.map(function (memberId) {
  22112. return memberInfoMap[memberId];
  22113. }));
  22114. case 7:
  22115. case "end":
  22116. return _context2.stop();
  22117. }
  22118. }
  22119. }, _callee2, this);
  22120. }));
  22121. function getAllMemberInfo() {
  22122. return _getAllMemberInfo.apply(this, arguments);
  22123. }
  22124. return getAllMemberInfo;
  22125. }()
  22126. /**
  22127. * 获取指定成员的对话属性
  22128. * @since 4.0.0
  22129. * @param {String} memberId 成员 Id
  22130. * @return {Promise.<ConversationMemberInfo>} 指定成员的对话属性
  22131. */
  22132. ;
  22133. _proto.getMemberInfo =
  22134. /*#__PURE__*/
  22135. function () {
  22136. var _getMemberInfo = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(memberId) {
  22137. var _internal4, memberInfoMap;
  22138. return regenerator.wrap(function _callee3$(_context3) {
  22139. while (1) {
  22140. switch (_context3.prev = _context3.next) {
  22141. case 0:
  22142. if (!(this.members.indexOf(memberId) === -1)) {
  22143. _context3.next = 2;
  22144. break;
  22145. }
  22146. throw new Error("".concat(memberId, " is not the mumber of conversation[").concat(this.id, "]"));
  22147. case 2:
  22148. _internal4 = internal(this), memberInfoMap = _internal4.memberInfoMap;
  22149. if (memberInfoMap && memberInfoMap[memberId]) {
  22150. _context3.next = 6;
  22151. break;
  22152. }
  22153. _context3.next = 6;
  22154. return this.getAllMemberInfo();
  22155. case 6:
  22156. return _context3.abrupt("return", internal(this).memberInfoMap[memberId]);
  22157. case 7:
  22158. case "end":
  22159. return _context3.stop();
  22160. }
  22161. }
  22162. }, _callee3, this);
  22163. }));
  22164. function getMemberInfo(_x) {
  22165. return _getMemberInfo.apply(this, arguments);
  22166. }
  22167. return getMemberInfo;
  22168. }()
  22169. /**
  22170. * 更新指定用户的角色
  22171. * @since 4.0.0
  22172. * @param {String} memberId 成员 Id
  22173. * @param {module:leancloud-realtime.ConversationMemberRole | String} role 角色
  22174. * @return {Promise.<this>} self
  22175. */
  22176. ;
  22177. _proto.updateMemberRole =
  22178. /*#__PURE__*/
  22179. function () {
  22180. var _updateMemberRole = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(memberId, role) {
  22181. var _internal5, memberInfos;
  22182. return regenerator.wrap(function _callee4$(_context4) {
  22183. while (1) {
  22184. switch (_context4.prev = _context4.next) {
  22185. case 0:
  22186. this._debug('update member role');
  22187. if (!(role === ConversationMemberRole.OWNER)) {
  22188. _context4.next = 3;
  22189. break;
  22190. }
  22191. throw createError({
  22192. code: ErrorCode.OWNER_PROMOTION_NOT_ALLOWED
  22193. });
  22194. case 3:
  22195. _context4.next = 5;
  22196. return this._send(new GenericCommand({
  22197. op: OpType.member_info_update,
  22198. convMessage: new ConvCommand({
  22199. targetClientId: memberId,
  22200. info: new ConvMemberInfo({
  22201. pid: memberId,
  22202. role: role
  22203. })
  22204. })
  22205. }));
  22206. case 5:
  22207. _internal5 = internal(this), memberInfos = _internal5.memberInfos;
  22208. if (memberInfos && memberInfos[memberId]) {
  22209. internal(memberInfos[memberId]).role = role;
  22210. }
  22211. return _context4.abrupt("return", this);
  22212. case 8:
  22213. case "end":
  22214. return _context4.stop();
  22215. }
  22216. }
  22217. }, _callee4, this);
  22218. }));
  22219. function updateMemberRole(_x2, _x3) {
  22220. return _updateMemberRole.apply(this, arguments);
  22221. }
  22222. return updateMemberRole;
  22223. }();
  22224. return Conversation;
  22225. }(PersistentConversation);
  22226. /**
  22227. * 聊天室。
  22228. *
  22229. * 无法直接实例化,请使用 {@link IMClient#createChatRoom} 创建新的聊天室。
  22230. * @since 4.0.0
  22231. * @extends PersistentConversation
  22232. * @public
  22233. */
  22234. var ChatRoom = /*#__PURE__*/function (_PersistentConversati) {
  22235. inheritsLoose(ChatRoom, _PersistentConversati);
  22236. function ChatRoom() {
  22237. return _PersistentConversati.apply(this, arguments) || this;
  22238. }
  22239. return ChatRoom;
  22240. }(PersistentConversation);
  22241. /**
  22242. * 服务号。
  22243. *
  22244. * 服务号不支持在客户端创建。
  22245. * @since 4.0.0
  22246. * @extends PersistentConversation
  22247. * @public
  22248. */
  22249. var ServiceConversation = /*#__PURE__*/function (_PersistentConversati) {
  22250. inheritsLoose(ServiceConversation, _PersistentConversati);
  22251. function ServiceConversation() {
  22252. return _PersistentConversati.apply(this, arguments) || this;
  22253. }
  22254. var _proto = ServiceConversation.prototype;
  22255. /**
  22256. * 订阅该服务号
  22257. * @return {Promise.<this>} self
  22258. */
  22259. _proto.subscribe =
  22260. /*#__PURE__*/
  22261. function () {
  22262. var _subscribe = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
  22263. return regenerator.wrap(function _callee$(_context) {
  22264. while (1) {
  22265. switch (_context.prev = _context.next) {
  22266. case 0:
  22267. return _context.abrupt("return", this.join());
  22268. case 1:
  22269. case "end":
  22270. return _context.stop();
  22271. }
  22272. }
  22273. }, _callee, this);
  22274. }));
  22275. function subscribe() {
  22276. return _subscribe.apply(this, arguments);
  22277. }
  22278. return subscribe;
  22279. }()
  22280. /**
  22281. * 退订该服务号
  22282. * @return {Promise.<this>} self
  22283. */
  22284. ;
  22285. _proto.unsubscribe =
  22286. /*#__PURE__*/
  22287. function () {
  22288. var _unsubscribe = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  22289. return regenerator.wrap(function _callee2$(_context2) {
  22290. while (1) {
  22291. switch (_context2.prev = _context2.next) {
  22292. case 0:
  22293. return _context2.abrupt("return", this.quit());
  22294. case 1:
  22295. case "end":
  22296. return _context2.stop();
  22297. }
  22298. }
  22299. }, _callee2, this);
  22300. }));
  22301. function unsubscribe() {
  22302. return _unsubscribe.apply(this, arguments);
  22303. }
  22304. return unsubscribe;
  22305. }();
  22306. return ServiceConversation;
  22307. }(PersistentConversation);
  22308. function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  22309. function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  22310. var transformNotFoundError = function transformNotFoundError(error) {
  22311. return error.code === ErrorCode.CONVERSATION_NOT_FOUND ? createError({
  22312. code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
  22313. }) : error;
  22314. };
  22315. /**
  22316. * 临时对话
  22317. * @since 4.0.0
  22318. * @extends ConversationBase
  22319. * @public
  22320. */
  22321. var TemporaryConversation = /*#__PURE__*/function (_ConversationBase) {
  22322. inheritsLoose(TemporaryConversation, _ConversationBase);
  22323. /**
  22324. * 无法直接实例化,请使用 {@link IMClient#createTemporaryConversation} 创建新的临时对话。
  22325. */
  22326. function TemporaryConversation(data, _ref, client) {
  22327. var expiredAt = _ref.expiredAt;
  22328. return _ConversationBase.call(this, _objectSpread$7(_objectSpread$7({}, data), {}, {
  22329. expiredAt: expiredAt
  22330. }), client) || this;
  22331. }
  22332. /**
  22333. * 对话失效时间
  22334. * @type {Date}
  22335. */
  22336. var _proto = TemporaryConversation.prototype;
  22337. _proto._send = /*#__PURE__*/function () {
  22338. var _send2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
  22339. var _ConversationBase$pro,
  22340. _len,
  22341. args,
  22342. _key,
  22343. _args = arguments;
  22344. return regenerator.wrap(function _callee$(_context) {
  22345. while (1) {
  22346. switch (_context.prev = _context.next) {
  22347. case 0:
  22348. if (!this.expired) {
  22349. _context.next = 2;
  22350. break;
  22351. }
  22352. throw createError({
  22353. code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
  22354. });
  22355. case 2:
  22356. _context.prev = 2;
  22357. for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  22358. args[_key] = _args[_key];
  22359. }
  22360. _context.next = 6;
  22361. return (_ConversationBase$pro = _ConversationBase.prototype._send).call.apply(_ConversationBase$pro, [this].concat(args));
  22362. case 6:
  22363. return _context.abrupt("return", _context.sent);
  22364. case 9:
  22365. _context.prev = 9;
  22366. _context.t0 = _context["catch"](2);
  22367. throw transformNotFoundError(_context.t0);
  22368. case 12:
  22369. case "end":
  22370. return _context.stop();
  22371. }
  22372. }
  22373. }, _callee, this, [[2, 9]]);
  22374. }));
  22375. function _send() {
  22376. return _send2.apply(this, arguments);
  22377. }
  22378. return _send;
  22379. }();
  22380. _proto.send = /*#__PURE__*/function () {
  22381. var _send3 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  22382. var _ConversationBase$pro2,
  22383. _len2,
  22384. args,
  22385. _key2,
  22386. _args2 = arguments;
  22387. return regenerator.wrap(function _callee2$(_context2) {
  22388. while (1) {
  22389. switch (_context2.prev = _context2.next) {
  22390. case 0:
  22391. _context2.prev = 0;
  22392. for (_len2 = _args2.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  22393. args[_key2] = _args2[_key2];
  22394. }
  22395. _context2.next = 4;
  22396. return (_ConversationBase$pro2 = _ConversationBase.prototype.send).call.apply(_ConversationBase$pro2, [this].concat(args));
  22397. case 4:
  22398. return _context2.abrupt("return", _context2.sent);
  22399. case 7:
  22400. _context2.prev = 7;
  22401. _context2.t0 = _context2["catch"](0);
  22402. throw transformNotFoundError(_context2.t0);
  22403. case 10:
  22404. case "end":
  22405. return _context2.stop();
  22406. }
  22407. }
  22408. }, _callee2, this, [[0, 7]]);
  22409. }));
  22410. function send() {
  22411. return _send3.apply(this, arguments);
  22412. }
  22413. return send;
  22414. }();
  22415. _proto.toFullJSON = function toFullJSON() {
  22416. var expiredAt = this.expiredAt;
  22417. return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
  22418. expiredAt: getTime(expiredAt)
  22419. });
  22420. };
  22421. _proto.toJSON = function toJSON() {
  22422. var expiredAt = this.expiredAt,
  22423. expired = this.expired;
  22424. return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
  22425. expiredAt: expiredAt,
  22426. expired: expired
  22427. });
  22428. };
  22429. createClass(TemporaryConversation, [{
  22430. key: "expiredAt",
  22431. set: function set(value) {
  22432. this._expiredAt = decodeDate(value);
  22433. },
  22434. get: function get() {
  22435. return this._expiredAt;
  22436. }
  22437. /**
  22438. * 对话是否已失效
  22439. * @type {Boolean}
  22440. */
  22441. }, {
  22442. key: "expired",
  22443. get: function get() {
  22444. return this.expiredAt < new Date();
  22445. }
  22446. }]);
  22447. return TemporaryConversation;
  22448. }(ConversationBase);
  22449. var debug$9 = browser('LC:ConversationQuery');
  22450. var ConversationQuery = /*#__PURE__*/function () {
  22451. ConversationQuery._encode = function _encode(value) {
  22452. if (value instanceof Date) {
  22453. return {
  22454. __type: 'Date',
  22455. iso: value.toJSON()
  22456. };
  22457. }
  22458. if (value instanceof RegExp) {
  22459. return value.source;
  22460. }
  22461. return value;
  22462. };
  22463. ConversationQuery._quote = function _quote(s) {
  22464. return "\\Q".concat(s.replace('\\E', '\\E\\\\E\\Q'), "\\E");
  22465. };
  22466. ConversationQuery._calculateFlag = function _calculateFlag(options) {
  22467. return ['withLastMessagesRefreshed', 'compact'].reduce( // eslint-disable-next-line no-bitwise
  22468. function (prev, key) {
  22469. return (prev << 1) + Boolean(options[key]);
  22470. }, 0);
  22471. }
  22472. /**
  22473. * 构造一个用 AND 连接所有查询的 ConversationQuery
  22474. * @param {...ConversationQuery} queries
  22475. * @return {ConversationQuery}
  22476. */
  22477. ;
  22478. ConversationQuery.and = function and() {
  22479. for (var _len = arguments.length, queries = new Array(_len), _key = 0; _key < _len; _key++) {
  22480. queries[_key] = arguments[_key];
  22481. }
  22482. if (queries.length < 2) {
  22483. throw new Error('The queries must contain at least two elements');
  22484. }
  22485. if (!queries.every(function (q) {
  22486. return q instanceof ConversationQuery;
  22487. })) {
  22488. throw new Error('The element of queries must be an instance of ConversationQuery');
  22489. }
  22490. var combined = new ConversationQuery(queries[0]._client);
  22491. combined._where.$and = queries.map(function (q) {
  22492. return q._where;
  22493. });
  22494. return combined;
  22495. }
  22496. /**
  22497. * 构造一个用 OR 连接所有查询的 ConversationQuery
  22498. * @param {...ConversationQuery} queries
  22499. * @return {ConversationQuery}
  22500. */
  22501. ;
  22502. ConversationQuery.or = function or() {
  22503. var combined = ConversationQuery.and.apply(ConversationQuery, arguments);
  22504. combined._where.$or = combined._where.$and;
  22505. delete combined._where.$and;
  22506. return combined;
  22507. }
  22508. /**
  22509. * Create a ConversationQuery
  22510. * @param {IMClient} client
  22511. */
  22512. ;
  22513. function ConversationQuery(client) {
  22514. this._client = client;
  22515. this._where = {};
  22516. this._extraOptions = {};
  22517. }
  22518. var _proto = ConversationQuery.prototype;
  22519. _proto._addCondition = function _addCondition(key, condition, value) {
  22520. // Check if we already have a condition
  22521. if (!this._where[key]) {
  22522. this._where[key] = {};
  22523. }
  22524. this._where[key][condition] = this.constructor._encode(value);
  22525. return this;
  22526. };
  22527. _proto.toJSON = function toJSON() {
  22528. var json = {
  22529. where: this._where,
  22530. flag: this.constructor._calculateFlag(this._extraOptions)
  22531. };
  22532. if (typeof this._skip !== 'undefined') json.skip = this._skip;
  22533. if (typeof this._limit !== 'undefined') json.limit = this._limit;
  22534. if (typeof this._order !== 'undefined') json.sort = this._order;
  22535. debug$9(json);
  22536. return json;
  22537. }
  22538. /**
  22539. * 增加查询条件,指定聊天室的组员包含某些成员即可返回
  22540. * @param {string[]} peerIds - 成员 ID 列表
  22541. * @return {ConversationQuery} self
  22542. */
  22543. ;
  22544. _proto.containsMembers = function containsMembers(peerIds) {
  22545. return this.containsAll('m', peerIds);
  22546. }
  22547. /**
  22548. * 增加查询条件,指定聊天室的组员条件满足条件的才返回
  22549. *
  22550. * @param {string[]} - 成员 ID 列表
  22551. * @param {Boolean} includeSelf - 是否包含自己
  22552. * @return {ConversationQuery} self
  22553. */
  22554. ;
  22555. _proto.withMembers = function withMembers(peerIds, includeSelf) {
  22556. var peerIdsSet = new Set(peerIds);
  22557. if (includeSelf) {
  22558. peerIdsSet.add(this._client.id);
  22559. }
  22560. this.sizeEqualTo('m', peerIdsSet.size);
  22561. return this.containsMembers(Array.from(peerIdsSet));
  22562. }
  22563. /**
  22564. * 增加查询条件,当 conversation 的属性中对应的字段满足等于条件时即可返回
  22565. *
  22566. * @param {string} key
  22567. * @param value
  22568. * @return {ConversationQuery} self
  22569. */
  22570. ;
  22571. _proto.equalTo = function equalTo(key, value) {
  22572. this._where[key] = this.constructor._encode(value);
  22573. return this;
  22574. }
  22575. /**
  22576. * 增加查询条件,当 conversation 的属性中对应的字段满足小于条件时即可返回
  22577. * @param {string} key
  22578. * @param value
  22579. * @return {ConversationQuery} self
  22580. */
  22581. ;
  22582. _proto.lessThan = function lessThan(key, value) {
  22583. return this._addCondition(key, '$lt', value);
  22584. }
  22585. /**
  22586. * 增加查询条件,当 conversation 的属性中对应的字段满足小于等于条件时即可返回
  22587. * @param {string} key
  22588. * @param value
  22589. * @return {ConversationQuery} self
  22590. */
  22591. ;
  22592. _proto.lessThanOrEqualTo = function lessThanOrEqualTo(key, value) {
  22593. return this._addCondition(key, '$lte', value);
  22594. }
  22595. /**
  22596. * 增加查询条件,当 conversation 的属性中对应的字段满足大于条件时即可返回
  22597. *
  22598. * @param {string} key
  22599. * @param value
  22600. * @return {ConversationQuery} self
  22601. */
  22602. ;
  22603. _proto.greaterThan = function greaterThan(key, value) {
  22604. return this._addCondition(key, '$gt', value);
  22605. }
  22606. /**
  22607. * 增加查询条件,当 conversation 的属性中对应的字段满足大于等于条件时即可返回
  22608. *
  22609. * @param {string} key
  22610. * @param value
  22611. * @return {ConversationQuery} self
  22612. */
  22613. ;
  22614. _proto.greaterThanOrEqualTo = function greaterThanOrEqualTo(key, value) {
  22615. return this._addCondition(key, '$gte', value);
  22616. }
  22617. /**
  22618. * 增加查询条件,当 conversation 的属性中对应的字段满足不等于条件时即可返回
  22619. *
  22620. * @param {string} key
  22621. * @param value
  22622. * @return {ConversationQuery} self
  22623. */
  22624. ;
  22625. _proto.notEqualTo = function notEqualTo(key, value) {
  22626. return this._addCondition(key, '$ne', value);
  22627. }
  22628. /**
  22629. * 增加查询条件,当 conversation 存在指定的字段时即可返回
  22630. *
  22631. * @since 3.5.0
  22632. * @param {string} key
  22633. * @return {ConversationQuery} self
  22634. */
  22635. ;
  22636. _proto.exists = function exists(key) {
  22637. return this._addCondition(key, '$exists', true);
  22638. }
  22639. /**
  22640. * 增加查询条件,当 conversation 不存在指定的字段时即可返回
  22641. *
  22642. * @since 3.5.0
  22643. * @param {string} key
  22644. * @return {ConversationQuery} self
  22645. */
  22646. ;
  22647. _proto.doesNotExist = function doesNotExist(key) {
  22648. return this._addCondition(key, '$exists', false);
  22649. }
  22650. /**
  22651. * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含在指定值中时即可返回
  22652. *
  22653. * @param {string} key
  22654. * @param values
  22655. * @return {ConversationQuery} self
  22656. */
  22657. ;
  22658. _proto.containedIn = function containedIn(key, values) {
  22659. return this._addCondition(key, '$in', values);
  22660. }
  22661. /**
  22662. * 增加查询条件,当 conversation 的属性中对应的字段对应的值不包含在指定值中时即可返回
  22663. *
  22664. * @param {string} key
  22665. * @param values
  22666. * @return {ConversationQuery} self
  22667. */
  22668. ;
  22669. _proto.notContainsIn = function notContainsIn(key, values) {
  22670. return this._addCondition(key, '$nin', values);
  22671. }
  22672. /**
  22673. * 增加查询条件,当conversation的属性中对应的字段中的元素包含所有的值才可返回
  22674. *
  22675. * @param {string} key
  22676. * @param values
  22677. * @return {ConversationQuery} self
  22678. */
  22679. ;
  22680. _proto.containsAll = function containsAll(key, values) {
  22681. return this._addCondition(key, '$all', values);
  22682. }
  22683. /**
  22684. * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含此字符串即可返回
  22685. *
  22686. * @param {string} key
  22687. * @param {string} subString
  22688. * @return {ConversationQuery} self
  22689. */
  22690. ;
  22691. _proto.contains = function contains(key, subString) {
  22692. return this._addCondition(key, '$regex', ConversationQuery._quote(subString));
  22693. }
  22694. /**
  22695. * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串起始即可返回
  22696. *
  22697. * @param {string} key
  22698. * @param {string} prefix
  22699. * @return {ConversationQuery} self
  22700. */
  22701. ;
  22702. _proto.startsWith = function startsWith(key, prefix) {
  22703. return this._addCondition(key, '$regex', "^".concat(ConversationQuery._quote(prefix)));
  22704. }
  22705. /**
  22706. * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串结束即可返回
  22707. *
  22708. * @param {string} key
  22709. * @param {string} suffix
  22710. * @return {ConversationQuery} self
  22711. */
  22712. ;
  22713. _proto.endsWith = function endsWith(key, suffix) {
  22714. return this._addCondition(key, '$regex', "".concat(ConversationQuery._quote(suffix), "$"));
  22715. }
  22716. /**
  22717. * 增加查询条件,当 conversation 的属性中对应的字段对应的值满足提供的正则表达式即可返回
  22718. *
  22719. * @param {string} key
  22720. * @param {RegExp} regex
  22721. * @return {ConversationQuery} self
  22722. */
  22723. ;
  22724. _proto.matches = function matches(key, regex) {
  22725. this._addCondition(key, '$regex', regex); // Javascript regex options support mig as inline options but store them
  22726. // as properties of the object. We support mi & should migrate them to
  22727. // modifiers
  22728. var _modifiers = '';
  22729. if (regex.ignoreCase) {
  22730. _modifiers += 'i';
  22731. }
  22732. if (regex.multiline) {
  22733. _modifiers += 'm';
  22734. }
  22735. if (_modifiers && _modifiers.length) {
  22736. this._addCondition(key, '$options', _modifiers);
  22737. }
  22738. return this;
  22739. }
  22740. /**
  22741. * 添加查询约束条件,查找 key 类型是数组,该数组的长度匹配提供的数值
  22742. *
  22743. * @param {string} key
  22744. * @param {Number} length
  22745. * @return {ConversationQuery} self
  22746. */
  22747. ;
  22748. _proto.sizeEqualTo = function sizeEqualTo(key, length) {
  22749. return this._addCondition(key, '$size', length);
  22750. }
  22751. /**
  22752. * 设置返回集合的大小上限
  22753. *
  22754. * @param {Number} limit - 上限
  22755. * @return {ConversationQuery} self
  22756. */
  22757. ;
  22758. _proto.limit = function limit(_limit) {
  22759. this._limit = _limit;
  22760. return this;
  22761. }
  22762. /**
  22763. * 设置返回集合的起始位置,一般用于分页
  22764. *
  22765. * @param {Number} skip - 起始位置跳过几个对象
  22766. * @return {ConversationQuery} self
  22767. */
  22768. ;
  22769. _proto.skip = function skip(_skip) {
  22770. this._skip = _skip;
  22771. return this;
  22772. }
  22773. /**
  22774. * 设置返回集合按照指定key进行增序排列
  22775. *
  22776. * @param {string} key
  22777. * @return {ConversationQuery} self
  22778. */
  22779. ;
  22780. _proto.ascending = function ascending(key) {
  22781. this._order = key;
  22782. return this;
  22783. }
  22784. /**
  22785. * 设置返回集合按照指定key进行增序排列,如果已设置其他排序,原排序的优先级较高
  22786. *
  22787. * @param {string} key
  22788. * @return {ConversationQuery} self
  22789. */
  22790. ;
  22791. _proto.addAscending = function addAscending(key) {
  22792. if (this._order) {
  22793. this._order += ",".concat(key);
  22794. } else {
  22795. this._order = key;
  22796. }
  22797. return this;
  22798. }
  22799. /**
  22800. * 设置返回集合按照指定 key 进行降序排列
  22801. *
  22802. * @param {string} key
  22803. * @return {ConversationQuery} self
  22804. */
  22805. ;
  22806. _proto.descending = function descending(key) {
  22807. this._order = "-".concat(key);
  22808. return this;
  22809. }
  22810. /**
  22811. * 设置返回集合按照指定 key 进行降序排列,如果已设置其他排序,原排序的优先级较高
  22812. *
  22813. * @param {string} key
  22814. * @return {ConversationQuery} self
  22815. */
  22816. ;
  22817. _proto.addDescending = function addDescending(key) {
  22818. if (this._order) {
  22819. this._order += ",-".concat(key);
  22820. } else {
  22821. this._order = "-".concat(key);
  22822. }
  22823. return this;
  22824. }
  22825. /**
  22826. * 设置返回的 conversations 刷新最后一条消息
  22827. * @param {Boolean} [enabled=true]
  22828. * @return {ConversationQuery} self
  22829. */
  22830. ;
  22831. _proto.withLastMessagesRefreshed = function withLastMessagesRefreshed() {
  22832. var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  22833. this._extraOptions.withLastMessagesRefreshed = enabled;
  22834. return this;
  22835. }
  22836. /**
  22837. * 设置返回的 conversations 为精简模式,即不含成员列表
  22838. * @param {Boolean} [enabled=true]
  22839. * @return {ConversationQuery} self
  22840. */
  22841. ;
  22842. _proto.compact = function compact() {
  22843. var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  22844. this._extraOptions.compact = enabled;
  22845. return this;
  22846. }
  22847. /**
  22848. * 执行查询
  22849. * @return {Promise.<ConversationBase[]>}
  22850. */
  22851. ;
  22852. _proto.find =
  22853. /*#__PURE__*/
  22854. function () {
  22855. var _find = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
  22856. return regenerator.wrap(function _callee$(_context) {
  22857. while (1) {
  22858. switch (_context.prev = _context.next) {
  22859. case 0:
  22860. return _context.abrupt("return", this._client._executeQuery(this));
  22861. case 1:
  22862. case "end":
  22863. return _context.stop();
  22864. }
  22865. }
  22866. }, _callee, this);
  22867. }));
  22868. function find() {
  22869. return _find.apply(this, arguments);
  22870. }
  22871. return find;
  22872. }()
  22873. /**
  22874. * 返回符合条件的第一个结果
  22875. * @return {Promise.<ConversationBase>}
  22876. */
  22877. ;
  22878. _proto.first =
  22879. /*#__PURE__*/
  22880. function () {
  22881. var _first = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  22882. return regenerator.wrap(function _callee2$(_context2) {
  22883. while (1) {
  22884. switch (_context2.prev = _context2.next) {
  22885. case 0:
  22886. _context2.next = 2;
  22887. return this.limit(1).find();
  22888. case 2:
  22889. return _context2.abrupt("return", _context2.sent[0]);
  22890. case 3:
  22891. case "end":
  22892. return _context2.stop();
  22893. }
  22894. }
  22895. }, _callee2, this);
  22896. }));
  22897. function first() {
  22898. return _first.apply(this, arguments);
  22899. }
  22900. return first;
  22901. }();
  22902. return ConversationQuery;
  22903. }();
  22904. var debug$a = browser('LC:SessionManager');
  22905. var SessionManager = /*#__PURE__*/function () {
  22906. function SessionManager() {
  22907. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  22908. refresh = _ref.refresh,
  22909. onBeforeGetSessionToken = _ref.onBeforeGetSessionToken;
  22910. this.refresh = refresh;
  22911. this._onBeforeGetSessionToken = onBeforeGetSessionToken;
  22912. this.setSessionToken(null, 0);
  22913. }
  22914. var _proto = SessionManager.prototype;
  22915. _proto.setSessionToken = function setSessionToken(token, ttl) {
  22916. debug$a('set session token', token, ttl);
  22917. var sessionToken = new Expirable(token, ttl * 1000);
  22918. this._sessionToken = sessionToken;
  22919. delete this._pendingSessionTokenPromise;
  22920. return sessionToken;
  22921. };
  22922. _proto.setSessionTokenAsync = /*#__PURE__*/function () {
  22923. var _setSessionTokenAsync = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(promise) {
  22924. var _this = this;
  22925. var currentSessionToken;
  22926. return regenerator.wrap(function _callee$(_context) {
  22927. while (1) {
  22928. switch (_context.prev = _context.next) {
  22929. case 0:
  22930. currentSessionToken = this._sessionToken;
  22931. this._pendingSessionTokenPromise = promise["catch"](function (error) {
  22932. // revert, otherwise the following getSessionToken calls
  22933. // will all be rejected
  22934. _this._sessionToken = currentSessionToken;
  22935. throw error;
  22936. });
  22937. _context.t0 = this.setSessionToken;
  22938. _context.t1 = this;
  22939. _context.t2 = toConsumableArray;
  22940. _context.next = 7;
  22941. return this._pendingSessionTokenPromise;
  22942. case 7:
  22943. _context.t3 = _context.sent;
  22944. _context.t4 = (0, _context.t2)(_context.t3);
  22945. return _context.abrupt("return", _context.t0.apply.call(_context.t0, _context.t1, _context.t4));
  22946. case 10:
  22947. case "end":
  22948. return _context.stop();
  22949. }
  22950. }
  22951. }, _callee, this);
  22952. }));
  22953. function setSessionTokenAsync(_x) {
  22954. return _setSessionTokenAsync.apply(this, arguments);
  22955. }
  22956. return setSessionTokenAsync;
  22957. }();
  22958. _proto.getSessionToken = /*#__PURE__*/function () {
  22959. var _getSessionToken = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
  22960. var _ref2,
  22961. _ref2$autoRefresh,
  22962. autoRefresh,
  22963. _ref3,
  22964. value,
  22965. originalValue,
  22966. _yield$this$setSessio,
  22967. newValue,
  22968. _args2 = arguments;
  22969. return regenerator.wrap(function _callee2$(_context2) {
  22970. while (1) {
  22971. switch (_context2.prev = _context2.next) {
  22972. case 0:
  22973. _ref2 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref2$autoRefresh = _ref2.autoRefresh, autoRefresh = _ref2$autoRefresh === void 0 ? true : _ref2$autoRefresh;
  22974. debug$a('get session token');
  22975. if (this._onBeforeGetSessionToken) {
  22976. this._onBeforeGetSessionToken(this);
  22977. }
  22978. _context2.t0 = this._sessionToken;
  22979. if (_context2.t0) {
  22980. _context2.next = 8;
  22981. break;
  22982. }
  22983. _context2.next = 7;
  22984. return this._pendingSessionTokenPromise;
  22985. case 7:
  22986. _context2.t0 = _context2.sent;
  22987. case 8:
  22988. _ref3 = _context2.t0;
  22989. value = _ref3.value;
  22990. originalValue = _ref3.originalValue;
  22991. if (!(value === Expirable.EXPIRED && autoRefresh && this.refresh)) {
  22992. _context2.next = 19;
  22993. break;
  22994. }
  22995. debug$a('refresh expired session token');
  22996. _context2.next = 15;
  22997. return this.setSessionTokenAsync(this.refresh(this, originalValue));
  22998. case 15:
  22999. _yield$this$setSessio = _context2.sent;
  23000. newValue = _yield$this$setSessio.value;
  23001. debug$a('session token', newValue);
  23002. return _context2.abrupt("return", newValue);
  23003. case 19:
  23004. debug$a('session token', value);
  23005. return _context2.abrupt("return", value);
  23006. case 21:
  23007. case "end":
  23008. return _context2.stop();
  23009. }
  23010. }
  23011. }, _callee2, this);
  23012. }));
  23013. function getSessionToken() {
  23014. return _getSessionToken.apply(this, arguments);
  23015. }
  23016. return getSessionToken;
  23017. }();
  23018. _proto.revoke = function revoke() {
  23019. if (this._sessionToken) this._sessionToken.expiredAt = -1;
  23020. };
  23021. return SessionManager;
  23022. }();
  23023. var _dec$2, _dec2, _class$3;
  23024. function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  23025. function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  23026. var debug$b = browser('LC:IMClient');
  23027. var INVITED$1 = INVITED,
  23028. KICKED$1 = KICKED,
  23029. MEMBERS_JOINED$1 = MEMBERS_JOINED,
  23030. MEMBERS_LEFT$1 = MEMBERS_LEFT,
  23031. MEMBER_INFO_UPDATED$1 = MEMBER_INFO_UPDATED,
  23032. BLOCKED$1 = BLOCKED,
  23033. UNBLOCKED$1 = UNBLOCKED,
  23034. MEMBERS_BLOCKED$1 = MEMBERS_BLOCKED,
  23035. MEMBERS_UNBLOCKED$1 = MEMBERS_UNBLOCKED,
  23036. MUTED$1 = MUTED,
  23037. UNMUTED$1 = UNMUTED,
  23038. MEMBERS_MUTED$1 = MEMBERS_MUTED,
  23039. MEMBERS_UNMUTED$1 = MEMBERS_UNMUTED,
  23040. MESSAGE$2 = MESSAGE$1,
  23041. UNREAD_MESSAGES_COUNT_UPDATE$1 = UNREAD_MESSAGES_COUNT_UPDATE,
  23042. CLOSE$1 = CLOSE,
  23043. CONFLICT$1 = CONFLICT,
  23044. UNHANDLED_MESSAGE$1 = UNHANDLED_MESSAGE,
  23045. CONVERSATION_INFO_UPDATED$1 = CONVERSATION_INFO_UPDATED,
  23046. MESSAGE_RECALL$1 = MESSAGE_RECALL,
  23047. MESSAGE_UPDATE$1 = MESSAGE_UPDATE,
  23048. INFO_UPDATED$1 = INFO_UPDATED;
  23049. var isTemporaryConversatrionId = function isTemporaryConversatrionId(id) {
  23050. return /^_tmp:/.test(id);
  23051. };
  23052. /**
  23053. * 1 patch-msg
  23054. * 1 temp-conv-msg
  23055. * 0 auto-bind-deviceid-and-installation
  23056. * 1 transient-msg-ack
  23057. * 1 keep-notification
  23058. * 1 partial-failed-msg
  23059. * 0 group-chat-rcp
  23060. * 1 omit-peer-id
  23061. * @ignore
  23062. */
  23063. var configBitmap = 187;
  23064. var IMClient = (_dec$2 = throttle(1000), _dec2 = throttle(1000), (_class$3 = /*#__PURE__*/function (_EventEmitter) {
  23065. inheritsLoose(IMClient, _EventEmitter);
  23066. /**
  23067. * 无法直接实例化,请使用 {@link Realtime#createIMClient} 创建新的 IMClient。
  23068. *
  23069. * @extends EventEmitter
  23070. */
  23071. function IMClient(id) {
  23072. var _this;
  23073. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  23074. var props = arguments.length > 2 ? arguments[2] : undefined;
  23075. if (!(id === undefined || typeof id === 'string')) {
  23076. throw new TypeError("Client id [".concat(id, "] is not a String"));
  23077. }
  23078. _this = _EventEmitter.call(this) || this;
  23079. Object.assign(assertThisInitialized(_this), {
  23080. /**
  23081. * @var id {String} 客户端 id
  23082. * @memberof IMClient#
  23083. */
  23084. id: id,
  23085. options: options
  23086. }, props);
  23087. if (!_this._messageParser) {
  23088. throw new Error('IMClient must be initialized with a MessageParser');
  23089. }
  23090. _this._conversationCache = new Cache("client:".concat(_this.id));
  23091. _this._ackMessageBuffer = {};
  23092. internal(assertThisInitialized(_this)).lastPatchTime = Date.now();
  23093. internal(assertThisInitialized(_this)).lastNotificationTime = undefined;
  23094. internal(assertThisInitialized(_this))._eventemitter = new eventemitter3();
  23095. if (debug$b.enabled) {
  23096. values_1(IMEvent).forEach(function (event) {
  23097. return _this.on(event, function () {
  23098. for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
  23099. payload[_key] = arguments[_key];
  23100. }
  23101. return _this._debug("".concat(event, " event emitted. %o"), payload);
  23102. });
  23103. });
  23104. } // onIMClientCreate hook
  23105. applyDecorators(_this._plugins.onIMClientCreate, assertThisInitialized(_this));
  23106. return _this;
  23107. }
  23108. var _proto = IMClient.prototype;
  23109. _proto._debug = function _debug() {
  23110. for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  23111. params[_key2] = arguments[_key2];
  23112. }
  23113. debug$b.apply(void 0, params.concat(["[".concat(this.id, "]")]));
  23114. }
  23115. /**
  23116. * @override
  23117. * @private
  23118. */
  23119. ;
  23120. _proto._dispatchCommand =
  23121. /*#__PURE__*/
  23122. function () {
  23123. var _dispatchCommand2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
  23124. return regenerator.wrap(function _callee$(_context) {
  23125. while (1) {
  23126. switch (_context.prev = _context.next) {
  23127. case 0:
  23128. this._debug(trim(command), 'received');
  23129. if (command.serverTs && command.notificationType === 1) {
  23130. internal(this).lastNotificationTime = getTime(decodeDate(command.serverTs));
  23131. }
  23132. _context.t0 = command.cmd;
  23133. _context.next = _context.t0 === CommandType.conv ? 5 : _context.t0 === CommandType.direct ? 6 : _context.t0 === CommandType.session ? 7 : _context.t0 === CommandType.unread ? 8 : _context.t0 === CommandType.rcp ? 9 : _context.t0 === CommandType.patch ? 10 : 11;
  23134. break;
  23135. case 5:
  23136. return _context.abrupt("return", this._dispatchConvMessage(command));
  23137. case 6:
  23138. return _context.abrupt("return", this._dispatchDirectMessage(command));
  23139. case 7:
  23140. return _context.abrupt("return", this._dispatchSessionMessage(command));
  23141. case 8:
  23142. return _context.abrupt("return", this._dispatchUnreadMessage(command));
  23143. case 9:
  23144. return _context.abrupt("return", this._dispatchRcpMessage(command));
  23145. case 10:
  23146. return _context.abrupt("return", this._dispatchPatchMessage(command));
  23147. case 11:
  23148. return _context.abrupt("return", this.emit(UNHANDLED_MESSAGE$1, command));
  23149. case 12:
  23150. case "end":
  23151. return _context.stop();
  23152. }
  23153. }
  23154. }, _callee, this);
  23155. }));
  23156. function _dispatchCommand(_x) {
  23157. return _dispatchCommand2.apply(this, arguments);
  23158. }
  23159. return _dispatchCommand;
  23160. }();
  23161. _proto._dispatchSessionMessage = /*#__PURE__*/function () {
  23162. var _dispatchSessionMessage2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message) {
  23163. var _message$sessionMessa, code, reason;
  23164. return regenerator.wrap(function _callee2$(_context2) {
  23165. while (1) {
  23166. switch (_context2.prev = _context2.next) {
  23167. case 0:
  23168. _message$sessionMessa = message.sessionMessage, code = _message$sessionMessa.code, reason = _message$sessionMessa.reason;
  23169. _context2.t0 = message.op;
  23170. _context2.next = _context2.t0 === OpType.closed ? 4 : 8;
  23171. break;
  23172. case 4:
  23173. internal(this)._eventemitter.emit('close');
  23174. if (!(code === ErrorCode.SESSION_CONFLICT)) {
  23175. _context2.next = 7;
  23176. break;
  23177. }
  23178. return _context2.abrupt("return", this.emit(CONFLICT$1, {
  23179. reason: reason
  23180. }));
  23181. case 7:
  23182. return _context2.abrupt("return", this.emit(CLOSE$1, {
  23183. code: code,
  23184. reason: reason
  23185. }));
  23186. case 8:
  23187. this.emit(UNHANDLED_MESSAGE$1, message);
  23188. throw new Error('Unrecognized session command');
  23189. case 10:
  23190. case "end":
  23191. return _context2.stop();
  23192. }
  23193. }
  23194. }, _callee2, this);
  23195. }));
  23196. function _dispatchSessionMessage(_x2) {
  23197. return _dispatchSessionMessage2.apply(this, arguments);
  23198. }
  23199. return _dispatchSessionMessage;
  23200. }();
  23201. _proto._dispatchUnreadMessage = function _dispatchUnreadMessage(_ref) {
  23202. var _this2 = this;
  23203. var _ref$unreadMessage = _ref.unreadMessage,
  23204. convs = _ref$unreadMessage.convs,
  23205. notifTime = _ref$unreadMessage.notifTime;
  23206. internal(this).lastUnreadNotifTime = notifTime; // ensure all converstions are cached
  23207. return this.getConversations(convs.map(function (conv) {
  23208. return conv.cid;
  23209. })).then(function () {
  23210. return (// update conversations data
  23211. Promise.all(convs.map(function (_ref2) {
  23212. var cid = _ref2.cid,
  23213. unread = _ref2.unread,
  23214. mid = _ref2.mid,
  23215. ts = _ref2.timestamp,
  23216. from = _ref2.from,
  23217. data = _ref2.data,
  23218. binaryMsg = _ref2.binaryMsg,
  23219. patchTimestamp = _ref2.patchTimestamp,
  23220. mentioned = _ref2.mentioned;
  23221. var conversation = _this2._conversationCache.get(cid); // deleted conversation
  23222. if (!conversation) return null;
  23223. var timestamp;
  23224. if (ts) {
  23225. timestamp = decodeDate(ts);
  23226. conversation.lastMessageAt = timestamp; // eslint-disable-line no-param-reassign
  23227. }
  23228. return (mid ? _this2._messageParser.parse(binaryMsg || data).then(function (message) {
  23229. var messageProps = {
  23230. id: mid,
  23231. cid: cid,
  23232. timestamp: timestamp,
  23233. updatedAt: patchTimestamp,
  23234. from: from
  23235. };
  23236. Object.assign(message, messageProps);
  23237. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  23238. }) : Promise.resolve()).then(function () {
  23239. conversation._setUnreadMessagesMentioned(mentioned);
  23240. var countNotUpdated = unread === internal(conversation).unreadMessagesCount;
  23241. if (countNotUpdated) return null; // to be filtered
  23242. // manipulate internal property directly to skip unreadmessagescountupdate event
  23243. internal(conversation).unreadMessagesCount = unread;
  23244. return conversation;
  23245. }); // filter conversations without unread count update
  23246. })).then(function (conversations) {
  23247. return conversations.filter(function (conversation) {
  23248. return conversation;
  23249. });
  23250. })
  23251. );
  23252. }).then(function (conversations) {
  23253. if (conversations.length) {
  23254. /**
  23255. * 未读消息数目更新
  23256. * @event IMClient#UNREAD_MESSAGES_COUNT_UPDATE
  23257. * @since 3.4.0
  23258. * @param {Conversation[]} conversations 未读消息数目有更新的对话列表
  23259. */
  23260. _this2.emit(UNREAD_MESSAGES_COUNT_UPDATE$1, conversations);
  23261. }
  23262. });
  23263. };
  23264. _proto._dispatchRcpMessage = /*#__PURE__*/function () {
  23265. var _dispatchRcpMessage2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(message) {
  23266. var rcpMessage, read, conversationId, messageId, timestamp, conversation;
  23267. return regenerator.wrap(function _callee3$(_context3) {
  23268. while (1) {
  23269. switch (_context3.prev = _context3.next) {
  23270. case 0:
  23271. rcpMessage = message.rcpMessage, read = message.rcpMessage.read;
  23272. conversationId = rcpMessage.cid;
  23273. messageId = rcpMessage.id;
  23274. timestamp = decodeDate(rcpMessage.t);
  23275. conversation = this._conversationCache.get(conversationId); // conversation not cached means the client does not send the message
  23276. // during this session
  23277. if (conversation) {
  23278. _context3.next = 7;
  23279. break;
  23280. }
  23281. return _context3.abrupt("return");
  23282. case 7:
  23283. conversation._handleReceipt({
  23284. messageId: messageId,
  23285. timestamp: timestamp,
  23286. read: read
  23287. });
  23288. case 8:
  23289. case "end":
  23290. return _context3.stop();
  23291. }
  23292. }
  23293. }, _callee3, this);
  23294. }));
  23295. function _dispatchRcpMessage(_x3) {
  23296. return _dispatchRcpMessage2.apply(this, arguments);
  23297. }
  23298. return _dispatchRcpMessage;
  23299. }();
  23300. _proto._dispatchPatchMessage = function _dispatchPatchMessage(_ref3) {
  23301. var _this3 = this;
  23302. var patches = _ref3.patchMessage.patches;
  23303. // ensure all converstions are cached
  23304. return this.getConversations(patches.map(function (patch) {
  23305. return patch.cid;
  23306. })).then(function () {
  23307. return Promise.all(patches.map(function (_ref4) {
  23308. var cid = _ref4.cid,
  23309. mid = _ref4.mid,
  23310. timestamp = _ref4.timestamp,
  23311. recall = _ref4.recall,
  23312. data = _ref4.data,
  23313. patchTimestamp = _ref4.patchTimestamp,
  23314. from = _ref4.from,
  23315. binaryMsg = _ref4.binaryMsg,
  23316. mentionAll = _ref4.mentionAll,
  23317. mentionPids = _ref4.mentionPids,
  23318. patchCode = _ref4.patchCode,
  23319. patchReason = _ref4.patchReason;
  23320. var conversation = _this3._conversationCache.get(cid); // deleted conversation
  23321. if (!conversation) return null;
  23322. return _this3._messageParser.parse(binaryMsg || data).then(function (message) {
  23323. var patchTime = getTime(decodeDate(patchTimestamp));
  23324. var messageProps = {
  23325. id: mid,
  23326. cid: cid,
  23327. timestamp: timestamp,
  23328. updatedAt: patchTime,
  23329. from: from,
  23330. mentionList: mentionPids,
  23331. mentionedAll: mentionAll
  23332. };
  23333. Object.assign(message, messageProps);
  23334. message._setStatus(MessageStatus.SENT);
  23335. message._updateMentioned(_this3.id);
  23336. if (internal(_this3).lastPatchTime < patchTime) {
  23337. internal(_this3).lastPatchTime = patchTime;
  23338. } // update conversation lastMessage
  23339. if (conversation.lastMessage && conversation.lastMessage.id === mid) {
  23340. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  23341. }
  23342. var reason;
  23343. if (patchCode) {
  23344. reason = {
  23345. code: patchCode.toNumber(),
  23346. detail: patchReason
  23347. };
  23348. }
  23349. if (recall) {
  23350. /**
  23351. * 消息被撤回
  23352. * @event IMClient#MESSAGE_RECALL
  23353. * @param {AVMessage} message 被撤回的消息
  23354. * @param {ConversationBase} conversation 消息所在的会话
  23355. * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
  23356. */
  23357. _this3.emit(MESSAGE_RECALL$1, message, conversation, reason);
  23358. /**
  23359. * 消息被撤回
  23360. * @event ConversationBase#MESSAGE_RECALL
  23361. * @param {AVMessage} message 被撤回的消息
  23362. * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
  23363. */
  23364. conversation.emit(MESSAGE_RECALL$1, message, reason);
  23365. } else {
  23366. /**
  23367. * 消息被修改
  23368. * @event IMClient#MESSAGE_UPDATE
  23369. * @param {AVMessage} message 被修改的消息
  23370. * @param {ConversationBase} conversation 消息所在的会话
  23371. * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
  23372. */
  23373. _this3.emit(MESSAGE_UPDATE$1, message, conversation, reason);
  23374. /**
  23375. * 消息被修改
  23376. * @event ConversationBase#MESSAGE_UPDATE
  23377. * @param {AVMessage} message 被修改的消息
  23378. * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
  23379. */
  23380. conversation.emit(MESSAGE_UPDATE$1, message, reason);
  23381. }
  23382. });
  23383. }));
  23384. });
  23385. };
  23386. _proto._dispatchConvMessage = /*#__PURE__*/function () {
  23387. var _dispatchConvMessage2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message) {
  23388. var convMessage, _message$convMessage, initBy, m, info, attr, conversation, payload, _payload, _payload2, _payload3, _payload4, _payload5, _payload6, _payload7, _payload8, _payload9, _payload10, _payload11, pid, role, _internal, memberInfoMap, memberInfo, _payload12, attributes, _payload13;
  23389. return regenerator.wrap(function _callee4$(_context4) {
  23390. while (1) {
  23391. switch (_context4.prev = _context4.next) {
  23392. case 0:
  23393. convMessage = message.convMessage, _message$convMessage = message.convMessage, initBy = _message$convMessage.initBy, m = _message$convMessage.m, info = _message$convMessage.info, attr = _message$convMessage.attr;
  23394. _context4.next = 3;
  23395. return this.getConversation(convMessage.cid);
  23396. case 3:
  23397. conversation = _context4.sent;
  23398. _context4.t0 = message.op;
  23399. _context4.next = _context4.t0 === OpType.joined ? 7 : _context4.t0 === OpType.left ? 12 : _context4.t0 === OpType.members_joined ? 17 : _context4.t0 === OpType.members_left ? 22 : _context4.t0 === OpType.members_blocked ? 27 : _context4.t0 === OpType.members_unblocked ? 31 : _context4.t0 === OpType.blocked ? 35 : _context4.t0 === OpType.unblocked ? 39 : _context4.t0 === OpType.members_shutuped ? 43 : _context4.t0 === OpType.members_unshutuped ? 47 : _context4.t0 === OpType.shutuped ? 51 : _context4.t0 === OpType.unshutuped ? 55 : _context4.t0 === OpType.member_info_changed ? 59 : _context4.t0 === OpType.updated ? 71 : 77;
  23400. break;
  23401. case 7:
  23402. conversation._addMembers([this.id]);
  23403. payload = {
  23404. invitedBy: initBy
  23405. };
  23406. /**
  23407. * 当前用户被添加至某个对话
  23408. * @event IMClient#INVITED
  23409. * @param {Object} payload
  23410. * @param {String} payload.invitedBy 邀请者 id
  23411. * @param {ConversationBase} conversation
  23412. */
  23413. this.emit(INVITED$1, payload, conversation);
  23414. /**
  23415. * 当前用户被添加至当前对话
  23416. * @event ConversationBase#INVITED
  23417. * @param {Object} payload
  23418. * @param {String} payload.invitedBy 该移除操作的发起者 id
  23419. */
  23420. conversation.emit(INVITED$1, payload);
  23421. return _context4.abrupt("return");
  23422. case 12:
  23423. conversation._removeMembers([this.id]);
  23424. _payload = {
  23425. kickedBy: initBy
  23426. };
  23427. /**
  23428. * 当前用户被从某个对话中移除
  23429. * @event IMClient#KICKED
  23430. * @param {Object} payload
  23431. * @param {String} payload.kickedBy 该移除操作的发起者 id
  23432. * @param {ConversationBase} conversation
  23433. */
  23434. this.emit(KICKED$1, _payload, conversation);
  23435. /**
  23436. * 当前用户被从当前对话中移除
  23437. * @event ConversationBase#KICKED
  23438. * @param {Object} payload
  23439. * @param {String} payload.kickedBy 该移除操作的发起者 id
  23440. */
  23441. conversation.emit(KICKED$1, _payload);
  23442. return _context4.abrupt("return");
  23443. case 17:
  23444. conversation._addMembers(m);
  23445. _payload2 = {
  23446. invitedBy: initBy,
  23447. members: m
  23448. };
  23449. /**
  23450. * 有用户被添加至某个对话
  23451. * @event IMClient#MEMBERS_JOINED
  23452. * @param {Object} payload
  23453. * @param {String[]} payload.members 被添加的用户 id 列表
  23454. * @param {String} payload.invitedBy 邀请者 id
  23455. * @param {ConversationBase} conversation
  23456. */
  23457. this.emit(MEMBERS_JOINED$1, _payload2, conversation);
  23458. /**
  23459. * 有成员被添加至当前对话
  23460. * @event ConversationBase#MEMBERS_JOINED
  23461. * @param {Object} payload
  23462. * @param {String[]} payload.members 被添加的成员 id 列表
  23463. * @param {String} payload.invitedBy 邀请者 id
  23464. */
  23465. conversation.emit(MEMBERS_JOINED$1, _payload2);
  23466. return _context4.abrupt("return");
  23467. case 22:
  23468. conversation._removeMembers(m);
  23469. _payload3 = {
  23470. kickedBy: initBy,
  23471. members: m
  23472. };
  23473. /**
  23474. * 有成员被从某个对话中移除
  23475. * @event IMClient#MEMBERS_LEFT
  23476. * @param {Object} payload
  23477. * @param {String[]} payload.members 被移除的成员 id 列表
  23478. * @param {String} payload.kickedBy 该移除操作的发起者 id
  23479. * @param {ConversationBase} conversation
  23480. */
  23481. this.emit(MEMBERS_LEFT$1, _payload3, conversation);
  23482. /**
  23483. * 有成员被从当前对话中移除
  23484. * @event ConversationBase#MEMBERS_LEFT
  23485. * @param {Object} payload
  23486. * @param {String[]} payload.members 被移除的成员 id 列表
  23487. * @param {String} payload.kickedBy 该移除操作的发起者 id
  23488. */
  23489. conversation.emit(MEMBERS_LEFT$1, _payload3);
  23490. return _context4.abrupt("return");
  23491. case 27:
  23492. _payload4 = {
  23493. blockedBy: initBy,
  23494. members: m
  23495. };
  23496. /**
  23497. * 有成员被加入某个对话的黑名单
  23498. * @event IMClient#MEMBERS_BLOCKED
  23499. * @param {Object} payload
  23500. * @param {String[]} payload.members 成员 id 列表
  23501. * @param {String} payload.blockedBy 该操作的发起者 id
  23502. * @param {ConversationBase} conversation
  23503. */
  23504. this.emit(MEMBERS_BLOCKED$1, _payload4, conversation);
  23505. /**
  23506. * 有成员被加入当前对话的黑名单
  23507. * @event ConversationBase#MEMBERS_BLOCKED
  23508. * @param {Object} payload
  23509. * @param {String[]} payload.members 成员 id 列表
  23510. * @param {String} payload.blockedBy 该操作的发起者 id
  23511. */
  23512. conversation.emit(MEMBERS_BLOCKED$1, _payload4);
  23513. return _context4.abrupt("return");
  23514. case 31:
  23515. _payload5 = {
  23516. unblockedBy: initBy,
  23517. members: m
  23518. };
  23519. /**
  23520. * 有成员被移出某个对话的黑名单
  23521. * @event IMClient#MEMBERS_UNBLOCKED
  23522. * @param {Object} payload
  23523. * @param {String[]} payload.members 成员 id 列表
  23524. * @param {String} payload.unblockedBy 该操作的发起者 id
  23525. * @param {ConversationBase} conversation
  23526. */
  23527. this.emit(MEMBERS_UNBLOCKED$1, _payload5, conversation);
  23528. /**
  23529. * 有成员被移出当前对话的黑名单
  23530. * @event ConversationBase#MEMBERS_UNBLOCKED
  23531. * @param {Object} payload
  23532. * @param {String[]} payload.members 成员 id 列表
  23533. * @param {String} payload.unblockedBy 该操作的发起者 id
  23534. */
  23535. conversation.emit(MEMBERS_UNBLOCKED$1, _payload5);
  23536. return _context4.abrupt("return");
  23537. case 35:
  23538. _payload6 = {
  23539. blockedBy: initBy
  23540. };
  23541. /**
  23542. * 当前用户被加入某个对话的黑名单
  23543. * @event IMClient#BLOCKED
  23544. * @param {Object} payload
  23545. * @param {String} payload.blockedBy 该操作的发起者 id
  23546. * @param {ConversationBase} conversation
  23547. */
  23548. this.emit(BLOCKED$1, _payload6, conversation);
  23549. /**
  23550. * 当前用户被加入当前对话的黑名单
  23551. * @event ConversationBase#BLOCKED
  23552. * @param {Object} payload
  23553. * @param {String} payload.blockedBy 该操作的发起者 id
  23554. */
  23555. conversation.emit(BLOCKED$1, _payload6);
  23556. return _context4.abrupt("return");
  23557. case 39:
  23558. _payload7 = {
  23559. unblockedBy: initBy
  23560. };
  23561. /**
  23562. * 当前用户被移出某个对话的黑名单
  23563. * @event IMClient#UNBLOCKED
  23564. * @param {Object} payload
  23565. * @param {String} payload.unblockedBy 该操作的发起者 id
  23566. * @param {ConversationBase} conversation
  23567. */
  23568. this.emit(UNBLOCKED$1, _payload7, conversation);
  23569. /**
  23570. * 当前用户被移出当前对话的黑名单
  23571. * @event ConversationBase#UNBLOCKED
  23572. * @param {Object} payload
  23573. * @param {String} payload.unblockedBy 该操作的发起者 id
  23574. */
  23575. conversation.emit(UNBLOCKED$1, _payload7);
  23576. return _context4.abrupt("return");
  23577. case 43:
  23578. _payload8 = {
  23579. mutedBy: initBy,
  23580. members: m
  23581. };
  23582. /**
  23583. * 有成员在某个对话中被禁言
  23584. * @event IMClient#MEMBERS_MUTED
  23585. * @param {Object} payload
  23586. * @param {String[]} payload.members 成员 id 列表
  23587. * @param {String} payload.mutedBy 该操作的发起者 id
  23588. * @param {ConversationBase} conversation
  23589. */
  23590. this.emit(MEMBERS_MUTED$1, _payload8, conversation);
  23591. /**
  23592. * 有成员在当前对话中被禁言
  23593. * @event ConversationBase#MEMBERS_MUTED
  23594. * @param {Object} payload
  23595. * @param {String[]} payload.members 成员 id 列表
  23596. * @param {String} payload.mutedBy 该操作的发起者 id
  23597. */
  23598. conversation.emit(MEMBERS_MUTED$1, _payload8);
  23599. return _context4.abrupt("return");
  23600. case 47:
  23601. _payload9 = {
  23602. unmutedBy: initBy,
  23603. members: m
  23604. };
  23605. /**
  23606. * 有成员在某个对话中被解除禁言
  23607. * @event IMClient#MEMBERS_UNMUTED
  23608. * @param {Object} payload
  23609. * @param {String[]} payload.members 成员 id 列表
  23610. * @param {String} payload.unmutedBy 该操作的发起者 id
  23611. * @param {ConversationBase} conversation
  23612. */
  23613. this.emit(MEMBERS_UNMUTED$1, _payload9, conversation);
  23614. /**
  23615. * 有成员在当前对话中被解除禁言
  23616. * @event ConversationBase#MEMBERS_UNMUTED
  23617. * @param {Object} payload
  23618. * @param {String[]} payload.members 成员 id 列表
  23619. * @param {String} payload.unmutedBy 该操作的发起者 id
  23620. */
  23621. conversation.emit(MEMBERS_UNMUTED$1, _payload9);
  23622. return _context4.abrupt("return");
  23623. case 51:
  23624. _payload10 = {
  23625. mutedBy: initBy
  23626. };
  23627. /**
  23628. * 有成员在某个对话中被禁言
  23629. * @event IMClient#MUTED
  23630. * @param {Object} payload
  23631. * @param {String} payload.mutedBy 该操作的发起者 id
  23632. * @param {ConversationBase} conversation
  23633. */
  23634. this.emit(MUTED$1, _payload10, conversation);
  23635. /**
  23636. * 有成员在当前对话中被禁言
  23637. * @event ConversationBase#MUTED
  23638. * @param {Object} payload
  23639. * @param {String} payload.mutedBy 该操作的发起者 id
  23640. */
  23641. conversation.emit(MUTED$1, _payload10);
  23642. return _context4.abrupt("return");
  23643. case 55:
  23644. _payload11 = {
  23645. unmutedBy: initBy
  23646. };
  23647. /**
  23648. * 有成员在某个对话中被解除禁言
  23649. * @event IMClient#UNMUTED
  23650. * @param {Object} payload
  23651. * @param {String} payload.unmutedBy 该操作的发起者 id
  23652. * @param {ConversationBase} conversation
  23653. */
  23654. this.emit(UNMUTED$1, _payload11, conversation);
  23655. /**
  23656. * 有成员在当前对话中被解除禁言
  23657. * @event ConversationBase#UNMUTED
  23658. * @param {Object} payload
  23659. * @param {String} payload.unmutedBy 该操作的发起者 id
  23660. */
  23661. conversation.emit(UNMUTED$1, _payload11);
  23662. return _context4.abrupt("return");
  23663. case 59:
  23664. pid = info.pid, role = info.role;
  23665. _internal = internal(conversation), memberInfoMap = _internal.memberInfoMap; // 如果不存在缓存,且不是 role 的更新,则不通知
  23666. if (!(!memberInfoMap && !role)) {
  23667. _context4.next = 63;
  23668. break;
  23669. }
  23670. return _context4.abrupt("return");
  23671. case 63:
  23672. _context4.next = 65;
  23673. return conversation.getMemberInfo(pid);
  23674. case 65:
  23675. memberInfo = _context4.sent;
  23676. internal(memberInfo).role = role;
  23677. _payload12 = {
  23678. member: pid,
  23679. memberInfo: memberInfo,
  23680. updatedBy: initBy
  23681. };
  23682. /**
  23683. * 有成员的对话信息被更新
  23684. * @event IMClient#MEMBER_INFO_UPDATED
  23685. * @param {Object} payload
  23686. * @param {String} payload.member 被更新对话信息的成员 id
  23687. * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
  23688. * @param {String} payload.updatedBy 该操作的发起者 id
  23689. * @param {ConversationBase} conversation
  23690. */
  23691. this.emit(MEMBER_INFO_UPDATED$1, _payload12, conversation);
  23692. /**
  23693. * 有成员的对话信息被更新
  23694. * @event ConversationBase#MEMBER_INFO_UPDATED
  23695. * @param {Object} payload
  23696. * @param {String} payload.member 被更新对话信息的成员 id
  23697. * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
  23698. * @param {String} payload.updatedBy 该操作的发起者 id
  23699. */
  23700. conversation.emit(MEMBER_INFO_UPDATED$1, _payload12);
  23701. return _context4.abrupt("return");
  23702. case 71:
  23703. attributes = decode(JSON.parse(attr.data));
  23704. conversation._updateServerAttributes(attributes);
  23705. _payload13 = {
  23706. attributes: attributes,
  23707. updatedBy: initBy
  23708. };
  23709. /**
  23710. * 该对话信息被更新
  23711. * @event IMClient#CONVERSATION_INFO_UPDATED
  23712. * @param {Object} payload
  23713. * @param {Object} payload.attributes 被更新的属性
  23714. * @param {String} payload.updatedBy 该操作的发起者 id
  23715. * @param {ConversationBase} conversation
  23716. */
  23717. this.emit(CONVERSATION_INFO_UPDATED$1, _payload13, conversation);
  23718. /**
  23719. * 有对话信息被更新
  23720. * @event ConversationBase#INFO_UPDATED
  23721. * @param {Object} payload
  23722. * @param {Object} payload.attributes 被更新的属性
  23723. * @param {String} payload.updatedBy 该操作的发起者 id
  23724. */
  23725. conversation.emit(INFO_UPDATED$1, _payload13);
  23726. return _context4.abrupt("return");
  23727. case 77:
  23728. this.emit(UNHANDLED_MESSAGE$1, message);
  23729. throw new Error('Unrecognized conversation command');
  23730. case 79:
  23731. case "end":
  23732. return _context4.stop();
  23733. }
  23734. }
  23735. }, _callee4, this);
  23736. }));
  23737. function _dispatchConvMessage(_x4) {
  23738. return _dispatchConvMessage2.apply(this, arguments);
  23739. }
  23740. return _dispatchConvMessage;
  23741. }();
  23742. _proto._dispatchDirectMessage = function _dispatchDirectMessage(originalMessage) {
  23743. var _this4 = this;
  23744. var directMessage = originalMessage.directMessage,
  23745. _originalMessage$dire = originalMessage.directMessage,
  23746. id = _originalMessage$dire.id,
  23747. cid = _originalMessage$dire.cid,
  23748. fromPeerId = _originalMessage$dire.fromPeerId,
  23749. timestamp = _originalMessage$dire.timestamp,
  23750. _transient = _originalMessage$dire["transient"],
  23751. patchTimestamp = _originalMessage$dire.patchTimestamp,
  23752. mentionPids = _originalMessage$dire.mentionPids,
  23753. mentionAll = _originalMessage$dire.mentionAll,
  23754. binaryMsg = _originalMessage$dire.binaryMsg,
  23755. msg = _originalMessage$dire.msg;
  23756. var content = binaryMsg ? binaryMsg.toArrayBuffer() : msg;
  23757. return Promise.all([this.getConversation(directMessage.cid), this._messageParser.parse(content)]).then(function (_ref5) {
  23758. var _ref6 = slicedToArray(_ref5, 2),
  23759. conversation = _ref6[0],
  23760. message = _ref6[1];
  23761. // deleted conversation
  23762. if (!conversation) return undefined;
  23763. var messageProps = {
  23764. id: id,
  23765. cid: cid,
  23766. timestamp: timestamp,
  23767. updatedAt: patchTimestamp,
  23768. from: fromPeerId,
  23769. mentionList: mentionPids,
  23770. mentionedAll: mentionAll
  23771. };
  23772. Object.assign(message, messageProps);
  23773. message._updateMentioned(_this4.id);
  23774. message._setStatus(MessageStatus.SENT); // filter outgoing message sent from another device
  23775. if (message.from !== _this4.id) {
  23776. if (!(_transient || conversation["transient"])) {
  23777. _this4._sendAck(message);
  23778. }
  23779. }
  23780. return _this4._dispatchParsedMessage(message, conversation);
  23781. });
  23782. };
  23783. _proto._dispatchParsedMessage = function _dispatchParsedMessage(message, conversation) {
  23784. var _this5 = this;
  23785. // beforeMessageDispatch hook
  23786. return applyDispatcher(this._plugins.beforeMessageDispatch, [message, conversation]).then(function (shouldDispatch) {
  23787. if (shouldDispatch === false) return;
  23788. conversation.lastMessage = message; // eslint-disable-line no-param-reassign
  23789. conversation.lastMessageAt = message.timestamp; // eslint-disable-line no-param-reassign
  23790. // filter outgoing message sent from another device
  23791. if (message.from !== _this5.id) {
  23792. conversation.unreadMessagesCount += 1; // eslint-disable-line no-param-reassign
  23793. if (message.mentioned) conversation._setUnreadMessagesMentioned(true);
  23794. }
  23795. /**
  23796. * 当前用户收到消息
  23797. * @event IMClient#MESSAGE
  23798. * @param {Message} message
  23799. * @param {ConversationBase} conversation 收到消息的对话
  23800. */
  23801. _this5.emit(MESSAGE$2, message, conversation);
  23802. /**
  23803. * 当前对话收到消息
  23804. * @event ConversationBase#MESSAGE
  23805. * @param {Message} message
  23806. */
  23807. conversation.emit(MESSAGE$2, message);
  23808. });
  23809. };
  23810. _proto._sendAck = function _sendAck(message) {
  23811. this._debug('send ack for %O', message);
  23812. var cid = message.cid;
  23813. if (!cid) {
  23814. throw new Error('missing cid');
  23815. }
  23816. if (!this._ackMessageBuffer[cid]) {
  23817. this._ackMessageBuffer[cid] = [];
  23818. }
  23819. this._ackMessageBuffer[cid].push(message);
  23820. return this._doSendAck();
  23821. } // jsdoc-ignore-start
  23822. ;
  23823. _proto. // jsdoc-ignore-end
  23824. _doSendAck = function _doSendAck() {
  23825. var _this6 = this;
  23826. // if not connected, just skip everything
  23827. if (!this._connection.is('connected')) return;
  23828. this._debug('do send ack %O', this._ackMessageBuffer);
  23829. Promise.all(Object.keys(this._ackMessageBuffer).map(function (cid) {
  23830. var convAckMessages = _this6._ackMessageBuffer[cid];
  23831. var timestamps = convAckMessages.map(function (message) {
  23832. return message.timestamp;
  23833. });
  23834. var command = new GenericCommand({
  23835. cmd: 'ack',
  23836. ackMessage: new AckCommand({
  23837. cid: cid,
  23838. fromts: Math.min.apply(null, timestamps),
  23839. tots: Math.max.apply(null, timestamps)
  23840. })
  23841. });
  23842. delete _this6._ackMessageBuffer[cid];
  23843. return _this6._send(command, false)["catch"](function (error) {
  23844. _this6._debug('send ack failed: %O', error);
  23845. _this6._ackMessageBuffer[cid] = convAckMessages;
  23846. });
  23847. }));
  23848. };
  23849. _proto._omitPeerId = function _omitPeerId(value) {
  23850. internal(this).peerIdOmittable = value;
  23851. };
  23852. _proto._send = function _send(cmd) {
  23853. var _this$_connection;
  23854. var command = cmd;
  23855. if (!internal(this).peerIdOmittable && this.id) {
  23856. command.peerId = this.id;
  23857. }
  23858. for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  23859. args[_key3 - 1] = arguments[_key3];
  23860. }
  23861. return (_this$_connection = this._connection).send.apply(_this$_connection, [command].concat(args));
  23862. };
  23863. _proto._open = /*#__PURE__*/function () {
  23864. var _open2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(appId, tag, deviceId) {
  23865. var isReconnect,
  23866. _internal2,
  23867. lastUnreadNotifTime,
  23868. lastPatchTime,
  23869. lastNotificationTime,
  23870. command,
  23871. signatureResult,
  23872. sessionToken,
  23873. resCommand,
  23874. _resCommand,
  23875. peerId,
  23876. sessionMessage,
  23877. _resCommand$sessionMe,
  23878. token,
  23879. tokenTTL,
  23880. code,
  23881. serverTs,
  23882. serverTime,
  23883. _args5 = arguments;
  23884. return regenerator.wrap(function _callee5$(_context5) {
  23885. while (1) {
  23886. switch (_context5.prev = _context5.next) {
  23887. case 0:
  23888. isReconnect = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : false;
  23889. this._debug('open session');
  23890. _internal2 = internal(this), lastUnreadNotifTime = _internal2.lastUnreadNotifTime, lastPatchTime = _internal2.lastPatchTime, lastNotificationTime = _internal2.lastNotificationTime;
  23891. command = new GenericCommand({
  23892. cmd: 'session',
  23893. op: 'open',
  23894. appId: appId,
  23895. peerId: this.id,
  23896. sessionMessage: new SessionCommand({
  23897. ua: "js/".concat(version),
  23898. r: isReconnect,
  23899. lastUnreadNotifTime: lastUnreadNotifTime,
  23900. lastPatchTime: lastPatchTime,
  23901. configBitmap: configBitmap
  23902. })
  23903. });
  23904. if (isReconnect) {
  23905. _context5.next = 13;
  23906. break;
  23907. }
  23908. Object.assign(command.sessionMessage, trim({
  23909. tag: tag,
  23910. deviceId: deviceId
  23911. }));
  23912. if (!this.options.signatureFactory) {
  23913. _context5.next = 11;
  23914. break;
  23915. }
  23916. _context5.next = 9;
  23917. return runSignatureFactory(this.options.signatureFactory, [this._identity]);
  23918. case 9:
  23919. signatureResult = _context5.sent;
  23920. Object.assign(command.sessionMessage, keyRemap({
  23921. signature: 's',
  23922. timestamp: 't',
  23923. nonce: 'n'
  23924. }, signatureResult));
  23925. case 11:
  23926. _context5.next = 17;
  23927. break;
  23928. case 13:
  23929. _context5.next = 15;
  23930. return this._sessionManager.getSessionToken({
  23931. autoRefresh: false
  23932. });
  23933. case 15:
  23934. sessionToken = _context5.sent;
  23935. if (sessionToken && sessionToken !== Expirable.EXPIRED) {
  23936. Object.assign(command.sessionMessage, {
  23937. st: sessionToken
  23938. });
  23939. }
  23940. case 17:
  23941. _context5.prev = 17;
  23942. _context5.next = 20;
  23943. return this._send(command);
  23944. case 20:
  23945. resCommand = _context5.sent;
  23946. _context5.next = 32;
  23947. break;
  23948. case 23:
  23949. _context5.prev = 23;
  23950. _context5.t0 = _context5["catch"](17);
  23951. if (!(_context5.t0.code === ErrorCode.SESSION_TOKEN_EXPIRED)) {
  23952. _context5.next = 31;
  23953. break;
  23954. }
  23955. if (this._sessionManager) {
  23956. _context5.next = 28;
  23957. break;
  23958. }
  23959. throw new Error('Unexpected session expiration');
  23960. case 28:
  23961. debug$b('Session token expired, reopening');
  23962. this._sessionManager.revoke();
  23963. return _context5.abrupt("return", this._open(appId, tag, deviceId, isReconnect));
  23964. case 31:
  23965. throw _context5.t0;
  23966. case 32:
  23967. _resCommand = resCommand, peerId = _resCommand.peerId, sessionMessage = _resCommand.sessionMessage, _resCommand$sessionMe = _resCommand.sessionMessage, token = _resCommand$sessionMe.st, tokenTTL = _resCommand$sessionMe.stTtl, code = _resCommand$sessionMe.code, serverTs = _resCommand.serverTs;
  23968. if (!code) {
  23969. _context5.next = 35;
  23970. break;
  23971. }
  23972. throw createError(sessionMessage);
  23973. case 35:
  23974. if (peerId) {
  23975. this.id = peerId;
  23976. if (!this._identity) this._identity = peerId;
  23977. if (token) {
  23978. this._sessionManager = this._sessionManager || this._createSessionManager();
  23979. this._sessionManager.setSessionToken(token, tokenTTL);
  23980. }
  23981. serverTime = getTime(decodeDate(serverTs));
  23982. if (serverTs) {
  23983. internal(this).lastPatchTime = serverTime;
  23984. }
  23985. if (lastNotificationTime) {
  23986. // Do not await for it as this is failable
  23987. this._syncNotifications(lastNotificationTime)["catch"](function (error) {
  23988. return console.warn('Syncing notifications failed:', error);
  23989. });
  23990. } else {
  23991. // Set timestamp to now for next reconnection
  23992. internal(this).lastNotificationTime = serverTime;
  23993. }
  23994. } else {
  23995. console.warn('Unexpected session opened without peerId.');
  23996. }
  23997. return _context5.abrupt("return", undefined);
  23998. case 37:
  23999. case "end":
  24000. return _context5.stop();
  24001. }
  24002. }
  24003. }, _callee5, this, [[17, 23]]);
  24004. }));
  24005. function _open(_x5, _x6, _x7) {
  24006. return _open2.apply(this, arguments);
  24007. }
  24008. return _open;
  24009. }();
  24010. _proto._syncNotifications = /*#__PURE__*/function () {
  24011. var _syncNotifications2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(timestamp) {
  24012. var _this7 = this;
  24013. var _yield$this$_fetchNot, hasMore, notifications;
  24014. return regenerator.wrap(function _callee6$(_context6) {
  24015. while (1) {
  24016. switch (_context6.prev = _context6.next) {
  24017. case 0:
  24018. _context6.next = 2;
  24019. return this._fetchNotifications(timestamp);
  24020. case 2:
  24021. _yield$this$_fetchNot = _context6.sent;
  24022. hasMore = _yield$this$_fetchNot.hasMore;
  24023. notifications = _yield$this$_fetchNot.notifications;
  24024. notifications.forEach(function (notification) {
  24025. var cmd = notification.cmd,
  24026. op = notification.op,
  24027. serverTs = notification.serverTs,
  24028. notificationType = notification.notificationType,
  24029. payload = objectWithoutProperties(notification, ["cmd", "op", "serverTs", "notificationType"]);
  24030. _this7._dispatchCommand(defineProperty({
  24031. cmd: CommandType[cmd],
  24032. op: OpType[op],
  24033. serverTs: serverTs,
  24034. notificationType: notificationType
  24035. }, "".concat(cmd, "Message"), payload));
  24036. });
  24037. if (!hasMore) {
  24038. _context6.next = 8;
  24039. break;
  24040. }
  24041. return _context6.abrupt("return", this._syncNotifications(internal(this).lastNotificationTime));
  24042. case 8:
  24043. return _context6.abrupt("return", undefined);
  24044. case 9:
  24045. case "end":
  24046. return _context6.stop();
  24047. }
  24048. }
  24049. }, _callee6, this);
  24050. }));
  24051. function _syncNotifications(_x8) {
  24052. return _syncNotifications2.apply(this, arguments);
  24053. }
  24054. return _syncNotifications;
  24055. }();
  24056. _proto._fetchNotifications = /*#__PURE__*/function () {
  24057. var _fetchNotifications2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(timestamp) {
  24058. return regenerator.wrap(function _callee7$(_context7) {
  24059. while (1) {
  24060. switch (_context7.prev = _context7.next) {
  24061. case 0:
  24062. return _context7.abrupt("return", this._requestWithSessionToken({
  24063. method: 'GET',
  24064. path: '/rtm/notifications',
  24065. query: {
  24066. start_ts: timestamp,
  24067. notification_type: 'permanent'
  24068. }
  24069. }));
  24070. case 1:
  24071. case "end":
  24072. return _context7.stop();
  24073. }
  24074. }
  24075. }, _callee7, this);
  24076. }));
  24077. function _fetchNotifications(_x9) {
  24078. return _fetchNotifications2.apply(this, arguments);
  24079. }
  24080. return _fetchNotifications;
  24081. }();
  24082. _proto._createSessionManager = function _createSessionManager() {
  24083. var _this8 = this;
  24084. debug$b('create SessionManager');
  24085. return new SessionManager({
  24086. onBeforeGetSessionToken: this._connection.checkConnectionAvailability.bind(this._connection),
  24087. refresh: function refresh(manager, expiredSessionToken) {
  24088. return manager.setSessionTokenAsync(Promise.resolve(new GenericCommand({
  24089. cmd: 'session',
  24090. op: 'refresh',
  24091. sessionMessage: new SessionCommand({
  24092. ua: "js/".concat(version),
  24093. st: expiredSessionToken
  24094. })
  24095. })).then( /*#__PURE__*/function () {
  24096. var _ref7 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(command) {
  24097. var signatureResult;
  24098. return regenerator.wrap(function _callee8$(_context8) {
  24099. while (1) {
  24100. switch (_context8.prev = _context8.next) {
  24101. case 0:
  24102. if (!_this8.options.signatureFactory) {
  24103. _context8.next = 5;
  24104. break;
  24105. }
  24106. _context8.next = 3;
  24107. return runSignatureFactory(_this8.options.signatureFactory, [_this8._identity]);
  24108. case 3:
  24109. signatureResult = _context8.sent;
  24110. Object.assign(command.sessionMessage, keyRemap({
  24111. signature: 's',
  24112. timestamp: 't',
  24113. nonce: 'n'
  24114. }, signatureResult));
  24115. case 5:
  24116. return _context8.abrupt("return", command);
  24117. case 6:
  24118. case "end":
  24119. return _context8.stop();
  24120. }
  24121. }
  24122. }, _callee8);
  24123. }));
  24124. return function (_x10) {
  24125. return _ref7.apply(this, arguments);
  24126. };
  24127. }()).then(_this8._send.bind(_this8)).then(function (_ref8) {
  24128. var _ref8$sessionMessage = _ref8.sessionMessage,
  24129. token = _ref8$sessionMessage.st,
  24130. ttl = _ref8$sessionMessage.stTtl;
  24131. return [token, ttl];
  24132. }));
  24133. }
  24134. });
  24135. };
  24136. _proto._requestWithSessionToken = /*#__PURE__*/function () {
  24137. var _requestWithSessionToken2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(_ref9) {
  24138. var headers, query, params, sessionToken;
  24139. return regenerator.wrap(function _callee9$(_context9) {
  24140. while (1) {
  24141. switch (_context9.prev = _context9.next) {
  24142. case 0:
  24143. headers = _ref9.headers, query = _ref9.query, params = objectWithoutProperties(_ref9, ["headers", "query"]);
  24144. _context9.next = 3;
  24145. return this._sessionManager.getSessionToken();
  24146. case 3:
  24147. sessionToken = _context9.sent;
  24148. return _context9.abrupt("return", this._request(_objectSpread$8({
  24149. headers: _objectSpread$8({
  24150. 'X-LC-IM-Session-Token': sessionToken
  24151. }, headers),
  24152. query: _objectSpread$8({
  24153. client_id: this.id
  24154. }, query)
  24155. }, params)));
  24156. case 5:
  24157. case "end":
  24158. return _context9.stop();
  24159. }
  24160. }
  24161. }, _callee9, this);
  24162. }));
  24163. function _requestWithSessionToken(_x11) {
  24164. return _requestWithSessionToken2.apply(this, arguments);
  24165. }
  24166. return _requestWithSessionToken;
  24167. }()
  24168. /**
  24169. * 关闭客户端
  24170. * @return {Promise}
  24171. */
  24172. ;
  24173. _proto.close =
  24174. /*#__PURE__*/
  24175. function () {
  24176. var _close = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
  24177. var _ee, command;
  24178. return regenerator.wrap(function _callee10$(_context10) {
  24179. while (1) {
  24180. switch (_context10.prev = _context10.next) {
  24181. case 0:
  24182. this._debug('close session');
  24183. _ee = internal(this)._eventemitter;
  24184. _ee.emit('beforeclose');
  24185. if (!this._connection.is('connected')) {
  24186. _context10.next = 7;
  24187. break;
  24188. }
  24189. command = new GenericCommand({
  24190. cmd: 'session',
  24191. op: 'close'
  24192. });
  24193. _context10.next = 7;
  24194. return this._send(command);
  24195. case 7:
  24196. _ee.emit('close');
  24197. this.emit(CLOSE$1, {
  24198. code: 0
  24199. });
  24200. case 9:
  24201. case "end":
  24202. return _context10.stop();
  24203. }
  24204. }
  24205. }, _callee10, this);
  24206. }));
  24207. function close() {
  24208. return _close.apply(this, arguments);
  24209. }
  24210. return close;
  24211. }()
  24212. /**
  24213. * 获取 client 列表中在线的 client,每次查询最多 20 个 clientId,超出部分会被忽略
  24214. * @param {String[]} clientIds 要查询的 client ids
  24215. * @return {Primse.<String[]>} 在线的 client ids
  24216. */
  24217. ;
  24218. _proto.ping =
  24219. /*#__PURE__*/
  24220. function () {
  24221. var _ping = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
  24222. var command, resCommand;
  24223. return regenerator.wrap(function _callee11$(_context11) {
  24224. while (1) {
  24225. switch (_context11.prev = _context11.next) {
  24226. case 0:
  24227. this._debug('ping');
  24228. if (clientIds instanceof Array) {
  24229. _context11.next = 3;
  24230. break;
  24231. }
  24232. throw new TypeError("clientIds ".concat(clientIds, " is not an Array"));
  24233. case 3:
  24234. if (clientIds.length) {
  24235. _context11.next = 5;
  24236. break;
  24237. }
  24238. return _context11.abrupt("return", Promise.resolve([]));
  24239. case 5:
  24240. command = new GenericCommand({
  24241. cmd: 'session',
  24242. op: 'query',
  24243. sessionMessage: new SessionCommand({
  24244. sessionPeerIds: clientIds
  24245. })
  24246. });
  24247. _context11.next = 8;
  24248. return this._send(command);
  24249. case 8:
  24250. resCommand = _context11.sent;
  24251. return _context11.abrupt("return", resCommand.sessionMessage.onlineSessionPeerIds);
  24252. case 10:
  24253. case "end":
  24254. return _context11.stop();
  24255. }
  24256. }
  24257. }, _callee11, this);
  24258. }));
  24259. function ping(_x12) {
  24260. return _ping.apply(this, arguments);
  24261. }
  24262. return ping;
  24263. }()
  24264. /**
  24265. * 获取某个特定的对话
  24266. * @param {String} id 对话 id,对应 _Conversation 表中的 objectId
  24267. * @param {Boolean} [noCache=false] 强制不从缓存中获取
  24268. * @return {Promise.<ConversationBase>} 如果 id 对应的对话不存在则返回 null
  24269. */
  24270. ;
  24271. _proto.getConversation =
  24272. /*#__PURE__*/
  24273. function () {
  24274. var _getConversation = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(id) {
  24275. var noCache,
  24276. cachedConversation,
  24277. _args12 = arguments;
  24278. return regenerator.wrap(function _callee12$(_context12) {
  24279. while (1) {
  24280. switch (_context12.prev = _context12.next) {
  24281. case 0:
  24282. noCache = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : false;
  24283. if (!(typeof id !== 'string')) {
  24284. _context12.next = 3;
  24285. break;
  24286. }
  24287. throw new TypeError("".concat(id, " is not a String"));
  24288. case 3:
  24289. if (noCache) {
  24290. _context12.next = 7;
  24291. break;
  24292. }
  24293. cachedConversation = this._conversationCache.get(id);
  24294. if (!cachedConversation) {
  24295. _context12.next = 7;
  24296. break;
  24297. }
  24298. return _context12.abrupt("return", cachedConversation);
  24299. case 7:
  24300. if (!isTemporaryConversatrionId(id)) {
  24301. _context12.next = 14;
  24302. break;
  24303. }
  24304. _context12.next = 10;
  24305. return this._getTemporaryConversations([id]);
  24306. case 10:
  24307. _context12.t0 = _context12.sent[0];
  24308. if (_context12.t0) {
  24309. _context12.next = 13;
  24310. break;
  24311. }
  24312. _context12.t0 = null;
  24313. case 13:
  24314. return _context12.abrupt("return", _context12.t0);
  24315. case 14:
  24316. return _context12.abrupt("return", this.getQuery().equalTo('objectId', id).find().then(function (conversations) {
  24317. return conversations[0] || null;
  24318. }));
  24319. case 15:
  24320. case "end":
  24321. return _context12.stop();
  24322. }
  24323. }
  24324. }, _callee12, this);
  24325. }));
  24326. function getConversation(_x13) {
  24327. return _getConversation.apply(this, arguments);
  24328. }
  24329. return getConversation;
  24330. }()
  24331. /**
  24332. * 通过 id 批量获取某个特定的对话
  24333. * @since 3.4.0
  24334. * @param {String[]} ids 对话 id 列表,对应 _Conversation 表中的 objectId
  24335. * @param {Boolean} [noCache=false] 强制不从缓存中获取
  24336. * @return {Promise.<ConversationBase[]>} 如果 id 对应的对话不存在则返回 null
  24337. */
  24338. ;
  24339. _proto.getConversations =
  24340. /*#__PURE__*/
  24341. function () {
  24342. var _getConversations = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13(ids) {
  24343. var _this9 = this;
  24344. var noCache,
  24345. remoteConversationIds,
  24346. remoteTemporaryConversationIds,
  24347. query,
  24348. remoteTemporaryConversationsPromise,
  24349. _args13 = arguments;
  24350. return regenerator.wrap(function _callee13$(_context13) {
  24351. while (1) {
  24352. switch (_context13.prev = _context13.next) {
  24353. case 0:
  24354. noCache = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : false;
  24355. remoteConversationIds = noCache ? ids : ids.filter(function (id) {
  24356. return _this9._conversationCache.get(id) === null;
  24357. });
  24358. if (!remoteConversationIds.length) {
  24359. _context13.next = 9;
  24360. break;
  24361. }
  24362. remoteTemporaryConversationIds = remove_1(remoteConversationIds, isTemporaryConversatrionId);
  24363. query = [];
  24364. if (remoteConversationIds.length) {
  24365. query.push(this.getQuery().containedIn('objectId', remoteConversationIds).limit(999).find());
  24366. }
  24367. if (remoteTemporaryConversationIds.length) {
  24368. remoteTemporaryConversationsPromise = remoteTemporaryConversationIds.map(this._getTemporaryConversations.bind(this));
  24369. query.push.apply(query, toConsumableArray(remoteTemporaryConversationsPromise));
  24370. }
  24371. _context13.next = 9;
  24372. return Promise.all(query);
  24373. case 9:
  24374. return _context13.abrupt("return", ids.map(function (id) {
  24375. return _this9._conversationCache.get(id);
  24376. }));
  24377. case 10:
  24378. case "end":
  24379. return _context13.stop();
  24380. }
  24381. }
  24382. }, _callee13, this);
  24383. }));
  24384. function getConversations(_x14) {
  24385. return _getConversations.apply(this, arguments);
  24386. }
  24387. return getConversations;
  24388. }();
  24389. _proto._getTemporaryConversations = /*#__PURE__*/function () {
  24390. var _getTemporaryConversations2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(ids) {
  24391. var command, resCommand;
  24392. return regenerator.wrap(function _callee14$(_context14) {
  24393. while (1) {
  24394. switch (_context14.prev = _context14.next) {
  24395. case 0:
  24396. command = new GenericCommand({
  24397. cmd: 'conv',
  24398. op: 'query',
  24399. convMessage: new ConvCommand({
  24400. tempConvIds: ids
  24401. })
  24402. });
  24403. _context14.next = 3;
  24404. return this._send(command);
  24405. case 3:
  24406. resCommand = _context14.sent;
  24407. return _context14.abrupt("return", this._handleQueryResults(resCommand));
  24408. case 5:
  24409. case "end":
  24410. return _context14.stop();
  24411. }
  24412. }
  24413. }, _callee14, this);
  24414. }));
  24415. function _getTemporaryConversations(_x15) {
  24416. return _getTemporaryConversations2.apply(this, arguments);
  24417. }
  24418. return _getTemporaryConversations;
  24419. }()
  24420. /**
  24421. * 构造一个 ConversationQuery 来查询对话
  24422. * @return {ConversationQuery.<PersistentConversation>}
  24423. */
  24424. ;
  24425. _proto.getQuery = function getQuery() {
  24426. return new ConversationQuery(this);
  24427. }
  24428. /**
  24429. * 构造一个 ConversationQuery 来查询聊天室
  24430. * @return {ConversationQuery.<ChatRoom>}
  24431. */
  24432. ;
  24433. _proto.getChatRoomQuery = function getChatRoomQuery() {
  24434. return this.getQuery().equalTo('tr', true);
  24435. }
  24436. /**
  24437. * 构造一个 ConversationQuery 来查询服务号
  24438. * @return {ConversationQuery.<ServiceConversation>}
  24439. */
  24440. ;
  24441. _proto.getServiceConversationQuery = function getServiceConversationQuery() {
  24442. return this.getQuery().equalTo('sys', true);
  24443. };
  24444. _proto._executeQuery = /*#__PURE__*/function () {
  24445. var _executeQuery2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(query) {
  24446. var queryJSON, command, resCommand;
  24447. return regenerator.wrap(function _callee15$(_context15) {
  24448. while (1) {
  24449. switch (_context15.prev = _context15.next) {
  24450. case 0:
  24451. queryJSON = query.toJSON();
  24452. queryJSON.where = new JsonObjectMessage({
  24453. data: JSON.stringify(encode(queryJSON.where))
  24454. });
  24455. command = new GenericCommand({
  24456. cmd: 'conv',
  24457. op: 'query',
  24458. convMessage: new ConvCommand(queryJSON)
  24459. });
  24460. _context15.next = 5;
  24461. return this._send(command);
  24462. case 5:
  24463. resCommand = _context15.sent;
  24464. return _context15.abrupt("return", this._handleQueryResults(resCommand));
  24465. case 7:
  24466. case "end":
  24467. return _context15.stop();
  24468. }
  24469. }
  24470. }, _callee15, this);
  24471. }));
  24472. function _executeQuery(_x16) {
  24473. return _executeQuery2.apply(this, arguments);
  24474. }
  24475. return _executeQuery;
  24476. }();
  24477. _proto._handleQueryResults = /*#__PURE__*/function () {
  24478. var _handleQueryResults2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16(resCommand) {
  24479. var conversations, commandString;
  24480. return regenerator.wrap(function _callee16$(_context16) {
  24481. while (1) {
  24482. switch (_context16.prev = _context16.next) {
  24483. case 0:
  24484. _context16.prev = 0;
  24485. conversations = decode(JSON.parse(resCommand.convMessage.results.data));
  24486. _context16.next = 8;
  24487. break;
  24488. case 4:
  24489. _context16.prev = 4;
  24490. _context16.t0 = _context16["catch"](0);
  24491. commandString = JSON.stringify(trim(resCommand));
  24492. throw new Error("Parse query result failed: ".concat(_context16.t0.message, ". Command: ").concat(commandString));
  24493. case 8:
  24494. _context16.next = 10;
  24495. return Promise.all(conversations.map(this._parseConversationFromRawData.bind(this)));
  24496. case 10:
  24497. conversations = _context16.sent;
  24498. return _context16.abrupt("return", conversations.map(this._upsertConversationToCache.bind(this)));
  24499. case 12:
  24500. case "end":
  24501. return _context16.stop();
  24502. }
  24503. }
  24504. }, _callee16, this, [[0, 4]]);
  24505. }));
  24506. function _handleQueryResults(_x17) {
  24507. return _handleQueryResults2.apply(this, arguments);
  24508. }
  24509. return _handleQueryResults;
  24510. }();
  24511. _proto._upsertConversationToCache = function _upsertConversationToCache(fetchedConversation) {
  24512. var conversation = this._conversationCache.get(fetchedConversation.id);
  24513. if (!conversation) {
  24514. conversation = fetchedConversation;
  24515. this._debug('no match, set cache');
  24516. this._conversationCache.set(fetchedConversation.id, fetchedConversation);
  24517. } else {
  24518. this._debug('update cached conversation');
  24519. ['creator', 'createdAt', 'updatedAt', 'lastMessageAt', 'lastMessage', 'mutedMembers', 'members', '_attributes', 'transient', 'muted'].forEach(function (key) {
  24520. var value = fetchedConversation[key];
  24521. if (value !== undefined) conversation[key] = value;
  24522. });
  24523. if (conversation._reset) conversation._reset();
  24524. }
  24525. return conversation;
  24526. }
  24527. /**
  24528. * 反序列化消息,与 {@link Message#toFullJSON} 相对。
  24529. * @param {Object}
  24530. * @return {AVMessage} 解析后的消息
  24531. * @since 4.0.0
  24532. */
  24533. ;
  24534. _proto.parseMessage =
  24535. /*#__PURE__*/
  24536. function () {
  24537. var _parseMessage = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee17(_ref10) {
  24538. var data, _ref10$bin, bin, properties, content, message;
  24539. return regenerator.wrap(function _callee17$(_context17) {
  24540. while (1) {
  24541. switch (_context17.prev = _context17.next) {
  24542. case 0:
  24543. data = _ref10.data, _ref10$bin = _ref10.bin, bin = _ref10$bin === void 0 ? false : _ref10$bin, properties = objectWithoutProperties(_ref10, ["data", "bin"]);
  24544. content = bin ? base64Arraybuffer_2(data) : data;
  24545. _context17.next = 4;
  24546. return this._messageParser.parse(content);
  24547. case 4:
  24548. message = _context17.sent;
  24549. Object.assign(message, properties);
  24550. message._updateMentioned(this.id);
  24551. return _context17.abrupt("return", message);
  24552. case 8:
  24553. case "end":
  24554. return _context17.stop();
  24555. }
  24556. }
  24557. }, _callee17, this);
  24558. }));
  24559. function parseMessage(_x18) {
  24560. return _parseMessage.apply(this, arguments);
  24561. }
  24562. return parseMessage;
  24563. }()
  24564. /**
  24565. * 反序列化对话,与 {@link Conversation#toFullJSON} 相对。
  24566. * @param {Object}
  24567. * @return {ConversationBase} 解析后的对话
  24568. * @since 4.0.0
  24569. */
  24570. ;
  24571. _proto.parseConversation =
  24572. /*#__PURE__*/
  24573. function () {
  24574. var _parseConversation = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee18(_ref11) {
  24575. var id, lastMessageAt, lastMessage, lastDeliveredAt, lastReadAt, unreadMessagesCount, members, mentioned, properties, conversationData, _transient2, system, expiredAt;
  24576. return regenerator.wrap(function _callee18$(_context18) {
  24577. while (1) {
  24578. switch (_context18.prev = _context18.next) {
  24579. case 0:
  24580. id = _ref11.id, lastMessageAt = _ref11.lastMessageAt, lastMessage = _ref11.lastMessage, lastDeliveredAt = _ref11.lastDeliveredAt, lastReadAt = _ref11.lastReadAt, unreadMessagesCount = _ref11.unreadMessagesCount, members = _ref11.members, mentioned = _ref11.mentioned, properties = objectWithoutProperties(_ref11, ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"]);
  24581. conversationData = {
  24582. id: id,
  24583. lastMessageAt: lastMessageAt,
  24584. lastMessage: lastMessage,
  24585. lastDeliveredAt: lastDeliveredAt,
  24586. lastReadAt: lastReadAt,
  24587. unreadMessagesCount: unreadMessagesCount,
  24588. members: members,
  24589. mentioned: mentioned
  24590. };
  24591. if (!lastMessage) {
  24592. _context18.next = 7;
  24593. break;
  24594. }
  24595. _context18.next = 5;
  24596. return this.parseMessage(lastMessage);
  24597. case 5:
  24598. conversationData.lastMessage = _context18.sent;
  24599. conversationData.lastMessage._setStatus(MessageStatus.SENT);
  24600. case 7:
  24601. _transient2 = properties["transient"], system = properties.system, expiredAt = properties.expiredAt;
  24602. if (!_transient2) {
  24603. _context18.next = 10;
  24604. break;
  24605. }
  24606. return _context18.abrupt("return", new ChatRoom(conversationData, properties, this));
  24607. case 10:
  24608. if (!system) {
  24609. _context18.next = 12;
  24610. break;
  24611. }
  24612. return _context18.abrupt("return", new ServiceConversation(conversationData, properties, this));
  24613. case 12:
  24614. if (!(expiredAt || isTemporaryConversatrionId(id))) {
  24615. _context18.next = 14;
  24616. break;
  24617. }
  24618. return _context18.abrupt("return", new TemporaryConversation(conversationData, {
  24619. expiredAt: expiredAt
  24620. }, this));
  24621. case 14:
  24622. return _context18.abrupt("return", new Conversation(conversationData, properties, this));
  24623. case 15:
  24624. case "end":
  24625. return _context18.stop();
  24626. }
  24627. }
  24628. }, _callee18, this);
  24629. }));
  24630. function parseConversation(_x19) {
  24631. return _parseConversation.apply(this, arguments);
  24632. }
  24633. return parseConversation;
  24634. }();
  24635. _proto._parseConversationFromRawData = /*#__PURE__*/function () {
  24636. var _parseConversationFromRawData2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee19(rawData) {
  24637. var data, ttl;
  24638. return regenerator.wrap(function _callee19$(_context19) {
  24639. while (1) {
  24640. switch (_context19.prev = _context19.next) {
  24641. case 0:
  24642. data = keyRemap({
  24643. objectId: 'id',
  24644. lm: 'lastMessageAt',
  24645. m: 'members',
  24646. tr: 'transient',
  24647. sys: 'system',
  24648. c: 'creator',
  24649. mu: 'mutedMembers'
  24650. }, rawData);
  24651. if (data.msg) {
  24652. data.lastMessage = {
  24653. data: data.msg,
  24654. bin: data.bin,
  24655. from: data.msg_from,
  24656. id: data.msg_mid,
  24657. timestamp: data.msg_timestamp,
  24658. updatedAt: data.patch_timestamp
  24659. };
  24660. delete data.lastMessageFrom;
  24661. delete data.lastMessageId;
  24662. delete data.lastMessageTimestamp;
  24663. delete data.lastMessagePatchTimestamp;
  24664. }
  24665. ttl = data.ttl;
  24666. if (ttl) data.expiredAt = Date.now() + ttl * 1000;
  24667. return _context19.abrupt("return", this.parseConversation(data));
  24668. case 5:
  24669. case "end":
  24670. return _context19.stop();
  24671. }
  24672. }
  24673. }, _callee19, this);
  24674. }));
  24675. function _parseConversationFromRawData(_x20) {
  24676. return _parseConversationFromRawData2.apply(this, arguments);
  24677. }
  24678. return _parseConversationFromRawData;
  24679. }()
  24680. /**
  24681. * 创建一个对话
  24682. * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
  24683. * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
  24684. * @param {String} [options.name] 对话的名字
  24685. * @param {Boolean} [options.unique=true] 唯一对话,当其为 true 时,如果当前已经有相同成员的对话存在则返回该对话,否则会创建新的对话
  24686. * @return {Promise.<Conversation>}
  24687. */
  24688. ;
  24689. _proto.createConversation =
  24690. /*#__PURE__*/
  24691. function () {
  24692. var _createConversation = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee20() {
  24693. var _ref12,
  24694. m,
  24695. name,
  24696. _transient3,
  24697. _ref12$unique,
  24698. unique,
  24699. tempConv,
  24700. tempConvTTL,
  24701. properties,
  24702. members,
  24703. attr,
  24704. startCommandJson,
  24705. command,
  24706. params,
  24707. signatureResult,
  24708. _yield$this$_send,
  24709. _yield$this$_send$con,
  24710. cid,
  24711. cdate,
  24712. ttl,
  24713. data,
  24714. conversation,
  24715. _args20 = arguments;
  24716. return regenerator.wrap(function _callee20$(_context20) {
  24717. while (1) {
  24718. switch (_context20.prev = _context20.next) {
  24719. case 0:
  24720. _ref12 = _args20.length > 0 && _args20[0] !== undefined ? _args20[0] : {}, m = _ref12.members, name = _ref12.name, _transient3 = _ref12["transient"], _ref12$unique = _ref12.unique, unique = _ref12$unique === void 0 ? true : _ref12$unique, tempConv = _ref12._tempConv, tempConvTTL = _ref12._tempConvTTL, properties = objectWithoutProperties(_ref12, ["members", "name", "transient", "unique", "_tempConv", "_tempConvTTL"]);
  24721. if (_transient3 || Array.isArray(m)) {
  24722. _context20.next = 3;
  24723. break;
  24724. }
  24725. throw new TypeError("conversation members ".concat(m, " is not an array"));
  24726. case 3:
  24727. members = new Set(m);
  24728. members.add(this.id);
  24729. members = Array.from(members).sort();
  24730. attr = properties || {};
  24731. if (!name) {
  24732. _context20.next = 11;
  24733. break;
  24734. }
  24735. if (!(typeof name !== 'string')) {
  24736. _context20.next = 10;
  24737. break;
  24738. }
  24739. throw new TypeError("conversation name ".concat(name, " is not a string"));
  24740. case 10:
  24741. attr.name = name;
  24742. case 11:
  24743. attr = new JsonObjectMessage({
  24744. data: JSON.stringify(encode(attr))
  24745. });
  24746. startCommandJson = {
  24747. m: members,
  24748. attr: attr,
  24749. "transient": _transient3,
  24750. unique: unique,
  24751. tempConv: tempConv,
  24752. tempConvTTL: tempConvTTL
  24753. };
  24754. command = new GenericCommand({
  24755. cmd: 'conv',
  24756. op: 'start',
  24757. convMessage: new ConvCommand(startCommandJson)
  24758. });
  24759. if (!this.options.conversationSignatureFactory) {
  24760. _context20.next = 20;
  24761. break;
  24762. }
  24763. params = [null, this._identity, members, 'create'];
  24764. _context20.next = 18;
  24765. return runSignatureFactory(this.options.conversationSignatureFactory, params);
  24766. case 18:
  24767. signatureResult = _context20.sent;
  24768. Object.assign(command.convMessage, keyRemap({
  24769. signature: 's',
  24770. timestamp: 't',
  24771. nonce: 'n'
  24772. }, signatureResult));
  24773. case 20:
  24774. _context20.next = 22;
  24775. return this._send(command);
  24776. case 22:
  24777. _yield$this$_send = _context20.sent;
  24778. _yield$this$_send$con = _yield$this$_send.convMessage;
  24779. cid = _yield$this$_send$con.cid;
  24780. cdate = _yield$this$_send$con.cdate;
  24781. ttl = _yield$this$_send$con.tempConvTTL;
  24782. data = _objectSpread$8({
  24783. name: name,
  24784. "transient": _transient3,
  24785. unique: unique,
  24786. id: cid,
  24787. createdAt: cdate,
  24788. updatedAt: cdate,
  24789. lastMessageAt: null,
  24790. creator: this.id,
  24791. members: _transient3 ? [] : members
  24792. }, properties);
  24793. if (ttl) data.expiredAt = Date.now() + ttl * 1000;
  24794. _context20.next = 31;
  24795. return this.parseConversation(data);
  24796. case 31:
  24797. conversation = _context20.sent;
  24798. return _context20.abrupt("return", this._upsertConversationToCache(conversation));
  24799. case 33:
  24800. case "end":
  24801. return _context20.stop();
  24802. }
  24803. }
  24804. }, _callee20, this);
  24805. }));
  24806. function createConversation() {
  24807. return _createConversation.apply(this, arguments);
  24808. }
  24809. return createConversation;
  24810. }()
  24811. /**
  24812. * 创建一个聊天室
  24813. * @since 4.0.0
  24814. * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
  24815. * @param {String} [options.name] 对话的名字
  24816. * @return {Promise.<ChatRoom>}
  24817. */
  24818. ;
  24819. _proto.createChatRoom =
  24820. /*#__PURE__*/
  24821. function () {
  24822. var _createChatRoom = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee21(param) {
  24823. return regenerator.wrap(function _callee21$(_context21) {
  24824. while (1) {
  24825. switch (_context21.prev = _context21.next) {
  24826. case 0:
  24827. return _context21.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
  24828. "transient": true,
  24829. members: null,
  24830. unique: false,
  24831. _tempConv: false
  24832. })));
  24833. case 1:
  24834. case "end":
  24835. return _context21.stop();
  24836. }
  24837. }
  24838. }, _callee21, this);
  24839. }));
  24840. function createChatRoom(_x21) {
  24841. return _createChatRoom.apply(this, arguments);
  24842. }
  24843. return createChatRoom;
  24844. }()
  24845. /**
  24846. * 创建一个临时对话
  24847. * @since 4.0.0
  24848. * @param {Object} options
  24849. * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
  24850. * @param {String} [options.ttl] 对话存在时间,单位为秒,最大值与默认值均为 86400(一天),过期后该对话不再可用。
  24851. * @return {Promise.<TemporaryConversation>}
  24852. */
  24853. ;
  24854. _proto.createTemporaryConversation =
  24855. /*#__PURE__*/
  24856. function () {
  24857. var _createTemporaryConversation = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee22(_ref13) {
  24858. var _tempConvTTL, param;
  24859. return regenerator.wrap(function _callee22$(_context22) {
  24860. while (1) {
  24861. switch (_context22.prev = _context22.next) {
  24862. case 0:
  24863. _tempConvTTL = _ref13.ttl, param = objectWithoutProperties(_ref13, ["ttl"]);
  24864. return _context22.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
  24865. _tempConv: true,
  24866. _tempConvTTL: _tempConvTTL
  24867. })));
  24868. case 2:
  24869. case "end":
  24870. return _context22.stop();
  24871. }
  24872. }
  24873. }, _callee22, this);
  24874. }));
  24875. function createTemporaryConversation(_x22) {
  24876. return _createTemporaryConversation.apply(this, arguments);
  24877. }
  24878. return createTemporaryConversation;
  24879. }() // jsdoc-ignore-start
  24880. ;
  24881. _proto. // jsdoc-ignore-end
  24882. _doSendRead = function _doSendRead() {
  24883. var _this10 = this;
  24884. // if not connected, just skip everything
  24885. if (!this._connection.is('connected')) return;
  24886. var buffer = internal(this).readConversationsBuffer;
  24887. var conversations = Array.from(buffer);
  24888. if (!conversations.length) return;
  24889. var ids = conversations.map(function (conversation) {
  24890. if (!(conversation instanceof ConversationBase)) {
  24891. throw new TypeError("".concat(conversation, " is not a Conversation"));
  24892. }
  24893. return conversation.id;
  24894. });
  24895. this._debug("mark [".concat(ids, "] as read"));
  24896. buffer.clear();
  24897. this._sendReadCommand(conversations)["catch"](function (error) {
  24898. _this10._debug('send read failed: %O', error);
  24899. conversations.forEach(buffer.add.bind(buffer));
  24900. });
  24901. };
  24902. _proto._sendReadCommand = function _sendReadCommand(conversations) {
  24903. var _this11 = this;
  24904. return this._send(new GenericCommand({
  24905. cmd: 'read',
  24906. readMessage: new ReadCommand({
  24907. convs: conversations.map(function (conversation) {
  24908. return new ReadTuple({
  24909. cid: conversation.id,
  24910. mid: conversation.lastMessage && conversation.lastMessage.from !== _this11.id ? conversation.lastMessage.id : undefined,
  24911. timestamp: (conversation.lastMessageAt || new Date()).getTime()
  24912. });
  24913. })
  24914. })
  24915. }), false);
  24916. };
  24917. return IMClient;
  24918. }(eventemitter3), (applyDecoratedDescriptor(_class$3.prototype, "_doSendAck", [_dec$2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendAck"), _class$3.prototype), applyDecoratedDescriptor(_class$3.prototype, "_doSendRead", [_dec2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendRead"), _class$3.prototype)), _class$3));
  24919. /**
  24920. * 修改、撤回消息的原因
  24921. * @typedef PatchReason
  24922. * @type {Object}
  24923. * @property {number} code 负数为内置 code,正数为开发者在 hook 中自定义的 code。比如因为敏感词过滤被修改的 code 为 -4408。
  24924. * @property {string} [detail] 具体的原因说明。
  24925. */
  24926. var RECONNECT_ERROR = 'reconnecterror';
  24927. var CoreEvent = /*#__PURE__*/Object.freeze({
  24928. __proto__: null,
  24929. RECONNECT_ERROR: RECONNECT_ERROR,
  24930. DISCONNECT: DISCONNECT,
  24931. RECONNECT: RECONNECT,
  24932. RETRY: RETRY,
  24933. SCHEDULE: SCHEDULE,
  24934. OFFLINE: OFFLINE,
  24935. ONLINE: ONLINE
  24936. });
  24937. var _class$4;
  24938. function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  24939. function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$9(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  24940. var // jsdoc-ignore-end
  24941. BinaryMessage = IE10Compatible(_class$4 = /*#__PURE__*/function (_Message) {
  24942. inheritsLoose(BinaryMessage, _Message);
  24943. /**
  24944. * 二进制消息
  24945. * @extends Message
  24946. * @param {ArrayBuffer} buffer
  24947. * @since 4.0.0
  24948. */
  24949. function BinaryMessage(buffer) {
  24950. if (!(buffer instanceof ArrayBuffer)) {
  24951. throw new TypeError("".concat(buffer, " is not an ArrayBuffer"));
  24952. }
  24953. return _Message.call(this, buffer) || this;
  24954. }
  24955. /**
  24956. * @type ArrayBuffer
  24957. */
  24958. BinaryMessage.validate = function validate(target) {
  24959. return target instanceof ArrayBuffer;
  24960. };
  24961. var _proto = BinaryMessage.prototype;
  24962. _proto.toJSON = function toJSON() {
  24963. return _objectSpread$9(_objectSpread$9({}, _Message.prototype._toJSON.call(this)), {}, {
  24964. data: base64Arraybuffer_1(this.content)
  24965. });
  24966. };
  24967. _proto.toFullJSON = function toFullJSON() {
  24968. return _objectSpread$9(_objectSpread$9({}, _Message.prototype.toFullJSON.call(this)), {}, {
  24969. bin: true,
  24970. data: base64Arraybuffer_1(this.content)
  24971. });
  24972. };
  24973. createClass(BinaryMessage, [{
  24974. key: "buffer",
  24975. get: function get() {
  24976. return this.content;
  24977. },
  24978. set: function set(buffer) {
  24979. this.content = buffer;
  24980. }
  24981. }]);
  24982. return BinaryMessage;
  24983. }(Message)) || _class$4;
  24984. var _dec$3, _class$5;
  24985. var // jsdoc-ignore-end
  24986. TextMessage = (_dec$3 = messageType(-1), _dec$3(_class$5 = IE10Compatible(_class$5 = /*#__PURE__*/function (_TypedMessage) {
  24987. inheritsLoose(TextMessage, _TypedMessage);
  24988. /**
  24989. * 文类类型消息
  24990. * @extends TypedMessage
  24991. * @param {String} [text='']
  24992. * @throws {TypeError} text 不是 String 类型
  24993. */
  24994. function TextMessage() {
  24995. var _this;
  24996. var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  24997. if (typeof text !== 'string') {
  24998. throw new TypeError("".concat(text, " is not a string"));
  24999. }
  25000. _this = _TypedMessage.call(this) || this;
  25001. _this.setText(text);
  25002. return _this;
  25003. }
  25004. return TextMessage;
  25005. }(TypedMessage)) || _class$5) || _class$5);
  25006. /**
  25007. * @name TYPE
  25008. * @memberof TextMessage
  25009. * @type Number
  25010. * @static
  25011. * @const
  25012. */
  25013. var _class$6;
  25014. function ownKeys$a(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  25015. function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$a(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  25016. function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  25017. function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
  25018. function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  25019. var debug$c = browser('LC:MessageParser');
  25020. var tryParseJson = function tryParseJson(target, key, descriptor) {
  25021. var fn = descriptor.value; // eslint-disable-next-line no-param-reassign
  25022. descriptor.value = function wrapper(param) {
  25023. var content;
  25024. if (typeof param !== 'string') {
  25025. content = param;
  25026. } else {
  25027. try {
  25028. content = JSON.parse(param);
  25029. } catch (error) {
  25030. content = param;
  25031. }
  25032. }
  25033. return fn.call(this, content);
  25034. };
  25035. };
  25036. var applyPlugins = function applyPlugins(target, key, descriptor) {
  25037. var fn = descriptor.value; // eslint-disable-next-line no-param-reassign
  25038. descriptor.value = function wrapper(json) {
  25039. var _this = this;
  25040. return Promise.resolve(json).then(applyMiddlewares(this._plugins.beforeMessageParse)).then(function (decoratedJson) {
  25041. return fn.call(_this, decoratedJson);
  25042. }).then(applyMiddlewares(this._plugins.afterMessageParse));
  25043. };
  25044. };
  25045. var MessageParser = (_class$6 = /*#__PURE__*/function () {
  25046. /**
  25047. * 消息解析器
  25048. * @param {Object} plugins 插件,插件的 messageClasses 会自动被注册,在解析时 beforeMessageParse 与 afterMessageParse Middleware 会被应用。
  25049. */
  25050. function MessageParser() {
  25051. var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  25052. this._plugins = plugins;
  25053. this._messageClasses = [];
  25054. this.register(plugins.messageClasses);
  25055. }
  25056. /**
  25057. * 注册消息类
  25058. *
  25059. * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
  25060. * 建议继承自 {@link TypedMessage},也可以传入一个消息类数组。
  25061. * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
  25062. */
  25063. var _proto = MessageParser.prototype;
  25064. _proto.register = function register(messageClasses) {
  25065. var _this2 = this;
  25066. ensureArray(messageClasses).map(function (klass) {
  25067. return _this2._register(klass);
  25068. });
  25069. };
  25070. _proto._register = function _register(messageClass) {
  25071. if (messageClass && messageClass.parse && messageClass.prototype && messageClass.prototype.getPayload) {
  25072. this._messageClasses.unshift(messageClass);
  25073. } else {
  25074. throw new TypeError('Invalid messageClass');
  25075. }
  25076. } // jsdoc-ignore-start
  25077. ;
  25078. _proto. // jsdoc-ignore-end
  25079. /**
  25080. * 解析消息内容
  25081. * @param {Object | string | any} target 消息内容,如果是字符串会尝试 parse 为 JSON。
  25082. * @return {AVMessage} 解析后的消息
  25083. * @throws {Error} 如果不匹配任何注册的消息则抛出异常
  25084. */
  25085. parse = function parse(content) {
  25086. debug$c('parsing message: %O', content); // eslint-disable-next-line
  25087. var _iterator = _createForOfIteratorHelper(this._messageClasses),
  25088. _step;
  25089. try {
  25090. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  25091. var Klass = _step.value;
  25092. var contentCopy = isPlainObject_1(content) ? _objectSpread$a({}, content) : content;
  25093. var valid = void 0;
  25094. var result = void 0;
  25095. try {
  25096. valid = Klass.validate(contentCopy);
  25097. } catch (error) {// eslint-disable-line no-empty
  25098. }
  25099. if (valid) {
  25100. try {
  25101. result = Klass.parse(contentCopy);
  25102. } catch (error) {
  25103. console.warn('parsing a valid message content error', {
  25104. error: error,
  25105. Klass: Klass,
  25106. content: contentCopy
  25107. });
  25108. }
  25109. if (result !== undefined) {
  25110. debug$c('parse result: %O', result);
  25111. return result;
  25112. }
  25113. }
  25114. }
  25115. } catch (err) {
  25116. _iterator.e(err);
  25117. } finally {
  25118. _iterator.f();
  25119. }
  25120. throw new Error('No Message Class matched');
  25121. };
  25122. return MessageParser;
  25123. }(), (applyDecoratedDescriptor(_class$6.prototype, "parse", [tryParseJson, applyPlugins], Object.getOwnPropertyDescriptor(_class$6.prototype, "parse"), _class$6.prototype)), _class$6);
  25124. function ownKeys$b(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  25125. function _objectSpread$b(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$b(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$b(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  25126. var debug$d = browser('LC:IMPlugin');
  25127. /**
  25128. * 消息优先级枚举
  25129. * @enum {Number}
  25130. * @since 3.3.0
  25131. */
  25132. var MessagePriority = {
  25133. /** 高 */
  25134. HIGH: 1,
  25135. /** 普通 */
  25136. NORMAL: 2,
  25137. /** 低 */
  25138. LOW: 3
  25139. };
  25140. Object.freeze(MessagePriority);
  25141. /**
  25142. * 为 Conversation 定义一个新属性
  25143. * @param {String} prop 属性名
  25144. * @param {Object} [descriptor] 属性的描述符,参见 {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description getOwnPropertyDescriptor#Description - MDN},默认为该属性名对应的 Conversation 自定义属性的 getter/setter
  25145. * @returns void
  25146. * @example
  25147. *
  25148. * conversation.get('type');
  25149. * conversation.set('type', 1);
  25150. *
  25151. * // equals to
  25152. * defineConversationProperty('type');
  25153. * conversation.type;
  25154. * conversation.type = 1;
  25155. */
  25156. var defineConversationProperty = function defineConversationProperty(prop) {
  25157. var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
  25158. get: function get() {
  25159. return this.get(prop);
  25160. },
  25161. set: function set(value) {
  25162. this.set(prop, value);
  25163. }
  25164. };
  25165. Object.defineProperty(Conversation.prototype, prop, descriptor);
  25166. };
  25167. var onRealtimeCreate = function onRealtimeCreate(realtime) {
  25168. /* eslint-disable no-param-reassign */
  25169. var deviceId = v4_1();
  25170. realtime._IMClients = {};
  25171. realtime._IMClientsCreationCount = 0;
  25172. var messageParser = new MessageParser(realtime._plugins);
  25173. realtime._messageParser = messageParser;
  25174. var signAVUser = /*#__PURE__*/function () {
  25175. var _ref = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(user) {
  25176. return regenerator.wrap(function _callee$(_context) {
  25177. while (1) {
  25178. switch (_context.prev = _context.next) {
  25179. case 0:
  25180. return _context.abrupt("return", realtime._request({
  25181. method: 'POST',
  25182. path: '/rtm/sign',
  25183. data: {
  25184. session_token: user.getSessionToken()
  25185. }
  25186. }));
  25187. case 1:
  25188. case "end":
  25189. return _context.stop();
  25190. }
  25191. }
  25192. }, _callee);
  25193. }));
  25194. return function signAVUser(_x) {
  25195. return _ref.apply(this, arguments);
  25196. };
  25197. }();
  25198. /**
  25199. * 注册消息类
  25200. *
  25201. * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容
  25202. *
  25203. * @memberof Realtime
  25204. * @instance
  25205. * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
  25206. * 建议继承自 {@link TypedMessage}
  25207. * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
  25208. */
  25209. var register = messageParser.register.bind(messageParser);
  25210. /**
  25211. * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例
  25212. * @memberof Realtime
  25213. * @instance
  25214. * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity,
  25215. * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。
  25216. * @param {Object} [options]
  25217. * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details
  25218. * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法
  25219. * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法
  25220. * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能
  25221. * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录
  25222. * @return {Promise.<IMClient>}
  25223. */
  25224. var createIMClient = /*#__PURE__*/function () {
  25225. var _ref2 = asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(identity) {
  25226. var _realtime$_open$then;
  25227. var _ref3,
  25228. tag,
  25229. isReconnect,
  25230. clientOptions,
  25231. lagecyTag,
  25232. id,
  25233. buildinOptions,
  25234. sessionToken,
  25235. _tag,
  25236. promise,
  25237. _args2 = arguments;
  25238. return regenerator.wrap(function _callee2$(_context2) {
  25239. while (1) {
  25240. switch (_context2.prev = _context2.next) {
  25241. case 0:
  25242. _ref3 = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}, tag = _ref3.tag, isReconnect = _ref3.isReconnect, clientOptions = objectWithoutProperties(_ref3, ["tag", "isReconnect"]);
  25243. lagecyTag = _args2.length > 2 ? _args2[2] : undefined;
  25244. buildinOptions = {};
  25245. if (!identity) {
  25246. _context2.next = 19;
  25247. break;
  25248. }
  25249. if (!(typeof identity === 'string')) {
  25250. _context2.next = 8;
  25251. break;
  25252. }
  25253. id = identity;
  25254. _context2.next = 17;
  25255. break;
  25256. case 8:
  25257. if (!(identity.id && identity.getSessionToken)) {
  25258. _context2.next = 16;
  25259. break;
  25260. }
  25261. id = identity.id;
  25262. sessionToken = identity.getSessionToken();
  25263. if (sessionToken) {
  25264. _context2.next = 13;
  25265. break;
  25266. }
  25267. throw new Error('User must be authenticated');
  25268. case 13:
  25269. buildinOptions.signatureFactory = signAVUser;
  25270. _context2.next = 17;
  25271. break;
  25272. case 16:
  25273. throw new TypeError('Identity must be a String or an AV.User');
  25274. case 17:
  25275. if (!(realtime._IMClients[id] !== undefined)) {
  25276. _context2.next = 19;
  25277. break;
  25278. }
  25279. return _context2.abrupt("return", realtime._IMClients[id]);
  25280. case 19:
  25281. if (lagecyTag) {
  25282. console.warn('DEPRECATION createIMClient tag param: Use options.tag instead.');
  25283. }
  25284. _tag = tag || lagecyTag;
  25285. promise = (_realtime$_open$then = realtime._open().then(function (connection) {
  25286. var client = new IMClient(id, _objectSpread$b(_objectSpread$b({}, buildinOptions), clientOptions), {
  25287. _connection: connection,
  25288. _request: realtime._request.bind(realtime),
  25289. _messageParser: messageParser,
  25290. _plugins: realtime._plugins,
  25291. _identity: identity
  25292. });
  25293. connection.on(RECONNECT, function () {
  25294. return client._open(realtime._options.appId, _tag, deviceId, true)
  25295. /**
  25296. * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生
  25297. * @event IMClient#RECONNECT
  25298. * @see Realtime#event:RECONNECT
  25299. * @since 3.2.0
  25300. */
  25301. /**
  25302. * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误)
  25303. * @event IMClient#RECONNECT_ERROR
  25304. * @since 3.2.0
  25305. */
  25306. .then(function () {
  25307. return client.emit(RECONNECT);
  25308. }, function (error) {
  25309. return client.emit(RECONNECT_ERROR, error);
  25310. });
  25311. });
  25312. internal(client)._eventemitter.on('beforeclose', function () {
  25313. delete realtime._IMClients[client.id];
  25314. if (realtime._firstIMClient === client) {
  25315. delete realtime._firstIMClient;
  25316. }
  25317. }, realtime);
  25318. internal(client)._eventemitter.on('close', function () {
  25319. realtime._deregister(client);
  25320. }, realtime);
  25321. return client._open(realtime._options.appId, _tag, deviceId, isReconnect).then(function () {
  25322. realtime._IMClients[client.id] = client;
  25323. realtime._IMClientsCreationCount += 1;
  25324. if (realtime._IMClientsCreationCount === 1) {
  25325. client._omitPeerId(true);
  25326. realtime._firstIMClient = client;
  25327. } else if (realtime._IMClientsCreationCount > 1 && realtime._firstIMClient) {
  25328. realtime._firstIMClient._omitPeerId(false);
  25329. }
  25330. realtime._register(client);
  25331. return client;
  25332. })["catch"](function (error) {
  25333. delete realtime._IMClients[client.id];
  25334. throw error;
  25335. });
  25336. })).then.apply(_realtime$_open$then, toConsumableArray(finalize(function () {
  25337. realtime._deregisterPending(promise);
  25338. })))["catch"](function (error) {
  25339. delete realtime._IMClients[id];
  25340. throw error;
  25341. });
  25342. if (identity) {
  25343. realtime._IMClients[id] = promise;
  25344. }
  25345. realtime._registerPending(promise);
  25346. return _context2.abrupt("return", promise);
  25347. case 25:
  25348. case "end":
  25349. return _context2.stop();
  25350. }
  25351. }
  25352. }, _callee2);
  25353. }));
  25354. return function createIMClient(_x2) {
  25355. return _ref2.apply(this, arguments);
  25356. };
  25357. }();
  25358. Object.assign(realtime, {
  25359. register: register,
  25360. createIMClient: createIMClient
  25361. });
  25362. /* eslint-enable no-param-reassign */
  25363. };
  25364. var beforeCommandDispatch = function beforeCommandDispatch(command, realtime) {
  25365. var isIMCommand = command.service === null || command.service === 2;
  25366. if (!isIMCommand) return true;
  25367. var targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient;
  25368. if (targetClient) {
  25369. Promise.resolve(targetClient).then(function (client) {
  25370. return client._dispatchCommand(command);
  25371. })["catch"](debug$d);
  25372. } else {
  25373. debug$d('[WARN] Unexpected message received without any live client match: %O', trim(command));
  25374. }
  25375. return false;
  25376. };
  25377. var IMPlugin = {
  25378. name: 'leancloud-realtime-plugin-im',
  25379. onRealtimeCreate: onRealtimeCreate,
  25380. beforeCommandDispatch: beforeCommandDispatch,
  25381. messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage]
  25382. };
  25383. function ownKeys$c(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  25384. function _objectSpread$c(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$c(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$c(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  25385. Realtime.defineConversationProperty = defineConversationProperty;
  25386. Realtime.__preRegisteredPlugins = [IMPlugin];
  25387. var Event = _objectSpread$c(_objectSpread$c({}, CoreEvent), IMEvent);
  25388. /** core + plugins + platform adapters */
  25389. setAdapters({
  25390. WebSocket: lib_4,
  25391. request: lib_1$1
  25392. });
  25393. exports.BinaryMessage = BinaryMessage;
  25394. exports.ChatRoom = ChatRoom;
  25395. exports.Conversation = Conversation;
  25396. exports.ConversationMemberRole = ConversationMemberRole;
  25397. exports.ConversationQuery = ConversationQuery;
  25398. exports.ErrorCode = ErrorCode;
  25399. exports.Event = Event;
  25400. exports.EventEmitter = eventemitter3;
  25401. exports.IE10Compatible = IE10Compatible;
  25402. exports.IMPlugin = IMPlugin;
  25403. exports.Message = Message;
  25404. exports.MessageParser = MessageParser;
  25405. exports.MessagePriority = MessagePriority;
  25406. exports.MessageQueryDirection = MessageQueryDirection;
  25407. exports.MessageStatus = MessageStatus;
  25408. exports.Promise = polyfilledPromise;
  25409. exports.Protocals = message;
  25410. exports.Protocols = message;
  25411. exports.Realtime = Realtime;
  25412. exports.RecalledMessage = RecalledMessage;
  25413. exports.ServiceConversation = ServiceConversation;
  25414. exports.TemporaryConversation = TemporaryConversation;
  25415. exports.TextMessage = TextMessage;
  25416. exports.TypedMessage = TypedMessage;
  25417. exports.debug = debug$2;
  25418. exports.defineConversationProperty = defineConversationProperty;
  25419. exports.getAdapter = getAdapter;
  25420. exports.messageField = messageField;
  25421. exports.messageType = messageType;
  25422. exports.setAdapters = setAdapters;
  25423. Object.defineProperty(exports, '__esModule', { value: true });
  25424. })));
  25425. //# sourceMappingURL=im-browser.js.map