No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.standalone.js 703KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var require$$2 = require('util');
  4. var require$$0 = require('buffer');
  5. var require$$1 = require('events');
  6. var require$$0$1 = require('stream');
  7. var require$$1$1 = require('crypto');
  8. var require$$2$1 = require('url');
  9. var require$$0$2 = require('assert');
  10. var require$$1$2 = require('net');
  11. var require$$2$2 = require('tls');
  12. var require$$1$3 = require('@firebase/util');
  13. var require$$2$3 = require('tslib');
  14. var require$$3 = require('@firebase/logger');
  15. var component = require('@firebase/component');
  16. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  17. var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
  18. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  19. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
  20. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  21. var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
  22. var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
  23. var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
  24. var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
  25. var require$$2__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$2$2);
  26. var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
  27. var require$$2__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$2$3);
  28. var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
  29. var index_standalone = {};
  30. var safeBuffer = {exports: {}};
  31. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  32. (function (module, exports) {
  33. /* eslint-disable node/no-deprecated-api */
  34. var buffer = require$$0__default["default"];
  35. var Buffer = buffer.Buffer;
  36. // alternative to using Object.keys for old browsers
  37. function copyProps (src, dst) {
  38. for (var key in src) {
  39. dst[key] = src[key];
  40. }
  41. }
  42. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  43. module.exports = buffer;
  44. } else {
  45. // Copy properties from require('buffer')
  46. copyProps(buffer, exports);
  47. exports.Buffer = SafeBuffer;
  48. }
  49. function SafeBuffer (arg, encodingOrOffset, length) {
  50. return Buffer(arg, encodingOrOffset, length)
  51. }
  52. SafeBuffer.prototype = Object.create(Buffer.prototype);
  53. // Copy static methods from Buffer
  54. copyProps(Buffer, SafeBuffer);
  55. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  56. if (typeof arg === 'number') {
  57. throw new TypeError('Argument must not be a number')
  58. }
  59. return Buffer(arg, encodingOrOffset, length)
  60. };
  61. SafeBuffer.alloc = function (size, fill, encoding) {
  62. if (typeof size !== 'number') {
  63. throw new TypeError('Argument must be a number')
  64. }
  65. var buf = Buffer(size);
  66. if (fill !== undefined) {
  67. if (typeof encoding === 'string') {
  68. buf.fill(fill, encoding);
  69. } else {
  70. buf.fill(fill);
  71. }
  72. } else {
  73. buf.fill(0);
  74. }
  75. return buf
  76. };
  77. SafeBuffer.allocUnsafe = function (size) {
  78. if (typeof size !== 'number') {
  79. throw new TypeError('Argument must be a number')
  80. }
  81. return Buffer(size)
  82. };
  83. SafeBuffer.allocUnsafeSlow = function (size) {
  84. if (typeof size !== 'number') {
  85. throw new TypeError('Argument must be a number')
  86. }
  87. return buffer.SlowBuffer(size)
  88. };
  89. }(safeBuffer, safeBuffer.exports));
  90. var streams$1 = {};
  91. /**
  92. Streams in a WebSocket connection
  93. ---------------------------------
  94. We model a WebSocket as two duplex streams: one stream is for the wire protocol
  95. over an I/O socket, and the other is for incoming/outgoing messages.
  96. +----------+ +---------+ +----------+
  97. [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2]
  98. | | +----+----+ | |
  99. | | | | |
  100. | IO | | [5] | Messages |
  101. | | V | |
  102. | | +---------+ | |
  103. [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3]
  104. +----------+ +---------+ +----------+
  105. Message transfer in each direction is simple: IO receives a byte stream [1] and
  106. sends this stream for parsing. The parser will periodically emit a complete
  107. message text on the Messages stream [2]. Similarly, when messages are written
  108. to the Messages stream [3], they are framed using the WebSocket wire format and
  109. emitted via IO [4].
  110. There is a feedback loop via [5] since some input from [1] will be things like
  111. ping, pong and close frames. In these cases the protocol responds by emitting
  112. responses directly back to [4] rather than emitting messages via [2].
  113. For the purposes of flow control, we consider the sources of each Readable
  114. stream to be as follows:
  115. * [2] receives input from [1]
  116. * [4] receives input from [1] and [3]
  117. The classes below express the relationships described above without prescribing
  118. anything about how parse() and frame() work, other than assuming they emit
  119. 'data' events to the IO and Messages streams. They will work with any protocol
  120. driver having these two methods.
  121. **/
  122. var Stream$3 = require$$0__default$1["default"].Stream,
  123. util$c = require$$2__default["default"];
  124. var IO = function(driver) {
  125. this.readable = this.writable = true;
  126. this._paused = false;
  127. this._driver = driver;
  128. };
  129. util$c.inherits(IO, Stream$3);
  130. // The IO pause() and resume() methods will be called when the socket we are
  131. // piping to gets backed up and drains. Since IO output [4] comes from IO input
  132. // [1] and Messages input [3], we need to tell both of those to return false
  133. // from write() when this stream is paused.
  134. IO.prototype.pause = function() {
  135. this._paused = true;
  136. this._driver.messages._paused = true;
  137. };
  138. IO.prototype.resume = function() {
  139. this._paused = false;
  140. this.emit('drain');
  141. var messages = this._driver.messages;
  142. messages._paused = false;
  143. messages.emit('drain');
  144. };
  145. // When we receive input from a socket, send it to the parser and tell the
  146. // source whether to back off.
  147. IO.prototype.write = function(chunk) {
  148. if (!this.writable) return false;
  149. this._driver.parse(chunk);
  150. return !this._paused;
  151. };
  152. // The IO end() method will be called when the socket piping into it emits
  153. // 'close' or 'end', i.e. the socket is closed. In this situation the Messages
  154. // stream will not emit any more data so we emit 'end'.
  155. IO.prototype.end = function(chunk) {
  156. if (!this.writable) return;
  157. if (chunk !== undefined) this.write(chunk);
  158. this.writable = false;
  159. var messages = this._driver.messages;
  160. if (messages.readable) {
  161. messages.readable = messages.writable = false;
  162. messages.emit('end');
  163. }
  164. };
  165. IO.prototype.destroy = function() {
  166. this.end();
  167. };
  168. var Messages = function(driver) {
  169. this.readable = this.writable = true;
  170. this._paused = false;
  171. this._driver = driver;
  172. };
  173. util$c.inherits(Messages, Stream$3);
  174. // The Messages pause() and resume() methods will be called when the app that's
  175. // processing the messages gets backed up and drains. If we're emitting
  176. // messages too fast we should tell the source to slow down. Message output [2]
  177. // comes from IO input [1].
  178. Messages.prototype.pause = function() {
  179. this._driver.io._paused = true;
  180. };
  181. Messages.prototype.resume = function() {
  182. this._driver.io._paused = false;
  183. this._driver.io.emit('drain');
  184. };
  185. // When we receive messages from the user, send them to the formatter and tell
  186. // the source whether to back off.
  187. Messages.prototype.write = function(message) {
  188. if (!this.writable) return false;
  189. if (typeof message === 'string') this._driver.text(message);
  190. else this._driver.binary(message);
  191. return !this._paused;
  192. };
  193. // The Messages end() method will be called when a stream piping into it emits
  194. // 'end'. Many streams may be piped into the WebSocket and one of them ending
  195. // does not mean the whole socket is done, so just process the input and move
  196. // on leaving the socket open.
  197. Messages.prototype.end = function(message) {
  198. if (message !== undefined) this.write(message);
  199. };
  200. Messages.prototype.destroy = function() {};
  201. streams$1.IO = IO;
  202. streams$1.Messages = Messages;
  203. var Headers$3 = function() {
  204. this.clear();
  205. };
  206. Headers$3.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate'];
  207. Headers$3.prototype.clear = function() {
  208. this._sent = {};
  209. this._lines = [];
  210. };
  211. Headers$3.prototype.set = function(name, value) {
  212. if (value === undefined) return;
  213. name = this._strip(name);
  214. value = this._strip(value);
  215. var key = name.toLowerCase();
  216. if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) {
  217. this._sent[key] = true;
  218. this._lines.push(name + ': ' + value + '\r\n');
  219. }
  220. };
  221. Headers$3.prototype.toString = function() {
  222. return this._lines.join('');
  223. };
  224. Headers$3.prototype._strip = function(string) {
  225. return string.toString().replace(/^ */, '').replace(/ *$/, '');
  226. };
  227. var headers = Headers$3;
  228. var Buffer$9 = safeBuffer.exports.Buffer;
  229. var StreamReader = function() {
  230. this._queue = [];
  231. this._queueSize = 0;
  232. this._offset = 0;
  233. };
  234. StreamReader.prototype.put = function(buffer) {
  235. if (!buffer || buffer.length === 0) return;
  236. if (!Buffer$9.isBuffer(buffer)) buffer = Buffer$9.from(buffer);
  237. this._queue.push(buffer);
  238. this._queueSize += buffer.length;
  239. };
  240. StreamReader.prototype.read = function(length) {
  241. if (length > this._queueSize) return null;
  242. if (length === 0) return Buffer$9.alloc(0);
  243. this._queueSize -= length;
  244. var queue = this._queue,
  245. remain = length,
  246. first = queue[0],
  247. buffers, buffer;
  248. if (first.length >= length) {
  249. if (first.length === length) {
  250. return queue.shift();
  251. } else {
  252. buffer = first.slice(0, length);
  253. queue[0] = first.slice(length);
  254. return buffer;
  255. }
  256. }
  257. for (var i = 0, n = queue.length; i < n; i++) {
  258. if (remain < queue[i].length) break;
  259. remain -= queue[i].length;
  260. }
  261. buffers = queue.splice(0, i);
  262. if (remain > 0 && queue.length > 0) {
  263. buffers.push(queue[0].slice(0, remain));
  264. queue[0] = queue[0].slice(remain);
  265. }
  266. return Buffer$9.concat(buffers, length);
  267. };
  268. StreamReader.prototype.eachByte = function(callback, context) {
  269. var buffer, n, index;
  270. while (this._queue.length > 0) {
  271. buffer = this._queue[0];
  272. n = buffer.length;
  273. while (this._offset < n) {
  274. index = this._offset;
  275. this._offset += 1;
  276. callback.call(context, buffer[index]);
  277. }
  278. this._offset = 0;
  279. this._queue.shift();
  280. }
  281. };
  282. var stream_reader = StreamReader;
  283. var Buffer$8 = safeBuffer.exports.Buffer,
  284. Emitter = require$$1__default["default"].EventEmitter,
  285. util$b = require$$2__default["default"],
  286. streams = streams$1,
  287. Headers$2 = headers,
  288. Reader = stream_reader;
  289. var Base$7 = function(request, url, options) {
  290. Emitter.call(this);
  291. Base$7.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']);
  292. this._request = request;
  293. this._reader = new Reader();
  294. this._options = options || {};
  295. this._maxLength = this._options.maxLength || this.MAX_LENGTH;
  296. this._headers = new Headers$2();
  297. this.__queue = [];
  298. this.readyState = 0;
  299. this.url = url;
  300. this.io = new streams.IO(this);
  301. this.messages = new streams.Messages(this);
  302. this._bindEventListeners();
  303. };
  304. util$b.inherits(Base$7, Emitter);
  305. Base$7.isWebSocket = function(request) {
  306. var connection = request.headers.connection || '',
  307. upgrade = request.headers.upgrade || '';
  308. return request.method === 'GET' &&
  309. connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 &&
  310. upgrade.toLowerCase() === 'websocket';
  311. };
  312. Base$7.validateOptions = function(options, validKeys) {
  313. for (var key in options) {
  314. if (validKeys.indexOf(key) < 0)
  315. throw new Error('Unrecognized option: ' + key);
  316. }
  317. };
  318. var instance$b = {
  319. // This is 64MB, small enough for an average VPS to handle without
  320. // crashing from process out of memory
  321. MAX_LENGTH: 0x3ffffff,
  322. STATES: ['connecting', 'open', 'closing', 'closed'],
  323. _bindEventListeners: function() {
  324. var self = this;
  325. // Protocol errors are informational and do not have to be handled
  326. this.messages.on('error', function() {});
  327. this.on('message', function(event) {
  328. var messages = self.messages;
  329. if (messages.readable) messages.emit('data', event.data);
  330. });
  331. this.on('error', function(error) {
  332. var messages = self.messages;
  333. if (messages.readable) messages.emit('error', error);
  334. });
  335. this.on('close', function() {
  336. var messages = self.messages;
  337. if (!messages.readable) return;
  338. messages.readable = messages.writable = false;
  339. messages.emit('end');
  340. });
  341. },
  342. getState: function() {
  343. return this.STATES[this.readyState] || null;
  344. },
  345. addExtension: function(extension) {
  346. return false;
  347. },
  348. setHeader: function(name, value) {
  349. if (this.readyState > 0) return false;
  350. this._headers.set(name, value);
  351. return true;
  352. },
  353. start: function() {
  354. if (this.readyState !== 0) return false;
  355. if (!Base$7.isWebSocket(this._request))
  356. return this._failHandshake(new Error('Not a WebSocket request'));
  357. var response;
  358. try {
  359. response = this._handshakeResponse();
  360. } catch (error) {
  361. return this._failHandshake(error);
  362. }
  363. this._write(response);
  364. if (this._stage !== -1) this._open();
  365. return true;
  366. },
  367. _failHandshake: function(error) {
  368. var headers = new Headers$2();
  369. headers.set('Content-Type', 'text/plain');
  370. headers.set('Content-Length', Buffer$8.byteLength(error.message, 'utf8'));
  371. headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message];
  372. this._write(Buffer$8.from(headers.join('\r\n'), 'utf8'));
  373. this._fail('protocol_error', error.message);
  374. return false;
  375. },
  376. text: function(message) {
  377. return this.frame(message);
  378. },
  379. binary: function(message) {
  380. return false;
  381. },
  382. ping: function() {
  383. return false;
  384. },
  385. pong: function() {
  386. return false;
  387. },
  388. close: function(reason, code) {
  389. if (this.readyState !== 1) return false;
  390. this.readyState = 3;
  391. this.emit('close', new Base$7.CloseEvent(null, null));
  392. return true;
  393. },
  394. _open: function() {
  395. this.readyState = 1;
  396. this.__queue.forEach(function(args) { this.frame.apply(this, args); }, this);
  397. this.__queue = [];
  398. this.emit('open', new Base$7.OpenEvent());
  399. },
  400. _queue: function(message) {
  401. this.__queue.push(message);
  402. return true;
  403. },
  404. _write: function(chunk) {
  405. var io = this.io;
  406. if (io.readable) io.emit('data', chunk);
  407. },
  408. _fail: function(type, message) {
  409. this.readyState = 2;
  410. this.emit('error', new Error(message));
  411. this.close();
  412. }
  413. };
  414. for (var key$b in instance$b)
  415. Base$7.prototype[key$b] = instance$b[key$b];
  416. Base$7.ConnectEvent = function() {};
  417. Base$7.OpenEvent = function() {};
  418. Base$7.CloseEvent = function(code, reason) {
  419. this.code = code;
  420. this.reason = reason;
  421. };
  422. Base$7.MessageEvent = function(data) {
  423. this.data = data;
  424. };
  425. Base$7.PingEvent = function(data) {
  426. this.data = data;
  427. };
  428. Base$7.PongEvent = function(data) {
  429. this.data = data;
  430. };
  431. var base = Base$7;
  432. var httpParser = {};
  433. /*jshint node:true */
  434. var assert = require$$0__default$2["default"];
  435. httpParser.HTTPParser = HTTPParser;
  436. function HTTPParser(type) {
  437. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE || type === undefined);
  438. if (type === undefined) ; else {
  439. this.initialize(type);
  440. }
  441. }
  442. HTTPParser.prototype.initialize = function (type, async_resource) {
  443. assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE);
  444. this.type = type;
  445. this.state = type + '_LINE';
  446. this.info = {
  447. headers: [],
  448. upgrade: false
  449. };
  450. this.trailers = [];
  451. this.line = '';
  452. this.isChunked = false;
  453. this.connection = '';
  454. this.headerSize = 0; // for preventing too big headers
  455. this.body_bytes = null;
  456. this.isUserCall = false;
  457. this.hadError = false;
  458. };
  459. HTTPParser.encoding = 'ascii';
  460. HTTPParser.maxHeaderSize = 80 * 1024; // maxHeaderSize (in bytes) is configurable, but 80kb by default;
  461. HTTPParser.REQUEST = 'REQUEST';
  462. HTTPParser.RESPONSE = 'RESPONSE';
  463. // Note: *not* starting with kOnHeaders=0 line the Node parser, because any
  464. // newly added constants (kOnTimeout in Node v12.19.0) will overwrite 0!
  465. var kOnHeaders = HTTPParser.kOnHeaders = 1;
  466. var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2;
  467. var kOnBody = HTTPParser.kOnBody = 3;
  468. var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4;
  469. // Some handler stubs, needed for compatibility
  470. HTTPParser.prototype[kOnHeaders] =
  471. HTTPParser.prototype[kOnHeadersComplete] =
  472. HTTPParser.prototype[kOnBody] =
  473. HTTPParser.prototype[kOnMessageComplete] = function () {};
  474. var compatMode0_12 = true;
  475. Object.defineProperty(HTTPParser, 'kOnExecute', {
  476. get: function () {
  477. // hack for backward compatibility
  478. compatMode0_12 = false;
  479. return 99;
  480. }
  481. });
  482. var methods = httpParser.methods = HTTPParser.methods = [
  483. 'DELETE',
  484. 'GET',
  485. 'HEAD',
  486. 'POST',
  487. 'PUT',
  488. 'CONNECT',
  489. 'OPTIONS',
  490. 'TRACE',
  491. 'COPY',
  492. 'LOCK',
  493. 'MKCOL',
  494. 'MOVE',
  495. 'PROPFIND',
  496. 'PROPPATCH',
  497. 'SEARCH',
  498. 'UNLOCK',
  499. 'BIND',
  500. 'REBIND',
  501. 'UNBIND',
  502. 'ACL',
  503. 'REPORT',
  504. 'MKACTIVITY',
  505. 'CHECKOUT',
  506. 'MERGE',
  507. 'M-SEARCH',
  508. 'NOTIFY',
  509. 'SUBSCRIBE',
  510. 'UNSUBSCRIBE',
  511. 'PATCH',
  512. 'PURGE',
  513. 'MKCALENDAR',
  514. 'LINK',
  515. 'UNLINK'
  516. ];
  517. var method_connect = methods.indexOf('CONNECT');
  518. HTTPParser.prototype.reinitialize = HTTPParser;
  519. HTTPParser.prototype.close =
  520. HTTPParser.prototype.pause =
  521. HTTPParser.prototype.resume =
  522. HTTPParser.prototype.free = function () {};
  523. HTTPParser.prototype._compatMode0_11 = false;
  524. HTTPParser.prototype.getAsyncId = function() { return 0; };
  525. var headerState = {
  526. REQUEST_LINE: true,
  527. RESPONSE_LINE: true,
  528. HEADER: true
  529. };
  530. HTTPParser.prototype.execute = function (chunk, start, length) {
  531. if (!(this instanceof HTTPParser)) {
  532. throw new TypeError('not a HTTPParser');
  533. }
  534. // backward compat to node < 0.11.4
  535. // Note: the start and length params were removed in newer version
  536. start = start || 0;
  537. length = typeof length === 'number' ? length : chunk.length;
  538. this.chunk = chunk;
  539. this.offset = start;
  540. var end = this.end = start + length;
  541. try {
  542. while (this.offset < end) {
  543. if (this[this.state]()) {
  544. break;
  545. }
  546. }
  547. } catch (err) {
  548. if (this.isUserCall) {
  549. throw err;
  550. }
  551. this.hadError = true;
  552. return err;
  553. }
  554. this.chunk = null;
  555. length = this.offset - start;
  556. if (headerState[this.state]) {
  557. this.headerSize += length;
  558. if (this.headerSize > HTTPParser.maxHeaderSize) {
  559. return new Error('max header size exceeded');
  560. }
  561. }
  562. return length;
  563. };
  564. var stateFinishAllowed = {
  565. REQUEST_LINE: true,
  566. RESPONSE_LINE: true,
  567. BODY_RAW: true
  568. };
  569. HTTPParser.prototype.finish = function () {
  570. if (this.hadError) {
  571. return;
  572. }
  573. if (!stateFinishAllowed[this.state]) {
  574. return new Error('invalid state for EOF');
  575. }
  576. if (this.state === 'BODY_RAW') {
  577. this.userCall()(this[kOnMessageComplete]());
  578. }
  579. };
  580. // These three methods are used for an internal speed optimization, and it also
  581. // works if theses are noops. Basically consume() asks us to read the bytes
  582. // ourselves, but if we don't do it we get them through execute().
  583. HTTPParser.prototype.consume =
  584. HTTPParser.prototype.unconsume =
  585. HTTPParser.prototype.getCurrentBuffer = function () {};
  586. //For correct error handling - see HTTPParser#execute
  587. //Usage: this.userCall()(userFunction('arg'));
  588. HTTPParser.prototype.userCall = function () {
  589. this.isUserCall = true;
  590. var self = this;
  591. return function (ret) {
  592. self.isUserCall = false;
  593. return ret;
  594. };
  595. };
  596. HTTPParser.prototype.nextRequest = function () {
  597. this.userCall()(this[kOnMessageComplete]());
  598. this.reinitialize(this.type);
  599. };
  600. HTTPParser.prototype.consumeLine = function () {
  601. var end = this.end,
  602. chunk = this.chunk;
  603. for (var i = this.offset; i < end; i++) {
  604. if (chunk[i] === 0x0a) { // \n
  605. var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i);
  606. if (line.charAt(line.length - 1) === '\r') {
  607. line = line.substr(0, line.length - 1);
  608. }
  609. this.line = '';
  610. this.offset = i + 1;
  611. return line;
  612. }
  613. }
  614. //line split over multiple chunks
  615. this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end);
  616. this.offset = this.end;
  617. };
  618. var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/;
  619. var headerContinueExp = /^[ \t]+(.*[^ \t])/;
  620. HTTPParser.prototype.parseHeader = function (line, headers) {
  621. if (line.indexOf('\r') !== -1) {
  622. throw parseErrorCode('HPE_LF_EXPECTED');
  623. }
  624. var match = headerExp.exec(line);
  625. var k = match && match[1];
  626. if (k) { // skip empty string (malformed header)
  627. headers.push(k);
  628. headers.push(match[2]);
  629. } else {
  630. var matchContinue = headerContinueExp.exec(line);
  631. if (matchContinue && headers.length) {
  632. if (headers[headers.length - 1]) {
  633. headers[headers.length - 1] += ' ';
  634. }
  635. headers[headers.length - 1] += matchContinue[1];
  636. }
  637. }
  638. };
  639. var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;
  640. HTTPParser.prototype.REQUEST_LINE = function () {
  641. var line = this.consumeLine();
  642. if (!line) {
  643. return;
  644. }
  645. var match = requestExp.exec(line);
  646. if (match === null) {
  647. throw parseErrorCode('HPE_INVALID_CONSTANT');
  648. }
  649. this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]);
  650. if (this.info.method === -1) {
  651. throw new Error('invalid request method');
  652. }
  653. this.info.url = match[2];
  654. this.info.versionMajor = +match[3];
  655. this.info.versionMinor = +match[4];
  656. this.body_bytes = 0;
  657. this.state = 'HEADER';
  658. };
  659. var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;
  660. HTTPParser.prototype.RESPONSE_LINE = function () {
  661. var line = this.consumeLine();
  662. if (!line) {
  663. return;
  664. }
  665. var match = responseExp.exec(line);
  666. if (match === null) {
  667. throw parseErrorCode('HPE_INVALID_CONSTANT');
  668. }
  669. this.info.versionMajor = +match[1];
  670. this.info.versionMinor = +match[2];
  671. var statusCode = this.info.statusCode = +match[3];
  672. this.info.statusMessage = match[4];
  673. // Implied zero length.
  674. if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) {
  675. this.body_bytes = 0;
  676. }
  677. this.state = 'HEADER';
  678. };
  679. HTTPParser.prototype.shouldKeepAlive = function () {
  680. if (this.info.versionMajor > 0 && this.info.versionMinor > 0) {
  681. if (this.connection.indexOf('close') !== -1) {
  682. return false;
  683. }
  684. } else if (this.connection.indexOf('keep-alive') === -1) {
  685. return false;
  686. }
  687. if (this.body_bytes !== null || this.isChunked) { // || skipBody
  688. return true;
  689. }
  690. return false;
  691. };
  692. HTTPParser.prototype.HEADER = function () {
  693. var line = this.consumeLine();
  694. if (line === undefined) {
  695. return;
  696. }
  697. var info = this.info;
  698. if (line) {
  699. this.parseHeader(line, info.headers);
  700. } else {
  701. var headers = info.headers;
  702. var hasContentLength = false;
  703. var currentContentLengthValue;
  704. var hasUpgradeHeader = false;
  705. for (var i = 0; i < headers.length; i += 2) {
  706. switch (headers[i].toLowerCase()) {
  707. case 'transfer-encoding':
  708. this.isChunked = headers[i + 1].toLowerCase() === 'chunked';
  709. break;
  710. case 'content-length':
  711. currentContentLengthValue = +headers[i + 1];
  712. if (hasContentLength) {
  713. // Fix duplicate Content-Length header with same values.
  714. // Throw error only if values are different.
  715. // Known issues:
  716. // https://github.com/request/request/issues/2091#issuecomment-328715113
  717. // https://github.com/nodejs/node/issues/6517#issuecomment-216263771
  718. if (currentContentLengthValue !== this.body_bytes) {
  719. throw parseErrorCode('HPE_UNEXPECTED_CONTENT_LENGTH');
  720. }
  721. } else {
  722. hasContentLength = true;
  723. this.body_bytes = currentContentLengthValue;
  724. }
  725. break;
  726. case 'connection':
  727. this.connection += headers[i + 1].toLowerCase();
  728. break;
  729. case 'upgrade':
  730. hasUpgradeHeader = true;
  731. break;
  732. }
  733. }
  734. // if both isChunked and hasContentLength, isChunked wins
  735. // This is required so the body is parsed using the chunked method, and matches
  736. // Chrome's behavior. We could, maybe, ignore them both (would get chunked
  737. // encoding into the body), and/or disable shouldKeepAlive to be more
  738. // resilient.
  739. if (this.isChunked && hasContentLength) {
  740. hasContentLength = false;
  741. this.body_bytes = null;
  742. }
  743. // Logic from https://github.com/nodejs/http-parser/blob/921d5585515a153fa00e411cf144280c59b41f90/http_parser.c#L1727-L1737
  744. // "For responses, "Upgrade: foo" and "Connection: upgrade" are
  745. // mandatory only when it is a 101 Switching Protocols response,
  746. // otherwise it is purely informational, to announce support.
  747. if (hasUpgradeHeader && this.connection.indexOf('upgrade') != -1) {
  748. info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101;
  749. } else {
  750. info.upgrade = info.method === method_connect;
  751. }
  752. if (this.isChunked && info.upgrade) {
  753. this.isChunked = false;
  754. }
  755. info.shouldKeepAlive = this.shouldKeepAlive();
  756. //problem which also exists in original node: we should know skipBody before calling onHeadersComplete
  757. var skipBody;
  758. if (compatMode0_12) {
  759. skipBody = this.userCall()(this[kOnHeadersComplete](info));
  760. } else {
  761. skipBody = this.userCall()(this[kOnHeadersComplete](info.versionMajor,
  762. info.versionMinor, info.headers, info.method, info.url, info.statusCode,
  763. info.statusMessage, info.upgrade, info.shouldKeepAlive));
  764. }
  765. if (skipBody === 2) {
  766. this.nextRequest();
  767. return true;
  768. } else if (this.isChunked && !skipBody) {
  769. this.state = 'BODY_CHUNKHEAD';
  770. } else if (skipBody || this.body_bytes === 0) {
  771. this.nextRequest();
  772. // For older versions of node (v6.x and older?), that return skipBody=1 or skipBody=true,
  773. // need this "return true;" if it's an upgrade request.
  774. return info.upgrade;
  775. } else if (this.body_bytes === null) {
  776. this.state = 'BODY_RAW';
  777. } else {
  778. this.state = 'BODY_SIZED';
  779. }
  780. }
  781. };
  782. HTTPParser.prototype.BODY_CHUNKHEAD = function () {
  783. var line = this.consumeLine();
  784. if (line === undefined) {
  785. return;
  786. }
  787. this.body_bytes = parseInt(line, 16);
  788. if (!this.body_bytes) {
  789. this.state = 'BODY_CHUNKTRAILERS';
  790. } else {
  791. this.state = 'BODY_CHUNK';
  792. }
  793. };
  794. HTTPParser.prototype.BODY_CHUNK = function () {
  795. var length = Math.min(this.end - this.offset, this.body_bytes);
  796. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  797. this.offset += length;
  798. this.body_bytes -= length;
  799. if (!this.body_bytes) {
  800. this.state = 'BODY_CHUNKEMPTYLINE';
  801. }
  802. };
  803. HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function () {
  804. var line = this.consumeLine();
  805. if (line === undefined) {
  806. return;
  807. }
  808. assert.equal(line, '');
  809. this.state = 'BODY_CHUNKHEAD';
  810. };
  811. HTTPParser.prototype.BODY_CHUNKTRAILERS = function () {
  812. var line = this.consumeLine();
  813. if (line === undefined) {
  814. return;
  815. }
  816. if (line) {
  817. this.parseHeader(line, this.trailers);
  818. } else {
  819. if (this.trailers.length) {
  820. this.userCall()(this[kOnHeaders](this.trailers, ''));
  821. }
  822. this.nextRequest();
  823. }
  824. };
  825. HTTPParser.prototype.BODY_RAW = function () {
  826. var length = this.end - this.offset;
  827. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  828. this.offset = this.end;
  829. };
  830. HTTPParser.prototype.BODY_SIZED = function () {
  831. var length = Math.min(this.end - this.offset, this.body_bytes);
  832. this.userCall()(this[kOnBody](this.chunk, this.offset, length));
  833. this.offset += length;
  834. this.body_bytes -= length;
  835. if (!this.body_bytes) {
  836. this.nextRequest();
  837. }
  838. };
  839. // backward compat to node < 0.11.6
  840. ['Headers', 'HeadersComplete', 'Body', 'MessageComplete'].forEach(function (name) {
  841. var k = HTTPParser['kOn' + name];
  842. Object.defineProperty(HTTPParser.prototype, 'on' + name, {
  843. get: function () {
  844. return this[k];
  845. },
  846. set: function (to) {
  847. // hack for backward compatibility
  848. this._compatMode0_11 = true;
  849. method_connect = 'CONNECT';
  850. return (this[k] = to);
  851. }
  852. });
  853. });
  854. function parseErrorCode(code) {
  855. var err = new Error('Parse Error');
  856. err.code = code;
  857. return err;
  858. }
  859. var NodeHTTPParser = httpParser.HTTPParser,
  860. Buffer$7 = safeBuffer.exports.Buffer;
  861. var TYPES = {
  862. request: NodeHTTPParser.REQUEST || 'request',
  863. response: NodeHTTPParser.RESPONSE || 'response'
  864. };
  865. var HttpParser$3 = function(type) {
  866. this._type = type;
  867. this._parser = new NodeHTTPParser(TYPES[type]);
  868. this._complete = false;
  869. this.headers = {};
  870. var current = null,
  871. self = this;
  872. this._parser.onHeaderField = function(b, start, length) {
  873. current = b.toString('utf8', start, start + length).toLowerCase();
  874. };
  875. this._parser.onHeaderValue = function(b, start, length) {
  876. var value = b.toString('utf8', start, start + length);
  877. if (self.headers.hasOwnProperty(current))
  878. self.headers[current] += ', ' + value;
  879. else
  880. self.headers[current] = value;
  881. };
  882. this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] =
  883. function(majorVersion, minorVersion, headers, method, pathname, statusCode) {
  884. var info = arguments[0];
  885. if (typeof info === 'object') {
  886. method = info.method;
  887. pathname = info.url;
  888. statusCode = info.statusCode;
  889. headers = info.headers;
  890. }
  891. self.method = (typeof method === 'number') ? HttpParser$3.METHODS[method] : method;
  892. self.statusCode = statusCode;
  893. self.url = pathname;
  894. if (!headers) return;
  895. for (var i = 0, n = headers.length, key, value; i < n; i += 2) {
  896. key = headers[i].toLowerCase();
  897. value = headers[i+1];
  898. if (self.headers.hasOwnProperty(key))
  899. self.headers[key] += ', ' + value;
  900. else
  901. self.headers[key] = value;
  902. }
  903. self._complete = true;
  904. };
  905. };
  906. HttpParser$3.METHODS = {
  907. 0: 'DELETE',
  908. 1: 'GET',
  909. 2: 'HEAD',
  910. 3: 'POST',
  911. 4: 'PUT',
  912. 5: 'CONNECT',
  913. 6: 'OPTIONS',
  914. 7: 'TRACE',
  915. 8: 'COPY',
  916. 9: 'LOCK',
  917. 10: 'MKCOL',
  918. 11: 'MOVE',
  919. 12: 'PROPFIND',
  920. 13: 'PROPPATCH',
  921. 14: 'SEARCH',
  922. 15: 'UNLOCK',
  923. 16: 'BIND',
  924. 17: 'REBIND',
  925. 18: 'UNBIND',
  926. 19: 'ACL',
  927. 20: 'REPORT',
  928. 21: 'MKACTIVITY',
  929. 22: 'CHECKOUT',
  930. 23: 'MERGE',
  931. 24: 'M-SEARCH',
  932. 25: 'NOTIFY',
  933. 26: 'SUBSCRIBE',
  934. 27: 'UNSUBSCRIBE',
  935. 28: 'PATCH',
  936. 29: 'PURGE',
  937. 30: 'MKCALENDAR',
  938. 31: 'LINK',
  939. 32: 'UNLINK'
  940. };
  941. var VERSION = process.version
  942. ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) })
  943. : [];
  944. if (VERSION[0] === 0 && VERSION[1] === 12) {
  945. HttpParser$3.METHODS[16] = 'REPORT';
  946. HttpParser$3.METHODS[17] = 'MKACTIVITY';
  947. HttpParser$3.METHODS[18] = 'CHECKOUT';
  948. HttpParser$3.METHODS[19] = 'MERGE';
  949. HttpParser$3.METHODS[20] = 'M-SEARCH';
  950. HttpParser$3.METHODS[21] = 'NOTIFY';
  951. HttpParser$3.METHODS[22] = 'SUBSCRIBE';
  952. HttpParser$3.METHODS[23] = 'UNSUBSCRIBE';
  953. HttpParser$3.METHODS[24] = 'PATCH';
  954. HttpParser$3.METHODS[25] = 'PURGE';
  955. }
  956. HttpParser$3.prototype.isComplete = function() {
  957. return this._complete;
  958. };
  959. HttpParser$3.prototype.parse = function(chunk) {
  960. var consumed = this._parser.execute(chunk, 0, chunk.length);
  961. if (typeof consumed !== 'number') {
  962. this.error = consumed;
  963. this._complete = true;
  964. return;
  965. }
  966. if (this._complete)
  967. this.body = (consumed < chunk.length)
  968. ? chunk.slice(consumed)
  969. : Buffer$7.alloc(0);
  970. };
  971. var http_parser = HttpParser$3;
  972. var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/,
  973. NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g,
  974. QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/,
  975. PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'),
  976. EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'),
  977. EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'),
  978. NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/;
  979. var hasOwnProperty = Object.prototype.hasOwnProperty;
  980. var Parser$1 = {
  981. parseHeader: function(header) {
  982. var offers = new Offers();
  983. if (header === '' || header === undefined) return offers;
  984. if (!EXT_LIST.test(header))
  985. throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header);
  986. var values = header.match(EXT);
  987. values.forEach(function(value) {
  988. var params = value.match(new RegExp(PARAM.source, 'g')),
  989. name = params.shift(),
  990. offer = {};
  991. params.forEach(function(param) {
  992. var args = param.match(PARAM), key = args[1], data;
  993. if (args[2] !== undefined) {
  994. data = args[2];
  995. } else if (args[3] !== undefined) {
  996. data = args[3].replace(/\\/g, '');
  997. } else {
  998. data = true;
  999. }
  1000. if (NUMBER.test(data)) data = parseFloat(data);
  1001. if (hasOwnProperty.call(offer, key)) {
  1002. offer[key] = [].concat(offer[key]);
  1003. offer[key].push(data);
  1004. } else {
  1005. offer[key] = data;
  1006. }
  1007. }, this);
  1008. offers.push(name, offer);
  1009. }, this);
  1010. return offers;
  1011. },
  1012. serializeParams: function(name, params) {
  1013. var values = [];
  1014. var print = function(key, value) {
  1015. if (value instanceof Array) {
  1016. value.forEach(function(v) { print(key, v); });
  1017. } else if (value === true) {
  1018. values.push(key);
  1019. } else if (typeof value === 'number') {
  1020. values.push(key + '=' + value);
  1021. } else if (NOTOKEN.test(value)) {
  1022. values.push(key + '="' + value.replace(/"/g, '\\"') + '"');
  1023. } else {
  1024. values.push(key + '=' + value);
  1025. }
  1026. };
  1027. for (var key in params) print(key, params[key]);
  1028. return [name].concat(values).join('; ');
  1029. }
  1030. };
  1031. var Offers = function() {
  1032. this._byName = {};
  1033. this._inOrder = [];
  1034. };
  1035. Offers.prototype.push = function(name, params) {
  1036. if (!hasOwnProperty.call(this._byName, name))
  1037. this._byName[name] = [];
  1038. this._byName[name].push(params);
  1039. this._inOrder.push({ name: name, params: params });
  1040. };
  1041. Offers.prototype.eachOffer = function(callback, context) {
  1042. var list = this._inOrder;
  1043. for (var i = 0, n = list.length; i < n; i++)
  1044. callback.call(context, list[i].name, list[i].params);
  1045. };
  1046. Offers.prototype.byName = function(name) {
  1047. return this._byName[name] || [];
  1048. };
  1049. Offers.prototype.toArray = function() {
  1050. return this._inOrder.slice();
  1051. };
  1052. var parser = Parser$1;
  1053. var RingBuffer$2 = function(bufferSize) {
  1054. this._bufferSize = bufferSize;
  1055. this.clear();
  1056. };
  1057. RingBuffer$2.prototype.clear = function() {
  1058. this._buffer = new Array(this._bufferSize);
  1059. this._ringOffset = 0;
  1060. this._ringSize = this._bufferSize;
  1061. this._head = 0;
  1062. this._tail = 0;
  1063. this.length = 0;
  1064. };
  1065. RingBuffer$2.prototype.push = function(value) {
  1066. var expandBuffer = false,
  1067. expandRing = false;
  1068. if (this._ringSize < this._bufferSize) {
  1069. expandBuffer = (this._tail === 0);
  1070. } else if (this._ringOffset === this._ringSize) {
  1071. expandBuffer = true;
  1072. expandRing = (this._tail === 0);
  1073. }
  1074. if (expandBuffer) {
  1075. this._tail = this._bufferSize;
  1076. this._buffer = this._buffer.concat(new Array(this._bufferSize));
  1077. this._bufferSize = this._buffer.length;
  1078. if (expandRing)
  1079. this._ringSize = this._bufferSize;
  1080. }
  1081. this._buffer[this._tail] = value;
  1082. this.length += 1;
  1083. if (this._tail < this._ringSize) this._ringOffset += 1;
  1084. this._tail = (this._tail + 1) % this._bufferSize;
  1085. };
  1086. RingBuffer$2.prototype.peek = function() {
  1087. if (this.length === 0) return void 0;
  1088. return this._buffer[this._head];
  1089. };
  1090. RingBuffer$2.prototype.shift = function() {
  1091. if (this.length === 0) return void 0;
  1092. var value = this._buffer[this._head];
  1093. this._buffer[this._head] = void 0;
  1094. this.length -= 1;
  1095. this._ringOffset -= 1;
  1096. if (this._ringOffset === 0 && this.length > 0) {
  1097. this._head = this._ringSize;
  1098. this._ringOffset = this.length;
  1099. this._ringSize = this._bufferSize;
  1100. } else {
  1101. this._head = (this._head + 1) % this._ringSize;
  1102. }
  1103. return value;
  1104. };
  1105. var ring_buffer = RingBuffer$2;
  1106. var RingBuffer$1 = ring_buffer;
  1107. var Functor$1 = function(session, method) {
  1108. this._session = session;
  1109. this._method = method;
  1110. this._queue = new RingBuffer$1(Functor$1.QUEUE_SIZE);
  1111. this._stopped = false;
  1112. this.pending = 0;
  1113. };
  1114. Functor$1.QUEUE_SIZE = 8;
  1115. Functor$1.prototype.call = function(error, message, callback, context) {
  1116. if (this._stopped) return;
  1117. var record = { error: error, message: message, callback: callback, context: context, done: false },
  1118. called = false,
  1119. self = this;
  1120. this._queue.push(record);
  1121. if (record.error) {
  1122. record.done = true;
  1123. this._stop();
  1124. return this._flushQueue();
  1125. }
  1126. var handler = function(err, msg) {
  1127. if (!(called ^ (called = true))) return;
  1128. if (err) {
  1129. self._stop();
  1130. record.error = err;
  1131. record.message = null;
  1132. } else {
  1133. record.message = msg;
  1134. }
  1135. record.done = true;
  1136. self._flushQueue();
  1137. };
  1138. try {
  1139. this._session[this._method](message, handler);
  1140. } catch (err) {
  1141. handler(err);
  1142. }
  1143. };
  1144. Functor$1.prototype._stop = function() {
  1145. this.pending = this._queue.length;
  1146. this._stopped = true;
  1147. };
  1148. Functor$1.prototype._flushQueue = function() {
  1149. var queue = this._queue, record;
  1150. while (queue.length > 0 && queue.peek().done) {
  1151. record = queue.shift();
  1152. if (record.error) {
  1153. this.pending = 0;
  1154. queue.clear();
  1155. } else {
  1156. this.pending -= 1;
  1157. }
  1158. record.callback.call(record.context, record.error, record.message);
  1159. }
  1160. };
  1161. var functor = Functor$1;
  1162. var RingBuffer = ring_buffer;
  1163. var Pledge$2 = function() {
  1164. this._complete = false;
  1165. this._callbacks = new RingBuffer(Pledge$2.QUEUE_SIZE);
  1166. };
  1167. Pledge$2.QUEUE_SIZE = 4;
  1168. Pledge$2.all = function(list) {
  1169. var pledge = new Pledge$2(),
  1170. pending = list.length,
  1171. n = pending;
  1172. if (pending === 0) pledge.done();
  1173. while (n--) list[n].then(function() {
  1174. pending -= 1;
  1175. if (pending === 0) pledge.done();
  1176. });
  1177. return pledge;
  1178. };
  1179. Pledge$2.prototype.then = function(callback) {
  1180. if (this._complete) callback();
  1181. else this._callbacks.push(callback);
  1182. };
  1183. Pledge$2.prototype.done = function() {
  1184. this._complete = true;
  1185. var callbacks = this._callbacks, callback;
  1186. while (callback = callbacks.shift()) callback();
  1187. };
  1188. var pledge = Pledge$2;
  1189. var Functor = functor,
  1190. Pledge$1 = pledge;
  1191. var Cell$1 = function(tuple) {
  1192. this._ext = tuple[0];
  1193. this._session = tuple[1];
  1194. this._functors = {
  1195. incoming: new Functor(this._session, 'processIncomingMessage'),
  1196. outgoing: new Functor(this._session, 'processOutgoingMessage')
  1197. };
  1198. };
  1199. Cell$1.prototype.pending = function(direction) {
  1200. var functor = this._functors[direction];
  1201. if (!functor._stopped) functor.pending += 1;
  1202. };
  1203. Cell$1.prototype.incoming = function(error, message, callback, context) {
  1204. this._exec('incoming', error, message, callback, context);
  1205. };
  1206. Cell$1.prototype.outgoing = function(error, message, callback, context) {
  1207. this._exec('outgoing', error, message, callback, context);
  1208. };
  1209. Cell$1.prototype.close = function() {
  1210. this._closed = this._closed || new Pledge$1();
  1211. this._doClose();
  1212. return this._closed;
  1213. };
  1214. Cell$1.prototype._exec = function(direction, error, message, callback, context) {
  1215. this._functors[direction].call(error, message, function(err, msg) {
  1216. if (err) err.message = this._ext.name + ': ' + err.message;
  1217. callback.call(context, err, msg);
  1218. this._doClose();
  1219. }, this);
  1220. };
  1221. Cell$1.prototype._doClose = function() {
  1222. var fin = this._functors.incoming,
  1223. fout = this._functors.outgoing;
  1224. if (!this._closed || fin.pending + fout.pending !== 0) return;
  1225. if (this._session) this._session.close();
  1226. this._session = null;
  1227. this._closed.done();
  1228. };
  1229. var cell = Cell$1;
  1230. var Cell = cell,
  1231. Pledge = pledge;
  1232. var Pipeline$1 = function(sessions) {
  1233. this._cells = sessions.map(function(session) { return new Cell(session) });
  1234. this._stopped = { incoming: false, outgoing: false };
  1235. };
  1236. Pipeline$1.prototype.processIncomingMessage = function(message, callback, context) {
  1237. if (this._stopped.incoming) return;
  1238. this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context);
  1239. };
  1240. Pipeline$1.prototype.processOutgoingMessage = function(message, callback, context) {
  1241. if (this._stopped.outgoing) return;
  1242. this._loop('outgoing', 0, this._cells.length, 1, message, callback, context);
  1243. };
  1244. Pipeline$1.prototype.close = function(callback, context) {
  1245. this._stopped = { incoming: true, outgoing: true };
  1246. var closed = this._cells.map(function(a) { return a.close() });
  1247. if (callback)
  1248. Pledge.all(closed).then(function() { callback.call(context); });
  1249. };
  1250. Pipeline$1.prototype._loop = function(direction, start, end, step, message, callback, context) {
  1251. var cells = this._cells,
  1252. n = cells.length,
  1253. self = this;
  1254. while (n--) cells[n].pending(direction);
  1255. var pipe = function(index, error, msg) {
  1256. if (index === end) return callback.call(context, error, msg);
  1257. cells[index][direction](error, msg, function(err, m) {
  1258. if (err) self._stopped[direction] = true;
  1259. pipe(index + step, err, m);
  1260. });
  1261. };
  1262. pipe(start, null, message);
  1263. };
  1264. var pipeline = Pipeline$1;
  1265. var Parser = parser,
  1266. Pipeline = pipeline;
  1267. var Extensions$1 = function() {
  1268. this._rsv1 = this._rsv2 = this._rsv3 = null;
  1269. this._byName = {};
  1270. this._inOrder = [];
  1271. this._sessions = [];
  1272. this._index = {};
  1273. };
  1274. Extensions$1.MESSAGE_OPCODES = [1, 2];
  1275. var instance$a = {
  1276. add: function(ext) {
  1277. if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string');
  1278. if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"');
  1279. if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false');
  1280. if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false');
  1281. if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false');
  1282. if (this._byName.hasOwnProperty(ext.name))
  1283. throw new TypeError('An extension with name "' + ext.name + '" is already registered');
  1284. this._byName[ext.name] = ext;
  1285. this._inOrder.push(ext);
  1286. },
  1287. generateOffer: function() {
  1288. var sessions = [],
  1289. offer = [],
  1290. index = {};
  1291. this._inOrder.forEach(function(ext) {
  1292. var session = ext.createClientSession();
  1293. if (!session) return;
  1294. var record = [ext, session];
  1295. sessions.push(record);
  1296. index[ext.name] = record;
  1297. var offers = session.generateOffer();
  1298. offers = offers ? [].concat(offers) : [];
  1299. offers.forEach(function(off) {
  1300. offer.push(Parser.serializeParams(ext.name, off));
  1301. }, this);
  1302. }, this);
  1303. this._sessions = sessions;
  1304. this._index = index;
  1305. return offer.length > 0 ? offer.join(', ') : null;
  1306. },
  1307. activate: function(header) {
  1308. var responses = Parser.parseHeader(header),
  1309. sessions = [];
  1310. responses.eachOffer(function(name, params) {
  1311. var record = this._index[name];
  1312. if (!record)
  1313. throw new Error('Server sent an extension response for unknown extension "' + name + '"');
  1314. var ext = record[0],
  1315. session = record[1],
  1316. reserved = this._reserved(ext);
  1317. if (reserved)
  1318. throw new Error('Server sent two extension responses that use the RSV' +
  1319. reserved[0] + ' bit: "' +
  1320. reserved[1] + '" and "' + ext.name + '"');
  1321. if (session.activate(params) !== true)
  1322. throw new Error('Server sent unacceptable extension parameters: ' +
  1323. Parser.serializeParams(name, params));
  1324. this._reserve(ext);
  1325. sessions.push(record);
  1326. }, this);
  1327. this._sessions = sessions;
  1328. this._pipeline = new Pipeline(sessions);
  1329. },
  1330. generateResponse: function(header) {
  1331. var sessions = [],
  1332. response = [],
  1333. offers = Parser.parseHeader(header);
  1334. this._inOrder.forEach(function(ext) {
  1335. var offer = offers.byName(ext.name);
  1336. if (offer.length === 0 || this._reserved(ext)) return;
  1337. var session = ext.createServerSession(offer);
  1338. if (!session) return;
  1339. this._reserve(ext);
  1340. sessions.push([ext, session]);
  1341. response.push(Parser.serializeParams(ext.name, session.generateResponse()));
  1342. }, this);
  1343. this._sessions = sessions;
  1344. this._pipeline = new Pipeline(sessions);
  1345. return response.length > 0 ? response.join(', ') : null;
  1346. },
  1347. validFrameRsv: function(frame) {
  1348. var allowed = { rsv1: false, rsv2: false, rsv3: false },
  1349. ext;
  1350. if (Extensions$1.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) {
  1351. for (var i = 0, n = this._sessions.length; i < n; i++) {
  1352. ext = this._sessions[i][0];
  1353. allowed.rsv1 = allowed.rsv1 || ext.rsv1;
  1354. allowed.rsv2 = allowed.rsv2 || ext.rsv2;
  1355. allowed.rsv3 = allowed.rsv3 || ext.rsv3;
  1356. }
  1357. }
  1358. return (allowed.rsv1 || !frame.rsv1) &&
  1359. (allowed.rsv2 || !frame.rsv2) &&
  1360. (allowed.rsv3 || !frame.rsv3);
  1361. },
  1362. processIncomingMessage: function(message, callback, context) {
  1363. this._pipeline.processIncomingMessage(message, callback, context);
  1364. },
  1365. processOutgoingMessage: function(message, callback, context) {
  1366. this._pipeline.processOutgoingMessage(message, callback, context);
  1367. },
  1368. close: function(callback, context) {
  1369. if (!this._pipeline) return callback.call(context);
  1370. this._pipeline.close(callback, context);
  1371. },
  1372. _reserve: function(ext) {
  1373. this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name);
  1374. this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name);
  1375. this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name);
  1376. },
  1377. _reserved: function(ext) {
  1378. if (this._rsv1 && ext.rsv1) return [1, this._rsv1];
  1379. if (this._rsv2 && ext.rsv2) return [2, this._rsv2];
  1380. if (this._rsv3 && ext.rsv3) return [3, this._rsv3];
  1381. return false;
  1382. }
  1383. };
  1384. for (var key$a in instance$a)
  1385. Extensions$1.prototype[key$a] = instance$a[key$a];
  1386. var websocket_extensions = Extensions$1;
  1387. var Frame$1 = function() {};
  1388. var instance$9 = {
  1389. final: false,
  1390. rsv1: false,
  1391. rsv2: false,
  1392. rsv3: false,
  1393. opcode: null,
  1394. masked: false,
  1395. maskingKey: null,
  1396. lengthBytes: 1,
  1397. length: 0,
  1398. payload: null
  1399. };
  1400. for (var key$9 in instance$9)
  1401. Frame$1.prototype[key$9] = instance$9[key$9];
  1402. var frame = Frame$1;
  1403. var Buffer$6 = safeBuffer.exports.Buffer;
  1404. var Message$1 = function() {
  1405. this.rsv1 = false;
  1406. this.rsv2 = false;
  1407. this.rsv3 = false;
  1408. this.opcode = null;
  1409. this.length = 0;
  1410. this._chunks = [];
  1411. };
  1412. var instance$8 = {
  1413. read: function() {
  1414. return this.data = this.data || Buffer$6.concat(this._chunks, this.length);
  1415. },
  1416. pushFrame: function(frame) {
  1417. this.rsv1 = this.rsv1 || frame.rsv1;
  1418. this.rsv2 = this.rsv2 || frame.rsv2;
  1419. this.rsv3 = this.rsv3 || frame.rsv3;
  1420. if (this.opcode === null) this.opcode = frame.opcode;
  1421. this._chunks.push(frame.payload);
  1422. this.length += frame.length;
  1423. }
  1424. };
  1425. for (var key$8 in instance$8)
  1426. Message$1.prototype[key$8] = instance$8[key$8];
  1427. var message = Message$1;
  1428. var Buffer$5 = safeBuffer.exports.Buffer,
  1429. crypto$2 = require$$1__default$1["default"],
  1430. util$a = require$$2__default["default"],
  1431. Extensions = websocket_extensions,
  1432. Base$6 = base,
  1433. Frame = frame,
  1434. Message = message;
  1435. var Hybi$2 = function(request, url, options) {
  1436. Base$6.apply(this, arguments);
  1437. this._extensions = new Extensions();
  1438. this._stage = 0;
  1439. this._masking = this._options.masking;
  1440. this._protocols = this._options.protocols || [];
  1441. this._requireMasking = this._options.requireMasking;
  1442. this._pingCallbacks = {};
  1443. if (typeof this._protocols === 'string')
  1444. this._protocols = this._protocols.split(/ *, */);
  1445. if (!this._request) return;
  1446. var protos = this._request.headers['sec-websocket-protocol'],
  1447. supported = this._protocols;
  1448. if (protos !== undefined) {
  1449. if (typeof protos === 'string') protos = protos.split(/ *, */);
  1450. this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0];
  1451. }
  1452. this.version = 'hybi-' + Hybi$2.VERSION;
  1453. };
  1454. util$a.inherits(Hybi$2, Base$6);
  1455. Hybi$2.VERSION = '13';
  1456. Hybi$2.mask = function(payload, mask, offset) {
  1457. if (!mask || mask.length === 0) return payload;
  1458. offset = offset || 0;
  1459. for (var i = 0, n = payload.length - offset; i < n; i++) {
  1460. payload[offset + i] = payload[offset + i] ^ mask[i % 4];
  1461. }
  1462. return payload;
  1463. };
  1464. Hybi$2.generateAccept = function(key) {
  1465. var sha1 = crypto$2.createHash('sha1');
  1466. sha1.update(key + Hybi$2.GUID);
  1467. return sha1.digest('base64');
  1468. };
  1469. Hybi$2.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  1470. var instance$7 = {
  1471. FIN: 0x80,
  1472. MASK: 0x80,
  1473. RSV1: 0x40,
  1474. RSV2: 0x20,
  1475. RSV3: 0x10,
  1476. OPCODE: 0x0F,
  1477. LENGTH: 0x7F,
  1478. OPCODES: {
  1479. continuation: 0,
  1480. text: 1,
  1481. binary: 2,
  1482. close: 8,
  1483. ping: 9,
  1484. pong: 10
  1485. },
  1486. OPCODE_CODES: [0, 1, 2, 8, 9, 10],
  1487. MESSAGE_OPCODES: [0, 1, 2],
  1488. OPENING_OPCODES: [1, 2],
  1489. ERRORS: {
  1490. normal_closure: 1000,
  1491. going_away: 1001,
  1492. protocol_error: 1002,
  1493. unacceptable: 1003,
  1494. encoding_error: 1007,
  1495. policy_violation: 1008,
  1496. too_large: 1009,
  1497. extension_error: 1010,
  1498. unexpected_condition: 1011
  1499. },
  1500. ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011],
  1501. DEFAULT_ERROR_CODE: 1000,
  1502. MIN_RESERVED_ERROR: 3000,
  1503. MAX_RESERVED_ERROR: 4999,
  1504. // http://www.w3.org/International/questions/qa-forms-utf-8.en.php
  1505. UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/,
  1506. addExtension: function(extension) {
  1507. this._extensions.add(extension);
  1508. return true;
  1509. },
  1510. parse: function(chunk) {
  1511. this._reader.put(chunk);
  1512. var buffer = true;
  1513. while (buffer) {
  1514. switch (this._stage) {
  1515. case 0:
  1516. buffer = this._reader.read(1);
  1517. if (buffer) this._parseOpcode(buffer[0]);
  1518. break;
  1519. case 1:
  1520. buffer = this._reader.read(1);
  1521. if (buffer) this._parseLength(buffer[0]);
  1522. break;
  1523. case 2:
  1524. buffer = this._reader.read(this._frame.lengthBytes);
  1525. if (buffer) this._parseExtendedLength(buffer);
  1526. break;
  1527. case 3:
  1528. buffer = this._reader.read(4);
  1529. if (buffer) {
  1530. this._stage = 4;
  1531. this._frame.maskingKey = buffer;
  1532. }
  1533. break;
  1534. case 4:
  1535. buffer = this._reader.read(this._frame.length);
  1536. if (buffer) {
  1537. this._stage = 0;
  1538. this._emitFrame(buffer);
  1539. }
  1540. break;
  1541. default:
  1542. buffer = null;
  1543. }
  1544. }
  1545. },
  1546. text: function(message) {
  1547. if (this.readyState > 1) return false;
  1548. return this.frame(message, 'text');
  1549. },
  1550. binary: function(message) {
  1551. if (this.readyState > 1) return false;
  1552. return this.frame(message, 'binary');
  1553. },
  1554. ping: function(message, callback) {
  1555. if (this.readyState > 1) return false;
  1556. message = message || '';
  1557. if (callback) this._pingCallbacks[message] = callback;
  1558. return this.frame(message, 'ping');
  1559. },
  1560. pong: function(message) {
  1561. if (this.readyState > 1) return false;
  1562. message = message ||'';
  1563. return this.frame(message, 'pong');
  1564. },
  1565. close: function(reason, code) {
  1566. reason = reason || '';
  1567. code = code || this.ERRORS.normal_closure;
  1568. if (this.readyState <= 0) {
  1569. this.readyState = 3;
  1570. this.emit('close', new Base$6.CloseEvent(code, reason));
  1571. return true;
  1572. } else if (this.readyState === 1) {
  1573. this.readyState = 2;
  1574. this._extensions.close(function() { this.frame(reason, 'close', code); }, this);
  1575. return true;
  1576. } else {
  1577. return false;
  1578. }
  1579. },
  1580. frame: function(buffer, type, code) {
  1581. if (this.readyState <= 0) return this._queue([buffer, type, code]);
  1582. if (this.readyState > 2) return false;
  1583. if (buffer instanceof Array) buffer = Buffer$5.from(buffer);
  1584. if (typeof buffer === 'number') buffer = buffer.toString();
  1585. var message = new Message(),
  1586. isText = (typeof buffer === 'string'),
  1587. payload, copy;
  1588. message.rsv1 = message.rsv2 = message.rsv3 = false;
  1589. message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')];
  1590. payload = isText ? Buffer$5.from(buffer, 'utf8') : buffer;
  1591. if (code) {
  1592. copy = payload;
  1593. payload = Buffer$5.allocUnsafe(2 + copy.length);
  1594. payload.writeUInt16BE(code, 0);
  1595. copy.copy(payload, 2);
  1596. }
  1597. message.data = payload;
  1598. var onMessageReady = function(message) {
  1599. var frame = new Frame();
  1600. frame.final = true;
  1601. frame.rsv1 = message.rsv1;
  1602. frame.rsv2 = message.rsv2;
  1603. frame.rsv3 = message.rsv3;
  1604. frame.opcode = message.opcode;
  1605. frame.masked = !!this._masking;
  1606. frame.length = message.data.length;
  1607. frame.payload = message.data;
  1608. if (frame.masked) frame.maskingKey = crypto$2.randomBytes(4);
  1609. this._sendFrame(frame);
  1610. };
  1611. if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0)
  1612. this._extensions.processOutgoingMessage(message, function(error, message) {
  1613. if (error) return this._fail('extension_error', error.message);
  1614. onMessageReady.call(this, message);
  1615. }, this);
  1616. else
  1617. onMessageReady.call(this, message);
  1618. return true;
  1619. },
  1620. _sendFrame: function(frame) {
  1621. var length = frame.length,
  1622. header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10),
  1623. offset = header + (frame.masked ? 4 : 0),
  1624. buffer = Buffer$5.allocUnsafe(offset + length),
  1625. masked = frame.masked ? this.MASK : 0;
  1626. buffer[0] = (frame.final ? this.FIN : 0) |
  1627. (frame.rsv1 ? this.RSV1 : 0) |
  1628. (frame.rsv2 ? this.RSV2 : 0) |
  1629. (frame.rsv3 ? this.RSV3 : 0) |
  1630. frame.opcode;
  1631. if (length <= 125) {
  1632. buffer[1] = masked | length;
  1633. } else if (length <= 65535) {
  1634. buffer[1] = masked | 126;
  1635. buffer.writeUInt16BE(length, 2);
  1636. } else {
  1637. buffer[1] = masked | 127;
  1638. buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2);
  1639. buffer.writeUInt32BE(length % 0x100000000, 6);
  1640. }
  1641. frame.payload.copy(buffer, offset);
  1642. if (frame.masked) {
  1643. frame.maskingKey.copy(buffer, header);
  1644. Hybi$2.mask(buffer, frame.maskingKey, offset);
  1645. }
  1646. this._write(buffer);
  1647. },
  1648. _handshakeResponse: function() {
  1649. var secKey = this._request.headers['sec-websocket-key'],
  1650. version = this._request.headers['sec-websocket-version'];
  1651. if (version !== Hybi$2.VERSION)
  1652. throw new Error('Unsupported WebSocket version: ' + version);
  1653. if (typeof secKey !== 'string')
  1654. throw new Error('Missing handshake request header: Sec-WebSocket-Key');
  1655. this._headers.set('Upgrade', 'websocket');
  1656. this._headers.set('Connection', 'Upgrade');
  1657. this._headers.set('Sec-WebSocket-Accept', Hybi$2.generateAccept(secKey));
  1658. if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol);
  1659. var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']);
  1660. if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions);
  1661. var start = 'HTTP/1.1 101 Switching Protocols',
  1662. headers = [start, this._headers.toString(), ''];
  1663. return Buffer$5.from(headers.join('\r\n'), 'utf8');
  1664. },
  1665. _shutdown: function(code, reason, error) {
  1666. delete this._frame;
  1667. delete this._message;
  1668. this._stage = 5;
  1669. var sendCloseFrame = (this.readyState === 1);
  1670. this.readyState = 2;
  1671. this._extensions.close(function() {
  1672. if (sendCloseFrame) this.frame(reason, 'close', code);
  1673. this.readyState = 3;
  1674. if (error) this.emit('error', new Error(reason));
  1675. this.emit('close', new Base$6.CloseEvent(code, reason));
  1676. }, this);
  1677. },
  1678. _fail: function(type, message) {
  1679. if (this.readyState > 1) return;
  1680. this._shutdown(this.ERRORS[type], message, true);
  1681. },
  1682. _parseOpcode: function(octet) {
  1683. var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) {
  1684. return (octet & rsv) === rsv;
  1685. });
  1686. var frame = this._frame = new Frame();
  1687. frame.final = (octet & this.FIN) === this.FIN;
  1688. frame.rsv1 = rsvs[0];
  1689. frame.rsv2 = rsvs[1];
  1690. frame.rsv3 = rsvs[2];
  1691. frame.opcode = (octet & this.OPCODE);
  1692. this._stage = 1;
  1693. if (!this._extensions.validFrameRsv(frame))
  1694. return this._fail('protocol_error',
  1695. 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) +
  1696. ', reserved2 = ' + (frame.rsv2 ? 1 : 0) +
  1697. ', reserved3 = ' + (frame.rsv3 ? 1 : 0));
  1698. if (this.OPCODE_CODES.indexOf(frame.opcode) < 0)
  1699. return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode);
  1700. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final)
  1701. return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode);
  1702. if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0)
  1703. return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished');
  1704. },
  1705. _parseLength: function(octet) {
  1706. var frame = this._frame;
  1707. frame.masked = (octet & this.MASK) === this.MASK;
  1708. frame.length = (octet & this.LENGTH);
  1709. if (frame.length >= 0 && frame.length <= 125) {
  1710. this._stage = frame.masked ? 3 : 4;
  1711. if (!this._checkFrameLength()) return;
  1712. } else {
  1713. this._stage = 2;
  1714. frame.lengthBytes = (frame.length === 126 ? 2 : 8);
  1715. }
  1716. if (this._requireMasking && !frame.masked)
  1717. return this._fail('unacceptable', 'Received unmasked frame but masking is required');
  1718. },
  1719. _parseExtendedLength: function(buffer) {
  1720. var frame = this._frame;
  1721. frame.length = this._readUInt(buffer);
  1722. this._stage = frame.masked ? 3 : 4;
  1723. if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125)
  1724. return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length);
  1725. if (!this._checkFrameLength()) return;
  1726. },
  1727. _checkFrameLength: function() {
  1728. var length = this._message ? this._message.length : 0;
  1729. if (length + this._frame.length > this._maxLength) {
  1730. this._fail('too_large', 'WebSocket frame length too large');
  1731. return false;
  1732. } else {
  1733. return true;
  1734. }
  1735. },
  1736. _emitFrame: function(buffer) {
  1737. var frame = this._frame,
  1738. payload = frame.payload = Hybi$2.mask(buffer, frame.maskingKey),
  1739. opcode = frame.opcode,
  1740. message,
  1741. code, reason,
  1742. callbacks, callback;
  1743. delete this._frame;
  1744. if (opcode === this.OPCODES.continuation) {
  1745. if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame');
  1746. this._message.pushFrame(frame);
  1747. }
  1748. if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) {
  1749. this._message = new Message();
  1750. this._message.pushFrame(frame);
  1751. }
  1752. if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0)
  1753. return this._emitMessage(this._message);
  1754. if (opcode === this.OPCODES.close) {
  1755. code = (payload.length >= 2) ? payload.readUInt16BE(0) : null;
  1756. reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null;
  1757. if (!(payload.length === 0) &&
  1758. !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) &&
  1759. this.ERROR_CODES.indexOf(code) < 0)
  1760. code = this.ERRORS.protocol_error;
  1761. if (payload.length > 125 || (payload.length > 2 && !reason))
  1762. code = this.ERRORS.protocol_error;
  1763. this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || '');
  1764. }
  1765. if (opcode === this.OPCODES.ping) {
  1766. this.frame(payload, 'pong');
  1767. this.emit('ping', new Base$6.PingEvent(payload.toString()));
  1768. }
  1769. if (opcode === this.OPCODES.pong) {
  1770. callbacks = this._pingCallbacks;
  1771. message = this._encode(payload);
  1772. callback = callbacks[message];
  1773. delete callbacks[message];
  1774. if (callback) callback();
  1775. this.emit('pong', new Base$6.PongEvent(payload.toString()));
  1776. }
  1777. },
  1778. _emitMessage: function(message) {
  1779. var message = this._message;
  1780. message.read();
  1781. delete this._message;
  1782. this._extensions.processIncomingMessage(message, function(error, message) {
  1783. if (error) return this._fail('extension_error', error.message);
  1784. var payload = message.data;
  1785. if (message.opcode === this.OPCODES.text) payload = this._encode(payload);
  1786. if (payload === null)
  1787. return this._fail('encoding_error', 'Could not decode a text frame as UTF-8');
  1788. else
  1789. this.emit('message', new Base$6.MessageEvent(payload));
  1790. }, this);
  1791. },
  1792. _encode: function(buffer) {
  1793. try {
  1794. var string = buffer.toString('binary', 0, buffer.length);
  1795. if (!this.UTF8_MATCH.test(string)) return null;
  1796. } catch (e) {}
  1797. return buffer.toString('utf8', 0, buffer.length);
  1798. },
  1799. _readUInt: function(buffer) {
  1800. if (buffer.length === 2) return buffer.readUInt16BE(0);
  1801. return buffer.readUInt32BE(0) * 0x100000000 +
  1802. buffer.readUInt32BE(4);
  1803. }
  1804. };
  1805. for (var key$7 in instance$7)
  1806. Hybi$2.prototype[key$7] = instance$7[key$7];
  1807. var hybi = Hybi$2;
  1808. var Buffer$4 = safeBuffer.exports.Buffer,
  1809. Stream$2 = require$$0__default$1["default"].Stream,
  1810. url$2 = require$$2__default$1["default"],
  1811. util$9 = require$$2__default["default"],
  1812. Base$5 = base,
  1813. Headers$1 = headers,
  1814. HttpParser$2 = http_parser;
  1815. var PORTS = { 'ws:': 80, 'wss:': 443 };
  1816. var Proxy$1 = function(client, origin, options) {
  1817. this._client = client;
  1818. this._http = new HttpParser$2('response');
  1819. this._origin = (typeof client.url === 'object') ? client.url : url$2.parse(client.url);
  1820. this._url = (typeof origin === 'object') ? origin : url$2.parse(origin);
  1821. this._options = options || {};
  1822. this._state = 0;
  1823. this.readable = this.writable = true;
  1824. this._paused = false;
  1825. this._headers = new Headers$1();
  1826. this._headers.set('Host', this._origin.host);
  1827. this._headers.set('Connection', 'keep-alive');
  1828. this._headers.set('Proxy-Connection', 'keep-alive');
  1829. var auth = this._url.auth && Buffer$4.from(this._url.auth, 'utf8').toString('base64');
  1830. if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth);
  1831. };
  1832. util$9.inherits(Proxy$1, Stream$2);
  1833. var instance$6 = {
  1834. setHeader: function(name, value) {
  1835. if (this._state !== 0) return false;
  1836. this._headers.set(name, value);
  1837. return true;
  1838. },
  1839. start: function() {
  1840. if (this._state !== 0) return false;
  1841. this._state = 1;
  1842. var origin = this._origin,
  1843. port = origin.port || PORTS[origin.protocol],
  1844. start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1';
  1845. var headers = [start, this._headers.toString(), ''];
  1846. this.emit('data', Buffer$4.from(headers.join('\r\n'), 'utf8'));
  1847. return true;
  1848. },
  1849. pause: function() {
  1850. this._paused = true;
  1851. },
  1852. resume: function() {
  1853. this._paused = false;
  1854. this.emit('drain');
  1855. },
  1856. write: function(chunk) {
  1857. if (!this.writable) return false;
  1858. this._http.parse(chunk);
  1859. if (!this._http.isComplete()) return !this._paused;
  1860. this.statusCode = this._http.statusCode;
  1861. this.headers = this._http.headers;
  1862. if (this.statusCode === 200) {
  1863. this.emit('connect', new Base$5.ConnectEvent());
  1864. } else {
  1865. var message = "Can't establish a connection to the server at " + this._origin.href;
  1866. this.emit('error', new Error(message));
  1867. }
  1868. this.end();
  1869. return !this._paused;
  1870. },
  1871. end: function(chunk) {
  1872. if (!this.writable) return;
  1873. if (chunk !== undefined) this.write(chunk);
  1874. this.readable = this.writable = false;
  1875. this.emit('close');
  1876. this.emit('end');
  1877. },
  1878. destroy: function() {
  1879. this.end();
  1880. }
  1881. };
  1882. for (var key$6 in instance$6)
  1883. Proxy$1.prototype[key$6] = instance$6[key$6];
  1884. var proxy = Proxy$1;
  1885. var Buffer$3 = safeBuffer.exports.Buffer,
  1886. crypto$1 = require$$1__default$1["default"],
  1887. url$1 = require$$2__default$1["default"],
  1888. util$8 = require$$2__default["default"],
  1889. HttpParser$1 = http_parser,
  1890. Base$4 = base,
  1891. Hybi$1 = hybi,
  1892. Proxy = proxy;
  1893. var Client$2 = function(_url, options) {
  1894. this.version = 'hybi-' + Hybi$1.VERSION;
  1895. Hybi$1.call(this, null, _url, options);
  1896. this.readyState = -1;
  1897. this._key = Client$2.generateKey();
  1898. this._accept = Hybi$1.generateAccept(this._key);
  1899. this._http = new HttpParser$1('response');
  1900. var uri = url$1.parse(this.url),
  1901. auth = uri.auth && Buffer$3.from(uri.auth, 'utf8').toString('base64');
  1902. if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)
  1903. throw new Error(this.url + ' is not a valid WebSocket URL');
  1904. this._pathname = (uri.pathname || '/') + (uri.search || '');
  1905. this._headers.set('Host', uri.host);
  1906. this._headers.set('Upgrade', 'websocket');
  1907. this._headers.set('Connection', 'Upgrade');
  1908. this._headers.set('Sec-WebSocket-Key', this._key);
  1909. this._headers.set('Sec-WebSocket-Version', Hybi$1.VERSION);
  1910. if (this._protocols.length > 0)
  1911. this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', '));
  1912. if (auth)
  1913. this._headers.set('Authorization', 'Basic ' + auth);
  1914. };
  1915. util$8.inherits(Client$2, Hybi$1);
  1916. Client$2.generateKey = function() {
  1917. return crypto$1.randomBytes(16).toString('base64');
  1918. };
  1919. var instance$5 = {
  1920. VALID_PROTOCOLS: ['ws:', 'wss:'],
  1921. proxy: function(origin, options) {
  1922. return new Proxy(this, origin, options);
  1923. },
  1924. start: function() {
  1925. if (this.readyState !== -1) return false;
  1926. this._write(this._handshakeRequest());
  1927. this.readyState = 0;
  1928. return true;
  1929. },
  1930. parse: function(chunk) {
  1931. if (this.readyState === 3) return;
  1932. if (this.readyState > 0) return Hybi$1.prototype.parse.call(this, chunk);
  1933. this._http.parse(chunk);
  1934. if (!this._http.isComplete()) return;
  1935. this._validateHandshake();
  1936. if (this.readyState === 3) return;
  1937. this._open();
  1938. this.parse(this._http.body);
  1939. },
  1940. _handshakeRequest: function() {
  1941. var extensions = this._extensions.generateOffer();
  1942. if (extensions)
  1943. this._headers.set('Sec-WebSocket-Extensions', extensions);
  1944. var start = 'GET ' + this._pathname + ' HTTP/1.1',
  1945. headers = [start, this._headers.toString(), ''];
  1946. return Buffer$3.from(headers.join('\r\n'), 'utf8');
  1947. },
  1948. _failHandshake: function(message) {
  1949. message = 'Error during WebSocket handshake: ' + message;
  1950. this.readyState = 3;
  1951. this.emit('error', new Error(message));
  1952. this.emit('close', new Base$4.CloseEvent(this.ERRORS.protocol_error, message));
  1953. },
  1954. _validateHandshake: function() {
  1955. this.statusCode = this._http.statusCode;
  1956. this.headers = this._http.headers;
  1957. if (this._http.error)
  1958. return this._failHandshake(this._http.error.message);
  1959. if (this._http.statusCode !== 101)
  1960. return this._failHandshake('Unexpected response code: ' + this._http.statusCode);
  1961. var headers = this._http.headers,
  1962. upgrade = headers['upgrade'] || '',
  1963. connection = headers['connection'] || '',
  1964. accept = headers['sec-websocket-accept'] || '',
  1965. protocol = headers['sec-websocket-protocol'] || '';
  1966. if (upgrade === '')
  1967. return this._failHandshake("'Upgrade' header is missing");
  1968. if (upgrade.toLowerCase() !== 'websocket')
  1969. return this._failHandshake("'Upgrade' header value is not 'WebSocket'");
  1970. if (connection === '')
  1971. return this._failHandshake("'Connection' header is missing");
  1972. if (connection.toLowerCase() !== 'upgrade')
  1973. return this._failHandshake("'Connection' header value is not 'Upgrade'");
  1974. if (accept !== this._accept)
  1975. return this._failHandshake('Sec-WebSocket-Accept mismatch');
  1976. this.protocol = null;
  1977. if (protocol !== '') {
  1978. if (this._protocols.indexOf(protocol) < 0)
  1979. return this._failHandshake('Sec-WebSocket-Protocol mismatch');
  1980. else
  1981. this.protocol = protocol;
  1982. }
  1983. try {
  1984. this._extensions.activate(this.headers['sec-websocket-extensions']);
  1985. } catch (e) {
  1986. return this._failHandshake(e.message);
  1987. }
  1988. }
  1989. };
  1990. for (var key$5 in instance$5)
  1991. Client$2.prototype[key$5] = instance$5[key$5];
  1992. var client$1 = Client$2;
  1993. var Buffer$2 = safeBuffer.exports.Buffer,
  1994. Base$3 = base,
  1995. util$7 = require$$2__default["default"];
  1996. var Draft75$2 = function(request, url, options) {
  1997. Base$3.apply(this, arguments);
  1998. this._stage = 0;
  1999. this.version = 'hixie-75';
  2000. this._headers.set('Upgrade', 'WebSocket');
  2001. this._headers.set('Connection', 'Upgrade');
  2002. this._headers.set('WebSocket-Origin', this._request.headers.origin);
  2003. this._headers.set('WebSocket-Location', this.url);
  2004. };
  2005. util$7.inherits(Draft75$2, Base$3);
  2006. var instance$4 = {
  2007. close: function() {
  2008. if (this.readyState === 3) return false;
  2009. this.readyState = 3;
  2010. this.emit('close', new Base$3.CloseEvent(null, null));
  2011. return true;
  2012. },
  2013. parse: function(chunk) {
  2014. if (this.readyState > 1) return;
  2015. this._reader.put(chunk);
  2016. this._reader.eachByte(function(octet) {
  2017. var message;
  2018. switch (this._stage) {
  2019. case -1:
  2020. this._body.push(octet);
  2021. this._sendHandshakeBody();
  2022. break;
  2023. case 0:
  2024. this._parseLeadingByte(octet);
  2025. break;
  2026. case 1:
  2027. this._length = (octet & 0x7F) + 128 * this._length;
  2028. if (this._closing && this._length === 0) {
  2029. return this.close();
  2030. }
  2031. else if ((octet & 0x80) !== 0x80) {
  2032. if (this._length === 0) {
  2033. this._stage = 0;
  2034. }
  2035. else {
  2036. this._skipped = 0;
  2037. this._stage = 2;
  2038. }
  2039. }
  2040. break;
  2041. case 2:
  2042. if (octet === 0xFF) {
  2043. this._stage = 0;
  2044. message = Buffer$2.from(this._buffer).toString('utf8', 0, this._buffer.length);
  2045. this.emit('message', new Base$3.MessageEvent(message));
  2046. }
  2047. else {
  2048. if (this._length) {
  2049. this._skipped += 1;
  2050. if (this._skipped === this._length)
  2051. this._stage = 0;
  2052. } else {
  2053. this._buffer.push(octet);
  2054. if (this._buffer.length > this._maxLength) return this.close();
  2055. }
  2056. }
  2057. break;
  2058. }
  2059. }, this);
  2060. },
  2061. frame: function(buffer) {
  2062. if (this.readyState === 0) return this._queue([buffer]);
  2063. if (this.readyState > 1) return false;
  2064. if (typeof buffer !== 'string') buffer = buffer.toString();
  2065. var length = Buffer$2.byteLength(buffer),
  2066. frame = Buffer$2.allocUnsafe(length + 2);
  2067. frame[0] = 0x00;
  2068. frame.write(buffer, 1);
  2069. frame[frame.length - 1] = 0xFF;
  2070. this._write(frame);
  2071. return true;
  2072. },
  2073. _handshakeResponse: function() {
  2074. var start = 'HTTP/1.1 101 Web Socket Protocol Handshake',
  2075. headers = [start, this._headers.toString(), ''];
  2076. return Buffer$2.from(headers.join('\r\n'), 'utf8');
  2077. },
  2078. _parseLeadingByte: function(octet) {
  2079. if ((octet & 0x80) === 0x80) {
  2080. this._length = 0;
  2081. this._stage = 1;
  2082. } else {
  2083. delete this._length;
  2084. delete this._skipped;
  2085. this._buffer = [];
  2086. this._stage = 2;
  2087. }
  2088. }
  2089. };
  2090. for (var key$4 in instance$4)
  2091. Draft75$2.prototype[key$4] = instance$4[key$4];
  2092. var draft75 = Draft75$2;
  2093. var Buffer$1 = safeBuffer.exports.Buffer,
  2094. Base$2 = base,
  2095. Draft75$1 = draft75,
  2096. crypto = require$$1__default$1["default"],
  2097. util$6 = require$$2__default["default"];
  2098. var numberFromKey = function(key) {
  2099. return parseInt((key.match(/[0-9]/g) || []).join(''), 10);
  2100. };
  2101. var spacesInKey = function(key) {
  2102. return (key.match(/ /g) || []).length;
  2103. };
  2104. var Draft76$1 = function(request, url, options) {
  2105. Draft75$1.apply(this, arguments);
  2106. this._stage = -1;
  2107. this._body = [];
  2108. this.version = 'hixie-76';
  2109. this._headers.clear();
  2110. this._headers.set('Upgrade', 'WebSocket');
  2111. this._headers.set('Connection', 'Upgrade');
  2112. this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin);
  2113. this._headers.set('Sec-WebSocket-Location', this.url);
  2114. };
  2115. util$6.inherits(Draft76$1, Draft75$1);
  2116. var instance$3 = {
  2117. BODY_SIZE: 8,
  2118. start: function() {
  2119. if (!Draft75$1.prototype.start.call(this)) return false;
  2120. this._started = true;
  2121. this._sendHandshakeBody();
  2122. return true;
  2123. },
  2124. close: function() {
  2125. if (this.readyState === 3) return false;
  2126. if (this.readyState === 1) this._write(Buffer$1.from([0xFF, 0x00]));
  2127. this.readyState = 3;
  2128. this.emit('close', new Base$2.CloseEvent(null, null));
  2129. return true;
  2130. },
  2131. _handshakeResponse: function() {
  2132. var headers = this._request.headers,
  2133. key1 = headers['sec-websocket-key1'],
  2134. key2 = headers['sec-websocket-key2'];
  2135. if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1');
  2136. if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2');
  2137. var number1 = numberFromKey(key1),
  2138. spaces1 = spacesInKey(key1),
  2139. number2 = numberFromKey(key2),
  2140. spaces2 = spacesInKey(key2);
  2141. if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0)
  2142. throw new Error('Client sent invalid Sec-WebSocket-Key headers');
  2143. this._keyValues = [number1 / spaces1, number2 / spaces2];
  2144. var start = 'HTTP/1.1 101 WebSocket Protocol Handshake',
  2145. headers = [start, this._headers.toString(), ''];
  2146. return Buffer$1.from(headers.join('\r\n'), 'binary');
  2147. },
  2148. _handshakeSignature: function() {
  2149. if (this._body.length < this.BODY_SIZE) return null;
  2150. var md5 = crypto.createHash('md5'),
  2151. buffer = Buffer$1.allocUnsafe(8 + this.BODY_SIZE);
  2152. buffer.writeUInt32BE(this._keyValues[0], 0);
  2153. buffer.writeUInt32BE(this._keyValues[1], 4);
  2154. Buffer$1.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE);
  2155. md5.update(buffer);
  2156. return Buffer$1.from(md5.digest('binary'), 'binary');
  2157. },
  2158. _sendHandshakeBody: function() {
  2159. if (!this._started) return;
  2160. var signature = this._handshakeSignature();
  2161. if (!signature) return;
  2162. this._write(signature);
  2163. this._stage = 0;
  2164. this._open();
  2165. if (this._body.length > this.BODY_SIZE)
  2166. this.parse(this._body.slice(this.BODY_SIZE));
  2167. },
  2168. _parseLeadingByte: function(octet) {
  2169. if (octet !== 0xFF)
  2170. return Draft75$1.prototype._parseLeadingByte.call(this, octet);
  2171. this._closing = true;
  2172. this._length = 0;
  2173. this._stage = 1;
  2174. }
  2175. };
  2176. for (var key$3 in instance$3)
  2177. Draft76$1.prototype[key$3] = instance$3[key$3];
  2178. var draft76 = Draft76$1;
  2179. var util$5 = require$$2__default["default"],
  2180. HttpParser = http_parser,
  2181. Base$1 = base,
  2182. Draft75 = draft75,
  2183. Draft76 = draft76,
  2184. Hybi = hybi;
  2185. var Server$1 = function(options) {
  2186. Base$1.call(this, null, null, options);
  2187. this._http = new HttpParser('request');
  2188. };
  2189. util$5.inherits(Server$1, Base$1);
  2190. var instance$2 = {
  2191. EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'],
  2192. _bindEventListeners: function() {
  2193. this.messages.on('error', function() {});
  2194. this.on('error', function() {});
  2195. },
  2196. parse: function(chunk) {
  2197. if (this._delegate) return this._delegate.parse(chunk);
  2198. this._http.parse(chunk);
  2199. if (!this._http.isComplete()) return;
  2200. this.method = this._http.method;
  2201. this.url = this._http.url;
  2202. this.headers = this._http.headers;
  2203. this.body = this._http.body;
  2204. var self = this;
  2205. this._delegate = Server$1.http(this, this._options);
  2206. this._delegate.messages = this.messages;
  2207. this._delegate.io = this.io;
  2208. this._open();
  2209. this.EVENTS.forEach(function(event) {
  2210. this._delegate.on(event, function(e) { self.emit(event, e); });
  2211. }, this);
  2212. this.protocol = this._delegate.protocol;
  2213. this.version = this._delegate.version;
  2214. this.parse(this._http.body);
  2215. this.emit('connect', new Base$1.ConnectEvent());
  2216. },
  2217. _open: function() {
  2218. this.__queue.forEach(function(msg) {
  2219. this._delegate[msg[0]].apply(this._delegate, msg[1]);
  2220. }, this);
  2221. this.__queue = [];
  2222. }
  2223. };
  2224. ['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) {
  2225. instance$2[method] = function() {
  2226. if (this._delegate) {
  2227. return this._delegate[method].apply(this._delegate, arguments);
  2228. } else {
  2229. this.__queue.push([method, arguments]);
  2230. return true;
  2231. }
  2232. };
  2233. });
  2234. for (var key$2 in instance$2)
  2235. Server$1.prototype[key$2] = instance$2[key$2];
  2236. Server$1.isSecureRequest = function(request) {
  2237. if (request.connection && request.connection.authorized !== undefined) return true;
  2238. if (request.socket && request.socket.secure) return true;
  2239. var headers = request.headers;
  2240. if (!headers) return false;
  2241. if (headers['https'] === 'on') return true;
  2242. if (headers['x-forwarded-ssl'] === 'on') return true;
  2243. if (headers['x-forwarded-scheme'] === 'https') return true;
  2244. if (headers['x-forwarded-proto'] === 'https') return true;
  2245. return false;
  2246. };
  2247. Server$1.determineUrl = function(request) {
  2248. var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:';
  2249. return scheme + '//' + request.headers.host + request.url;
  2250. };
  2251. Server$1.http = function(request, options) {
  2252. options = options || {};
  2253. if (options.requireMasking === undefined) options.requireMasking = true;
  2254. var headers = request.headers,
  2255. version = headers['sec-websocket-version'],
  2256. key = headers['sec-websocket-key'],
  2257. key1 = headers['sec-websocket-key1'],
  2258. key2 = headers['sec-websocket-key2'],
  2259. url = this.determineUrl(request);
  2260. if (version || key)
  2261. return new Hybi(request, url, options);
  2262. else if (key1 || key2)
  2263. return new Draft76(request, url, options);
  2264. else
  2265. return new Draft75(request, url, options);
  2266. };
  2267. var server = Server$1;
  2268. // Protocol references:
  2269. //
  2270. // * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
  2271. // * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
  2272. // * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17
  2273. var Base = base,
  2274. Client$1 = client$1,
  2275. Server = server;
  2276. var Driver = {
  2277. client: function(url, options) {
  2278. options = options || {};
  2279. if (options.masking === undefined) options.masking = true;
  2280. return new Client$1(url, options);
  2281. },
  2282. server: function(options) {
  2283. options = options || {};
  2284. if (options.requireMasking === undefined) options.requireMasking = true;
  2285. return new Server(options);
  2286. },
  2287. http: function() {
  2288. return Server.http.apply(Server, arguments);
  2289. },
  2290. isSecureRequest: function(request) {
  2291. return Server.isSecureRequest(request);
  2292. },
  2293. isWebSocket: function(request) {
  2294. return Base.isWebSocket(request);
  2295. },
  2296. validateOptions: function(options, validKeys) {
  2297. Base.validateOptions(options, validKeys);
  2298. }
  2299. };
  2300. var driver$4 = Driver;
  2301. var Event$3 = function(eventType, options) {
  2302. this.type = eventType;
  2303. for (var key in options)
  2304. this[key] = options[key];
  2305. };
  2306. Event$3.prototype.initEvent = function(eventType, canBubble, cancelable) {
  2307. this.type = eventType;
  2308. this.bubbles = canBubble;
  2309. this.cancelable = cancelable;
  2310. };
  2311. Event$3.prototype.stopPropagation = function() {};
  2312. Event$3.prototype.preventDefault = function() {};
  2313. Event$3.CAPTURING_PHASE = 1;
  2314. Event$3.AT_TARGET = 2;
  2315. Event$3.BUBBLING_PHASE = 3;
  2316. var event = Event$3;
  2317. var Event$2 = event;
  2318. var EventTarget$2 = {
  2319. onopen: null,
  2320. onmessage: null,
  2321. onerror: null,
  2322. onclose: null,
  2323. addEventListener: function(eventType, listener, useCapture) {
  2324. this.on(eventType, listener);
  2325. },
  2326. removeEventListener: function(eventType, listener, useCapture) {
  2327. this.removeListener(eventType, listener);
  2328. },
  2329. dispatchEvent: function(event) {
  2330. event.target = event.currentTarget = this;
  2331. event.eventPhase = Event$2.AT_TARGET;
  2332. if (this['on' + event.type])
  2333. this['on' + event.type](event);
  2334. this.emit(event.type, event);
  2335. }
  2336. };
  2337. var event_target = EventTarget$2;
  2338. var Stream$1 = require$$0__default$1["default"].Stream,
  2339. util$4 = require$$2__default["default"],
  2340. driver$3 = driver$4,
  2341. EventTarget$1 = event_target,
  2342. Event$1 = event;
  2343. var API$3 = function(options) {
  2344. options = options || {};
  2345. driver$3.validateOptions(options, ['headers', 'extensions', 'maxLength', 'ping', 'proxy', 'tls', 'ca']);
  2346. this.readable = this.writable = true;
  2347. var headers = options.headers;
  2348. if (headers) {
  2349. for (var name in headers) this._driver.setHeader(name, headers[name]);
  2350. }
  2351. var extensions = options.extensions;
  2352. if (extensions) {
  2353. [].concat(extensions).forEach(this._driver.addExtension, this._driver);
  2354. }
  2355. this._ping = options.ping;
  2356. this._pingId = 0;
  2357. this.readyState = API$3.CONNECTING;
  2358. this.bufferedAmount = 0;
  2359. this.protocol = '';
  2360. this.url = this._driver.url;
  2361. this.version = this._driver.version;
  2362. var self = this;
  2363. this._driver.on('open', function(e) { self._open(); });
  2364. this._driver.on('message', function(e) { self._receiveMessage(e.data); });
  2365. this._driver.on('close', function(e) { self._beginClose(e.reason, e.code); });
  2366. this._driver.on('error', function(error) {
  2367. self._emitError(error.message);
  2368. });
  2369. this.on('error', function() {});
  2370. this._driver.messages.on('drain', function() {
  2371. self.emit('drain');
  2372. });
  2373. if (this._ping)
  2374. this._pingTimer = setInterval(function() {
  2375. self._pingId += 1;
  2376. self.ping(self._pingId.toString());
  2377. }, this._ping * 1000);
  2378. this._configureStream();
  2379. if (!this._proxy) {
  2380. this._stream.pipe(this._driver.io);
  2381. this._driver.io.pipe(this._stream);
  2382. }
  2383. };
  2384. util$4.inherits(API$3, Stream$1);
  2385. API$3.CONNECTING = 0;
  2386. API$3.OPEN = 1;
  2387. API$3.CLOSING = 2;
  2388. API$3.CLOSED = 3;
  2389. API$3.CLOSE_TIMEOUT = 30000;
  2390. var instance$1 = {
  2391. write: function(data) {
  2392. return this.send(data);
  2393. },
  2394. end: function(data) {
  2395. if (data !== undefined) this.send(data);
  2396. this.close();
  2397. },
  2398. pause: function() {
  2399. return this._driver.messages.pause();
  2400. },
  2401. resume: function() {
  2402. return this._driver.messages.resume();
  2403. },
  2404. send: function(data) {
  2405. if (this.readyState > API$3.OPEN) return false;
  2406. if (!(data instanceof Buffer)) data = String(data);
  2407. return this._driver.messages.write(data);
  2408. },
  2409. ping: function(message, callback) {
  2410. if (this.readyState > API$3.OPEN) return false;
  2411. return this._driver.ping(message, callback);
  2412. },
  2413. close: function(code, reason) {
  2414. if (code === undefined) code = 1000;
  2415. if (reason === undefined) reason = '';
  2416. if (code !== 1000 && (code < 3000 || code > 4999))
  2417. throw new Error("Failed to execute 'close' on WebSocket: " +
  2418. "The code must be either 1000, or between 3000 and 4999. " +
  2419. code + " is neither.");
  2420. if (this.readyState < API$3.CLOSING) {
  2421. var self = this;
  2422. this._closeTimer = setTimeout(function() {
  2423. self._beginClose('', 1006);
  2424. }, API$3.CLOSE_TIMEOUT);
  2425. }
  2426. if (this.readyState !== API$3.CLOSED) this.readyState = API$3.CLOSING;
  2427. this._driver.close(reason, code);
  2428. },
  2429. _configureStream: function() {
  2430. var self = this;
  2431. this._stream.setTimeout(0);
  2432. this._stream.setNoDelay(true);
  2433. ['close', 'end'].forEach(function(event) {
  2434. this._stream.on(event, function() { self._finalizeClose(); });
  2435. }, this);
  2436. this._stream.on('error', function(error) {
  2437. self._emitError('Network error: ' + self.url + ': ' + error.message);
  2438. self._finalizeClose();
  2439. });
  2440. },
  2441. _open: function() {
  2442. if (this.readyState !== API$3.CONNECTING) return;
  2443. this.readyState = API$3.OPEN;
  2444. this.protocol = this._driver.protocol || '';
  2445. var event = new Event$1('open');
  2446. event.initEvent('open', false, false);
  2447. this.dispatchEvent(event);
  2448. },
  2449. _receiveMessage: function(data) {
  2450. if (this.readyState > API$3.OPEN) return false;
  2451. if (this.readable) this.emit('data', data);
  2452. var event = new Event$1('message', { data: data });
  2453. event.initEvent('message', false, false);
  2454. this.dispatchEvent(event);
  2455. },
  2456. _emitError: function(message) {
  2457. if (this.readyState >= API$3.CLOSING) return;
  2458. var event = new Event$1('error', { message: message });
  2459. event.initEvent('error', false, false);
  2460. this.dispatchEvent(event);
  2461. },
  2462. _beginClose: function(reason, code) {
  2463. if (this.readyState === API$3.CLOSED) return;
  2464. this.readyState = API$3.CLOSING;
  2465. this._closeParams = [reason, code];
  2466. if (this._stream) {
  2467. this._stream.destroy();
  2468. if (!this._stream.readable) this._finalizeClose();
  2469. }
  2470. },
  2471. _finalizeClose: function() {
  2472. if (this.readyState === API$3.CLOSED) return;
  2473. this.readyState = API$3.CLOSED;
  2474. if (this._closeTimer) clearTimeout(this._closeTimer);
  2475. if (this._pingTimer) clearInterval(this._pingTimer);
  2476. if (this._stream) this._stream.end();
  2477. if (this.readable) this.emit('end');
  2478. this.readable = this.writable = false;
  2479. var reason = this._closeParams ? this._closeParams[0] : '',
  2480. code = this._closeParams ? this._closeParams[1] : 1006;
  2481. var event = new Event$1('close', { code: code, reason: reason });
  2482. event.initEvent('close', false, false);
  2483. this.dispatchEvent(event);
  2484. }
  2485. };
  2486. for (var method$1 in instance$1) API$3.prototype[method$1] = instance$1[method$1];
  2487. for (var key$1 in EventTarget$1) API$3.prototype[key$1] = EventTarget$1[key$1];
  2488. var api = API$3;
  2489. var util$3 = require$$2__default["default"],
  2490. net = require$$1__default$2["default"],
  2491. tls = require$$2__default$2["default"],
  2492. url = require$$2__default$1["default"],
  2493. driver$2 = driver$4,
  2494. API$2 = api;
  2495. var DEFAULT_PORTS = { 'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443 },
  2496. SECURE_PROTOCOLS = ['https:', 'wss:'];
  2497. var Client = function(_url, protocols, options) {
  2498. options = options || {};
  2499. this.url = _url;
  2500. this._driver = driver$2.client(this.url, { maxLength: options.maxLength, protocols: protocols });
  2501. ['open', 'error'].forEach(function(event) {
  2502. this._driver.on(event, function() {
  2503. self.headers = self._driver.headers;
  2504. self.statusCode = self._driver.statusCode;
  2505. });
  2506. }, this);
  2507. var proxy = options.proxy || {},
  2508. endpoint = url.parse(proxy.origin || this.url),
  2509. port = endpoint.port || DEFAULT_PORTS[endpoint.protocol],
  2510. secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,
  2511. onConnect = function() { self._onConnect(); },
  2512. netOptions = options.net || {},
  2513. originTLS = options.tls || {},
  2514. socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,
  2515. self = this;
  2516. netOptions.host = socketTLS.host = endpoint.hostname;
  2517. netOptions.port = socketTLS.port = port;
  2518. originTLS.ca = originTLS.ca || options.ca;
  2519. socketTLS.servername = socketTLS.servername || endpoint.hostname;
  2520. this._stream = secure
  2521. ? tls.connect(socketTLS, onConnect)
  2522. : net.connect(netOptions, onConnect);
  2523. if (proxy.origin) this._configureProxy(proxy, originTLS);
  2524. API$2.call(this, options);
  2525. };
  2526. util$3.inherits(Client, API$2);
  2527. Client.prototype._onConnect = function() {
  2528. var worker = this._proxy || this._driver;
  2529. worker.start();
  2530. };
  2531. Client.prototype._configureProxy = function(proxy, originTLS) {
  2532. var uri = url.parse(this.url),
  2533. secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,
  2534. self = this,
  2535. name;
  2536. this._proxy = this._driver.proxy(proxy.origin);
  2537. if (proxy.headers) {
  2538. for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);
  2539. }
  2540. this._proxy.pipe(this._stream, { end: false });
  2541. this._stream.pipe(this._proxy);
  2542. this._proxy.on('connect', function() {
  2543. if (secure) {
  2544. var options = { socket: self._stream, servername: uri.hostname };
  2545. for (name in originTLS) options[name] = originTLS[name];
  2546. self._stream = tls.connect(options);
  2547. self._configureStream();
  2548. }
  2549. self._driver.io.pipe(self._stream);
  2550. self._stream.pipe(self._driver.io);
  2551. self._driver.start();
  2552. });
  2553. this._proxy.on('error', function(error) {
  2554. self._driver.emit('error', error);
  2555. });
  2556. };
  2557. var client = Client;
  2558. var Stream = require$$0__default$1["default"].Stream,
  2559. util$2 = require$$2__default["default"],
  2560. driver$1 = driver$4,
  2561. Headers = headers,
  2562. API$1 = api,
  2563. EventTarget = event_target,
  2564. Event = event;
  2565. var EventSource = function(request, response, options) {
  2566. this.writable = true;
  2567. options = options || {};
  2568. this._stream = response.socket;
  2569. this._ping = options.ping || this.DEFAULT_PING;
  2570. this._retry = options.retry || this.DEFAULT_RETRY;
  2571. var scheme = driver$1.isSecureRequest(request) ? 'https:' : 'http:';
  2572. this.url = scheme + '//' + request.headers.host + request.url;
  2573. this.lastEventId = request.headers['last-event-id'] || '';
  2574. this.readyState = API$1.CONNECTING;
  2575. var headers = new Headers(),
  2576. self = this;
  2577. if (options.headers) {
  2578. for (var key in options.headers) headers.set(key, options.headers[key]);
  2579. }
  2580. if (!this._stream || !this._stream.writable) return;
  2581. process.nextTick(function() { self._open(); });
  2582. this._stream.setTimeout(0);
  2583. this._stream.setNoDelay(true);
  2584. var handshake = 'HTTP/1.1 200 OK\r\n' +
  2585. 'Content-Type: text/event-stream\r\n' +
  2586. 'Cache-Control: no-cache, no-store\r\n' +
  2587. 'Connection: close\r\n' +
  2588. headers.toString() +
  2589. '\r\n' +
  2590. 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n';
  2591. this._write(handshake);
  2592. this._stream.on('drain', function() { self.emit('drain'); });
  2593. if (this._ping)
  2594. this._pingTimer = setInterval(function() { self.ping(); }, this._ping * 1000);
  2595. ['error', 'end'].forEach(function(event) {
  2596. self._stream.on(event, function() { self.close(); });
  2597. });
  2598. };
  2599. util$2.inherits(EventSource, Stream);
  2600. EventSource.isEventSource = function(request) {
  2601. if (request.method !== 'GET') return false;
  2602. var accept = (request.headers.accept || '').split(/\s*,\s*/);
  2603. return accept.indexOf('text/event-stream') >= 0;
  2604. };
  2605. var instance = {
  2606. DEFAULT_PING: 10,
  2607. DEFAULT_RETRY: 5,
  2608. _write: function(chunk) {
  2609. if (!this.writable) return false;
  2610. try {
  2611. return this._stream.write(chunk, 'utf8');
  2612. } catch (e) {
  2613. return false;
  2614. }
  2615. },
  2616. _open: function() {
  2617. if (this.readyState !== API$1.CONNECTING) return;
  2618. this.readyState = API$1.OPEN;
  2619. var event = new Event('open');
  2620. event.initEvent('open', false, false);
  2621. this.dispatchEvent(event);
  2622. },
  2623. write: function(message) {
  2624. return this.send(message);
  2625. },
  2626. end: function(message) {
  2627. if (message !== undefined) this.write(message);
  2628. this.close();
  2629. },
  2630. send: function(message, options) {
  2631. if (this.readyState > API$1.OPEN) return false;
  2632. message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: ');
  2633. options = options || {};
  2634. var frame = '';
  2635. if (options.event) frame += 'event: ' + options.event + '\r\n';
  2636. if (options.id) frame += 'id: ' + options.id + '\r\n';
  2637. frame += 'data: ' + message + '\r\n\r\n';
  2638. return this._write(frame);
  2639. },
  2640. ping: function() {
  2641. return this._write(':\r\n\r\n');
  2642. },
  2643. close: function() {
  2644. if (this.readyState > API$1.OPEN) return false;
  2645. this.readyState = API$1.CLOSED;
  2646. this.writable = false;
  2647. if (this._pingTimer) clearInterval(this._pingTimer);
  2648. if (this._stream) this._stream.end();
  2649. var event = new Event('close');
  2650. event.initEvent('close', false, false);
  2651. this.dispatchEvent(event);
  2652. return true;
  2653. }
  2654. };
  2655. for (var method in instance) EventSource.prototype[method] = instance[method];
  2656. for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key];
  2657. var eventsource = EventSource;
  2658. var util$1 = require$$2__default["default"],
  2659. driver = driver$4,
  2660. API = api;
  2661. var WebSocket$1 = function(request, socket, body, protocols, options) {
  2662. options = options || {};
  2663. this._stream = socket;
  2664. this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols });
  2665. var self = this;
  2666. if (!this._stream || !this._stream.writable) return;
  2667. if (!this._stream.readable) return this._stream.end();
  2668. var catchup = function() { self._stream.removeListener('data', catchup); };
  2669. this._stream.on('data', catchup);
  2670. API.call(this, options);
  2671. process.nextTick(function() {
  2672. self._driver.start();
  2673. self._driver.io.write(body);
  2674. });
  2675. };
  2676. util$1.inherits(WebSocket$1, API);
  2677. WebSocket$1.isWebSocket = function(request) {
  2678. return driver.isWebSocket(request);
  2679. };
  2680. WebSocket$1.validateOptions = function(options, validKeys) {
  2681. driver.validateOptions(options, validKeys);
  2682. };
  2683. WebSocket$1.WebSocket = WebSocket$1;
  2684. WebSocket$1.Client = client;
  2685. WebSocket$1.EventSource = eventsource;
  2686. var websocket = WebSocket$1;
  2687. Object.defineProperty(index_standalone, '__esModule', { value: true });
  2688. var Websocket = websocket;
  2689. var util = require$$1__default$3["default"];
  2690. var tslib = require$$2__default$3["default"];
  2691. var logger$1 = require$$3__default["default"];
  2692. function _interopDefaultLegacy$1 (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  2693. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy$1(Websocket);
  2694. /**
  2695. * @license
  2696. * Copyright 2017 Google LLC
  2697. *
  2698. * Licensed under the Apache License, Version 2.0 (the "License");
  2699. * you may not use this file except in compliance with the License.
  2700. * You may obtain a copy of the License at
  2701. *
  2702. * http://www.apache.org/licenses/LICENSE-2.0
  2703. *
  2704. * Unless required by applicable law or agreed to in writing, software
  2705. * distributed under the License is distributed on an "AS IS" BASIS,
  2706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2707. * See the License for the specific language governing permissions and
  2708. * limitations under the License.
  2709. */
  2710. var PROTOCOL_VERSION = '5';
  2711. var VERSION_PARAM = 'v';
  2712. var TRANSPORT_SESSION_PARAM = 's';
  2713. var REFERER_PARAM = 'r';
  2714. var FORGE_REF = 'f';
  2715. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  2716. // firebase.corp.google.com
  2717. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  2718. var LAST_SESSION_PARAM = 'ls';
  2719. var APPLICATION_ID_PARAM = 'p';
  2720. var APP_CHECK_TOKEN_PARAM = 'ac';
  2721. var WEBSOCKET = 'websocket';
  2722. var LONG_POLLING = 'long_polling';
  2723. /**
  2724. * @license
  2725. * Copyright 2017 Google LLC
  2726. *
  2727. * Licensed under the Apache License, Version 2.0 (the "License");
  2728. * you may not use this file except in compliance with the License.
  2729. * You may obtain a copy of the License at
  2730. *
  2731. * http://www.apache.org/licenses/LICENSE-2.0
  2732. *
  2733. * Unless required by applicable law or agreed to in writing, software
  2734. * distributed under the License is distributed on an "AS IS" BASIS,
  2735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2736. * See the License for the specific language governing permissions and
  2737. * limitations under the License.
  2738. */
  2739. /**
  2740. * Wraps a DOM Storage object and:
  2741. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  2742. * - prefixes names with "firebase:" to avoid collisions with app data.
  2743. *
  2744. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  2745. * and one for localStorage.
  2746. *
  2747. */
  2748. var DOMStorageWrapper = /** @class */ (function () {
  2749. /**
  2750. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  2751. */
  2752. function DOMStorageWrapper(domStorage_) {
  2753. this.domStorage_ = domStorage_;
  2754. // Use a prefix to avoid collisions with other stuff saved by the app.
  2755. this.prefix_ = 'firebase:';
  2756. }
  2757. /**
  2758. * @param key - The key to save the value under
  2759. * @param value - The value being stored, or null to remove the key.
  2760. */
  2761. DOMStorageWrapper.prototype.set = function (key, value) {
  2762. if (value == null) {
  2763. this.domStorage_.removeItem(this.prefixedName_(key));
  2764. }
  2765. else {
  2766. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  2767. }
  2768. };
  2769. /**
  2770. * @returns The value that was stored under this key, or null
  2771. */
  2772. DOMStorageWrapper.prototype.get = function (key) {
  2773. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  2774. if (storedVal == null) {
  2775. return null;
  2776. }
  2777. else {
  2778. return util.jsonEval(storedVal);
  2779. }
  2780. };
  2781. DOMStorageWrapper.prototype.remove = function (key) {
  2782. this.domStorage_.removeItem(this.prefixedName_(key));
  2783. };
  2784. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  2785. return this.prefix_ + name;
  2786. };
  2787. DOMStorageWrapper.prototype.toString = function () {
  2788. return this.domStorage_.toString();
  2789. };
  2790. return DOMStorageWrapper;
  2791. }());
  2792. /**
  2793. * @license
  2794. * Copyright 2017 Google LLC
  2795. *
  2796. * Licensed under the Apache License, Version 2.0 (the "License");
  2797. * you may not use this file except in compliance with the License.
  2798. * You may obtain a copy of the License at
  2799. *
  2800. * http://www.apache.org/licenses/LICENSE-2.0
  2801. *
  2802. * Unless required by applicable law or agreed to in writing, software
  2803. * distributed under the License is distributed on an "AS IS" BASIS,
  2804. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2805. * See the License for the specific language governing permissions and
  2806. * limitations under the License.
  2807. */
  2808. /**
  2809. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  2810. * (TODO: create interface for both to implement).
  2811. */
  2812. var MemoryStorage = /** @class */ (function () {
  2813. function MemoryStorage() {
  2814. this.cache_ = {};
  2815. this.isInMemoryStorage = true;
  2816. }
  2817. MemoryStorage.prototype.set = function (key, value) {
  2818. if (value == null) {
  2819. delete this.cache_[key];
  2820. }
  2821. else {
  2822. this.cache_[key] = value;
  2823. }
  2824. };
  2825. MemoryStorage.prototype.get = function (key) {
  2826. if (util.contains(this.cache_, key)) {
  2827. return this.cache_[key];
  2828. }
  2829. return null;
  2830. };
  2831. MemoryStorage.prototype.remove = function (key) {
  2832. delete this.cache_[key];
  2833. };
  2834. return MemoryStorage;
  2835. }());
  2836. /**
  2837. * @license
  2838. * Copyright 2017 Google LLC
  2839. *
  2840. * Licensed under the Apache License, Version 2.0 (the "License");
  2841. * you may not use this file except in compliance with the License.
  2842. * You may obtain a copy of the License at
  2843. *
  2844. * http://www.apache.org/licenses/LICENSE-2.0
  2845. *
  2846. * Unless required by applicable law or agreed to in writing, software
  2847. * distributed under the License is distributed on an "AS IS" BASIS,
  2848. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2849. * See the License for the specific language governing permissions and
  2850. * limitations under the License.
  2851. */
  2852. /**
  2853. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  2854. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  2855. * to reflect this type
  2856. *
  2857. * @param domStorageName - Name of the underlying storage object
  2858. * (e.g. 'localStorage' or 'sessionStorage').
  2859. * @returns Turning off type information until a common interface is defined.
  2860. */
  2861. var createStoragefor = function (domStorageName) {
  2862. try {
  2863. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  2864. // so it must be inside the try/catch.
  2865. if (typeof window !== 'undefined' &&
  2866. typeof window[domStorageName] !== 'undefined') {
  2867. // Need to test cache. Just because it's here doesn't mean it works
  2868. var domStorage = window[domStorageName];
  2869. domStorage.setItem('firebase:sentinel', 'cache');
  2870. domStorage.removeItem('firebase:sentinel');
  2871. return new DOMStorageWrapper(domStorage);
  2872. }
  2873. }
  2874. catch (e) { }
  2875. // Failed to create wrapper. Just return in-memory storage.
  2876. // TODO: log?
  2877. return new MemoryStorage();
  2878. };
  2879. /** A storage object that lasts across sessions */
  2880. var PersistentStorage = createStoragefor('localStorage');
  2881. /** A storage object that only lasts one session */
  2882. var SessionStorage = createStoragefor('sessionStorage');
  2883. /**
  2884. * @license
  2885. * Copyright 2017 Google LLC
  2886. *
  2887. * Licensed under the Apache License, Version 2.0 (the "License");
  2888. * you may not use this file except in compliance with the License.
  2889. * You may obtain a copy of the License at
  2890. *
  2891. * http://www.apache.org/licenses/LICENSE-2.0
  2892. *
  2893. * Unless required by applicable law or agreed to in writing, software
  2894. * distributed under the License is distributed on an "AS IS" BASIS,
  2895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2896. * See the License for the specific language governing permissions and
  2897. * limitations under the License.
  2898. */
  2899. var logClient$1 = new logger$1.Logger('@firebase/database');
  2900. /**
  2901. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  2902. */
  2903. var LUIDGenerator = (function () {
  2904. var id = 1;
  2905. return function () {
  2906. return id++;
  2907. };
  2908. })();
  2909. /**
  2910. * Sha1 hash of the input string
  2911. * @param str - The string to hash
  2912. * @returns {!string} The resulting hash
  2913. */
  2914. var sha1 = function (str) {
  2915. var utf8Bytes = util.stringToByteArray(str);
  2916. var sha1 = new util.Sha1();
  2917. sha1.update(utf8Bytes);
  2918. var sha1Bytes = sha1.digest();
  2919. return util.base64.encodeByteArray(sha1Bytes);
  2920. };
  2921. var buildLogMessage_ = function () {
  2922. var varArgs = [];
  2923. for (var _i = 0; _i < arguments.length; _i++) {
  2924. varArgs[_i] = arguments[_i];
  2925. }
  2926. var message = '';
  2927. for (var i = 0; i < varArgs.length; i++) {
  2928. var arg = varArgs[i];
  2929. if (Array.isArray(arg) ||
  2930. (arg &&
  2931. typeof arg === 'object' &&
  2932. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2933. typeof arg.length === 'number')) {
  2934. message += buildLogMessage_.apply(null, arg);
  2935. }
  2936. else if (typeof arg === 'object') {
  2937. message += util.stringify(arg);
  2938. }
  2939. else {
  2940. message += arg;
  2941. }
  2942. message += ' ';
  2943. }
  2944. return message;
  2945. };
  2946. /**
  2947. * Use this for all debug messages in Firebase.
  2948. */
  2949. var logger = null;
  2950. /**
  2951. * Flag to check for log availability on first log message
  2952. */
  2953. var firstLog_ = true;
  2954. /**
  2955. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  2956. * @param logger_ - A flag to turn on logging, or a custom logger
  2957. * @param persistent - Whether or not to persist logging settings across refreshes
  2958. */
  2959. var enableLogging$1 = function (logger_, persistent) {
  2960. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  2961. if (logger_ === true) {
  2962. logClient$1.logLevel = logger$1.LogLevel.VERBOSE;
  2963. logger = logClient$1.log.bind(logClient$1);
  2964. if (persistent) {
  2965. SessionStorage.set('logging_enabled', true);
  2966. }
  2967. }
  2968. else if (typeof logger_ === 'function') {
  2969. logger = logger_;
  2970. }
  2971. else {
  2972. logger = null;
  2973. SessionStorage.remove('logging_enabled');
  2974. }
  2975. };
  2976. var log = function () {
  2977. var varArgs = [];
  2978. for (var _i = 0; _i < arguments.length; _i++) {
  2979. varArgs[_i] = arguments[_i];
  2980. }
  2981. if (firstLog_ === true) {
  2982. firstLog_ = false;
  2983. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  2984. enableLogging$1(true);
  2985. }
  2986. }
  2987. if (logger) {
  2988. var message = buildLogMessage_.apply(null, varArgs);
  2989. logger(message);
  2990. }
  2991. };
  2992. var logWrapper = function (prefix) {
  2993. return function () {
  2994. var varArgs = [];
  2995. for (var _i = 0; _i < arguments.length; _i++) {
  2996. varArgs[_i] = arguments[_i];
  2997. }
  2998. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  2999. };
  3000. };
  3001. var error = function () {
  3002. var varArgs = [];
  3003. for (var _i = 0; _i < arguments.length; _i++) {
  3004. varArgs[_i] = arguments[_i];
  3005. }
  3006. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  3007. logClient$1.error(message);
  3008. };
  3009. var fatal = function () {
  3010. var varArgs = [];
  3011. for (var _i = 0; _i < arguments.length; _i++) {
  3012. varArgs[_i] = arguments[_i];
  3013. }
  3014. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
  3015. logClient$1.error(message);
  3016. throw new Error(message);
  3017. };
  3018. var warn$1 = function () {
  3019. var varArgs = [];
  3020. for (var _i = 0; _i < arguments.length; _i++) {
  3021. varArgs[_i] = arguments[_i];
  3022. }
  3023. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  3024. logClient$1.warn(message);
  3025. };
  3026. /**
  3027. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  3028. * does not use https.
  3029. */
  3030. var warnIfPageIsSecure = function () {
  3031. // Be very careful accessing browser globals. Who knows what may or may not exist.
  3032. if (typeof window !== 'undefined' &&
  3033. window.location &&
  3034. window.location.protocol &&
  3035. window.location.protocol.indexOf('https:') !== -1) {
  3036. warn$1('Insecure Firebase access from a secure page. ' +
  3037. 'Please use https in calls to new Firebase().');
  3038. }
  3039. };
  3040. /**
  3041. * Returns true if data is NaN, or +/- Infinity.
  3042. */
  3043. var isInvalidJSONNumber = function (data) {
  3044. return (typeof data === 'number' &&
  3045. (data !== data || // NaN
  3046. data === Number.POSITIVE_INFINITY ||
  3047. data === Number.NEGATIVE_INFINITY));
  3048. };
  3049. var executeWhenDOMReady = function (fn) {
  3050. if (util.isNodeSdk() || document.readyState === 'complete') {
  3051. fn();
  3052. }
  3053. else {
  3054. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  3055. // fire before onload), but fall back to onload.
  3056. var called_1 = false;
  3057. var wrappedFn_1 = function () {
  3058. if (!document.body) {
  3059. setTimeout(wrappedFn_1, Math.floor(10));
  3060. return;
  3061. }
  3062. if (!called_1) {
  3063. called_1 = true;
  3064. fn();
  3065. }
  3066. };
  3067. if (document.addEventListener) {
  3068. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  3069. // fallback to onload.
  3070. window.addEventListener('load', wrappedFn_1, false);
  3071. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3072. }
  3073. else if (document.attachEvent) {
  3074. // IE.
  3075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3076. document.attachEvent('onreadystatechange', function () {
  3077. if (document.readyState === 'complete') {
  3078. wrappedFn_1();
  3079. }
  3080. });
  3081. // fallback to onload.
  3082. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3083. window.attachEvent('onload', wrappedFn_1);
  3084. // jQuery has an extra hack for IE that we could employ (based on
  3085. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  3086. // I'm hoping we don't need it.
  3087. }
  3088. }
  3089. };
  3090. /**
  3091. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  3092. */
  3093. var MIN_NAME = '[MIN_NAME]';
  3094. /**
  3095. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  3096. */
  3097. var MAX_NAME = '[MAX_NAME]';
  3098. /**
  3099. * Compares valid Firebase key names, plus min and max name
  3100. */
  3101. var nameCompare = function (a, b) {
  3102. if (a === b) {
  3103. return 0;
  3104. }
  3105. else if (a === MIN_NAME || b === MAX_NAME) {
  3106. return -1;
  3107. }
  3108. else if (b === MIN_NAME || a === MAX_NAME) {
  3109. return 1;
  3110. }
  3111. else {
  3112. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  3113. if (aAsInt !== null) {
  3114. if (bAsInt !== null) {
  3115. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  3116. }
  3117. else {
  3118. return -1;
  3119. }
  3120. }
  3121. else if (bAsInt !== null) {
  3122. return 1;
  3123. }
  3124. else {
  3125. return a < b ? -1 : 1;
  3126. }
  3127. }
  3128. };
  3129. /**
  3130. * @returns {!number} comparison result.
  3131. */
  3132. var stringCompare = function (a, b) {
  3133. if (a === b) {
  3134. return 0;
  3135. }
  3136. else if (a < b) {
  3137. return -1;
  3138. }
  3139. else {
  3140. return 1;
  3141. }
  3142. };
  3143. var requireKey = function (key, obj) {
  3144. if (obj && key in obj) {
  3145. return obj[key];
  3146. }
  3147. else {
  3148. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  3149. }
  3150. };
  3151. var ObjectToUniqueKey = function (obj) {
  3152. if (typeof obj !== 'object' || obj === null) {
  3153. return util.stringify(obj);
  3154. }
  3155. var keys = [];
  3156. // eslint-disable-next-line guard-for-in
  3157. for (var k in obj) {
  3158. keys.push(k);
  3159. }
  3160. // Export as json, but with the keys sorted.
  3161. keys.sort();
  3162. var key = '{';
  3163. for (var i = 0; i < keys.length; i++) {
  3164. if (i !== 0) {
  3165. key += ',';
  3166. }
  3167. key += util.stringify(keys[i]);
  3168. key += ':';
  3169. key += ObjectToUniqueKey(obj[keys[i]]);
  3170. }
  3171. key += '}';
  3172. return key;
  3173. };
  3174. /**
  3175. * Splits a string into a number of smaller segments of maximum size
  3176. * @param str - The string
  3177. * @param segsize - The maximum number of chars in the string.
  3178. * @returns The string, split into appropriately-sized chunks
  3179. */
  3180. var splitStringBySize = function (str, segsize) {
  3181. var len = str.length;
  3182. if (len <= segsize) {
  3183. return [str];
  3184. }
  3185. var dataSegs = [];
  3186. for (var c = 0; c < len; c += segsize) {
  3187. if (c + segsize > len) {
  3188. dataSegs.push(str.substring(c, len));
  3189. }
  3190. else {
  3191. dataSegs.push(str.substring(c, c + segsize));
  3192. }
  3193. }
  3194. return dataSegs;
  3195. };
  3196. /**
  3197. * Apply a function to each (key, value) pair in an object or
  3198. * apply a function to each (index, value) pair in an array
  3199. * @param obj - The object or array to iterate over
  3200. * @param fn - The function to apply
  3201. */
  3202. function each(obj, fn) {
  3203. for (var key in obj) {
  3204. if (obj.hasOwnProperty(key)) {
  3205. fn(key, obj[key]);
  3206. }
  3207. }
  3208. }
  3209. /**
  3210. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  3211. * I made one modification at the end and removed the NaN / Infinity
  3212. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  3213. * @param v - A double
  3214. *
  3215. */
  3216. var doubleToIEEE754String = function (v) {
  3217. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  3218. var ebits = 11, fbits = 52;
  3219. var bias = (1 << (ebits - 1)) - 1;
  3220. var s, e, f, ln, i;
  3221. // Compute sign, exponent, fraction
  3222. // Skip NaN / Infinity handling --MJL.
  3223. if (v === 0) {
  3224. e = 0;
  3225. f = 0;
  3226. s = 1 / v === -Infinity ? 1 : 0;
  3227. }
  3228. else {
  3229. s = v < 0;
  3230. v = Math.abs(v);
  3231. if (v >= Math.pow(2, 1 - bias)) {
  3232. // Normalized
  3233. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  3234. e = ln + bias;
  3235. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  3236. }
  3237. else {
  3238. // Denormalized
  3239. e = 0;
  3240. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  3241. }
  3242. }
  3243. // Pack sign, exponent, fraction
  3244. var bits = [];
  3245. for (i = fbits; i; i -= 1) {
  3246. bits.push(f % 2 ? 1 : 0);
  3247. f = Math.floor(f / 2);
  3248. }
  3249. for (i = ebits; i; i -= 1) {
  3250. bits.push(e % 2 ? 1 : 0);
  3251. e = Math.floor(e / 2);
  3252. }
  3253. bits.push(s ? 1 : 0);
  3254. bits.reverse();
  3255. var str = bits.join('');
  3256. // Return the data as a hex string. --MJL
  3257. var hexByteString = '';
  3258. for (i = 0; i < 64; i += 8) {
  3259. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  3260. if (hexByte.length === 1) {
  3261. hexByte = '0' + hexByte;
  3262. }
  3263. hexByteString = hexByteString + hexByte;
  3264. }
  3265. return hexByteString.toLowerCase();
  3266. };
  3267. /**
  3268. * Used to detect if we're in a Chrome content script (which executes in an
  3269. * isolated environment where long-polling doesn't work).
  3270. */
  3271. var isChromeExtensionContentScript = function () {
  3272. return !!(typeof window === 'object' &&
  3273. window['chrome'] &&
  3274. window['chrome']['extension'] &&
  3275. !/^chrome/.test(window.location.href));
  3276. };
  3277. /**
  3278. * Used to detect if we're in a Windows 8 Store app.
  3279. */
  3280. var isWindowsStoreApp = function () {
  3281. // Check for the presence of a couple WinRT globals
  3282. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  3283. };
  3284. /**
  3285. * Converts a server error code to a Javascript Error
  3286. */
  3287. function errorForServerCode(code, query) {
  3288. var reason = 'Unknown Error';
  3289. if (code === 'too_big') {
  3290. reason =
  3291. 'The data requested exceeds the maximum size ' +
  3292. 'that can be accessed with a single request.';
  3293. }
  3294. else if (code === 'permission_denied') {
  3295. reason = "Client doesn't have permission to access the desired data.";
  3296. }
  3297. else if (code === 'unavailable') {
  3298. reason = 'The service is unavailable';
  3299. }
  3300. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  3301. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3302. error.code = code.toUpperCase();
  3303. return error;
  3304. }
  3305. /**
  3306. * Used to test for integer-looking strings
  3307. */
  3308. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  3309. /**
  3310. * For use in keys, the minimum possible 32-bit integer.
  3311. */
  3312. var INTEGER_32_MIN = -2147483648;
  3313. /**
  3314. * For use in kyes, the maximum possible 32-bit integer.
  3315. */
  3316. var INTEGER_32_MAX = 2147483647;
  3317. /**
  3318. * If the string contains a 32-bit integer, return it. Else return null.
  3319. */
  3320. var tryParseInt = function (str) {
  3321. if (INTEGER_REGEXP_.test(str)) {
  3322. var intVal = Number(str);
  3323. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  3324. return intVal;
  3325. }
  3326. }
  3327. return null;
  3328. };
  3329. /**
  3330. * Helper to run some code but catch any exceptions and re-throw them later.
  3331. * Useful for preventing user callbacks from breaking internal code.
  3332. *
  3333. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  3334. * convenient (we don't have to try to figure out when is a safe point to
  3335. * re-throw it), and the behavior seems reasonable:
  3336. *
  3337. * * If you aren't pausing on exceptions, you get an error in the console with
  3338. * the correct stack trace.
  3339. * * If you're pausing on all exceptions, the debugger will pause on your
  3340. * exception and then again when we rethrow it.
  3341. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  3342. * on us re-throwing it.
  3343. *
  3344. * @param fn - The code to guard.
  3345. */
  3346. var exceptionGuard = function (fn) {
  3347. try {
  3348. fn();
  3349. }
  3350. catch (e) {
  3351. // Re-throw exception when it's safe.
  3352. setTimeout(function () {
  3353. // It used to be that "throw e" would result in a good console error with
  3354. // relevant context, but as of Chrome 39, you just get the firebase.js
  3355. // file/line number where we re-throw it, which is useless. So we log
  3356. // e.stack explicitly.
  3357. var stack = e.stack || '';
  3358. warn$1('Exception was thrown by user callback.', stack);
  3359. throw e;
  3360. }, Math.floor(0));
  3361. }
  3362. };
  3363. /**
  3364. * @returns {boolean} true if we think we're currently being crawled.
  3365. */
  3366. var beingCrawled = function () {
  3367. var userAgent = (typeof window === 'object' &&
  3368. window['navigator'] &&
  3369. window['navigator']['userAgent']) ||
  3370. '';
  3371. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  3372. // believe to support JavaScript/AJAX rendering.
  3373. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  3374. // would have seen the page" is flaky if we don't treat it as a crawler.
  3375. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  3376. };
  3377. /**
  3378. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  3379. *
  3380. * It is removed with clearTimeout() as normal.
  3381. *
  3382. * @param fn - Function to run.
  3383. * @param time - Milliseconds to wait before running.
  3384. * @returns The setTimeout() return value.
  3385. */
  3386. var setTimeoutNonBlocking = function (fn, time) {
  3387. var timeout = setTimeout(fn, time);
  3388. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  3389. if (typeof timeout === 'number' &&
  3390. // @ts-ignore Is only defined in Deno environments.
  3391. typeof Deno !== 'undefined' &&
  3392. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  3393. Deno['unrefTimer']) {
  3394. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  3395. Deno.unrefTimer(timeout);
  3396. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3397. }
  3398. else if (typeof timeout === 'object' && timeout['unref']) {
  3399. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3400. timeout['unref']();
  3401. }
  3402. return timeout;
  3403. };
  3404. /**
  3405. * @license
  3406. * Copyright 2017 Google LLC
  3407. *
  3408. * Licensed under the Apache License, Version 2.0 (the "License");
  3409. * you may not use this file except in compliance with the License.
  3410. * You may obtain a copy of the License at
  3411. *
  3412. * http://www.apache.org/licenses/LICENSE-2.0
  3413. *
  3414. * Unless required by applicable law or agreed to in writing, software
  3415. * distributed under the License is distributed on an "AS IS" BASIS,
  3416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3417. * See the License for the specific language governing permissions and
  3418. * limitations under the License.
  3419. */
  3420. /**
  3421. * A class that holds metadata about a Repo object
  3422. */
  3423. var RepoInfo = /** @class */ (function () {
  3424. /**
  3425. * @param host - Hostname portion of the url for the repo
  3426. * @param secure - Whether or not this repo is accessed over ssl
  3427. * @param namespace - The namespace represented by the repo
  3428. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  3429. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  3430. * @param persistenceKey - Override the default session persistence storage key
  3431. */
  3432. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) {
  3433. if (nodeAdmin === void 0) { nodeAdmin = false; }
  3434. if (persistenceKey === void 0) { persistenceKey = ''; }
  3435. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  3436. this.secure = secure;
  3437. this.namespace = namespace;
  3438. this.webSocketOnly = webSocketOnly;
  3439. this.nodeAdmin = nodeAdmin;
  3440. this.persistenceKey = persistenceKey;
  3441. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  3442. this._host = host.toLowerCase();
  3443. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  3444. this.internalHost =
  3445. PersistentStorage.get('host:' + host) || this._host;
  3446. }
  3447. RepoInfo.prototype.isCacheableHost = function () {
  3448. return this.internalHost.substr(0, 2) === 's-';
  3449. };
  3450. RepoInfo.prototype.isCustomHost = function () {
  3451. return (this._domain !== 'firebaseio.com' &&
  3452. this._domain !== 'firebaseio-demo.com');
  3453. };
  3454. Object.defineProperty(RepoInfo.prototype, "host", {
  3455. get: function () {
  3456. return this._host;
  3457. },
  3458. set: function (newHost) {
  3459. if (newHost !== this.internalHost) {
  3460. this.internalHost = newHost;
  3461. if (this.isCacheableHost()) {
  3462. PersistentStorage.set('host:' + this._host, this.internalHost);
  3463. }
  3464. }
  3465. },
  3466. enumerable: false,
  3467. configurable: true
  3468. });
  3469. RepoInfo.prototype.toString = function () {
  3470. var str = this.toURLString();
  3471. if (this.persistenceKey) {
  3472. str += '<' + this.persistenceKey + '>';
  3473. }
  3474. return str;
  3475. };
  3476. RepoInfo.prototype.toURLString = function () {
  3477. var protocol = this.secure ? 'https://' : 'http://';
  3478. var query = this.includeNamespaceInQueryParams
  3479. ? "?ns=".concat(this.namespace)
  3480. : '';
  3481. return "".concat(protocol).concat(this.host, "/").concat(query);
  3482. };
  3483. return RepoInfo;
  3484. }());
  3485. function repoInfoNeedsQueryParam(repoInfo) {
  3486. return (repoInfo.host !== repoInfo.internalHost ||
  3487. repoInfo.isCustomHost() ||
  3488. repoInfo.includeNamespaceInQueryParams);
  3489. }
  3490. /**
  3491. * Returns the websocket URL for this repo
  3492. * @param repoInfo - RepoInfo object
  3493. * @param type - of connection
  3494. * @param params - list
  3495. * @returns The URL for this repo
  3496. */
  3497. function repoInfoConnectionURL(repoInfo, type, params) {
  3498. util.assert(typeof type === 'string', 'typeof type must == string');
  3499. util.assert(typeof params === 'object', 'typeof params must == object');
  3500. var connURL;
  3501. if (type === WEBSOCKET) {
  3502. connURL =
  3503. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  3504. }
  3505. else if (type === LONG_POLLING) {
  3506. connURL =
  3507. (repoInfo.secure ? 'https://' : 'http://') +
  3508. repoInfo.internalHost +
  3509. '/.lp?';
  3510. }
  3511. else {
  3512. throw new Error('Unknown connection type: ' + type);
  3513. }
  3514. if (repoInfoNeedsQueryParam(repoInfo)) {
  3515. params['ns'] = repoInfo.namespace;
  3516. }
  3517. var pairs = [];
  3518. each(params, function (key, value) {
  3519. pairs.push(key + '=' + value);
  3520. });
  3521. return connURL + pairs.join('&');
  3522. }
  3523. /**
  3524. * @license
  3525. * Copyright 2017 Google LLC
  3526. *
  3527. * Licensed under the Apache License, Version 2.0 (the "License");
  3528. * you may not use this file except in compliance with the License.
  3529. * You may obtain a copy of the License at
  3530. *
  3531. * http://www.apache.org/licenses/LICENSE-2.0
  3532. *
  3533. * Unless required by applicable law or agreed to in writing, software
  3534. * distributed under the License is distributed on an "AS IS" BASIS,
  3535. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3536. * See the License for the specific language governing permissions and
  3537. * limitations under the License.
  3538. */
  3539. /**
  3540. * Tracks a collection of stats.
  3541. */
  3542. var StatsCollection = /** @class */ (function () {
  3543. function StatsCollection() {
  3544. this.counters_ = {};
  3545. }
  3546. StatsCollection.prototype.incrementCounter = function (name, amount) {
  3547. if (amount === void 0) { amount = 1; }
  3548. if (!util.contains(this.counters_, name)) {
  3549. this.counters_[name] = 0;
  3550. }
  3551. this.counters_[name] += amount;
  3552. };
  3553. StatsCollection.prototype.get = function () {
  3554. return util.deepCopy(this.counters_);
  3555. };
  3556. return StatsCollection;
  3557. }());
  3558. /**
  3559. * @license
  3560. * Copyright 2017 Google LLC
  3561. *
  3562. * Licensed under the Apache License, Version 2.0 (the "License");
  3563. * you may not use this file except in compliance with the License.
  3564. * You may obtain a copy of the License at
  3565. *
  3566. * http://www.apache.org/licenses/LICENSE-2.0
  3567. *
  3568. * Unless required by applicable law or agreed to in writing, software
  3569. * distributed under the License is distributed on an "AS IS" BASIS,
  3570. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3571. * See the License for the specific language governing permissions and
  3572. * limitations under the License.
  3573. */
  3574. var collections = {};
  3575. var reporters = {};
  3576. function statsManagerGetCollection(repoInfo) {
  3577. var hashString = repoInfo.toString();
  3578. if (!collections[hashString]) {
  3579. collections[hashString] = new StatsCollection();
  3580. }
  3581. return collections[hashString];
  3582. }
  3583. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  3584. var hashString = repoInfo.toString();
  3585. if (!reporters[hashString]) {
  3586. reporters[hashString] = creatorFunction();
  3587. }
  3588. return reporters[hashString];
  3589. }
  3590. /**
  3591. * @license
  3592. * Copyright 2019 Google LLC
  3593. *
  3594. * Licensed under the Apache License, Version 2.0 (the "License");
  3595. * you may not use this file except in compliance with the License.
  3596. * You may obtain a copy of the License at
  3597. *
  3598. * http://www.apache.org/licenses/LICENSE-2.0
  3599. *
  3600. * Unless required by applicable law or agreed to in writing, software
  3601. * distributed under the License is distributed on an "AS IS" BASIS,
  3602. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3603. * See the License for the specific language governing permissions and
  3604. * limitations under the License.
  3605. */
  3606. /** The semver (www.semver.org) version of the SDK. */
  3607. var SDK_VERSION = '';
  3608. /**
  3609. * SDK_VERSION should be set before any database instance is created
  3610. * @internal
  3611. */
  3612. function setSDKVersion(version) {
  3613. SDK_VERSION = version;
  3614. }
  3615. /**
  3616. * @license
  3617. * Copyright 2017 Google LLC
  3618. *
  3619. * Licensed under the Apache License, Version 2.0 (the "License");
  3620. * you may not use this file except in compliance with the License.
  3621. * You may obtain a copy of the License at
  3622. *
  3623. * http://www.apache.org/licenses/LICENSE-2.0
  3624. *
  3625. * Unless required by applicable law or agreed to in writing, software
  3626. * distributed under the License is distributed on an "AS IS" BASIS,
  3627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3628. * See the License for the specific language governing permissions and
  3629. * limitations under the License.
  3630. */
  3631. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  3632. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  3633. var WebSocketImpl = null;
  3634. if (typeof MozWebSocket !== 'undefined') {
  3635. WebSocketImpl = MozWebSocket;
  3636. }
  3637. else if (typeof WebSocket !== 'undefined') {
  3638. WebSocketImpl = WebSocket;
  3639. }
  3640. function setWebSocketImpl(impl) {
  3641. WebSocketImpl = impl;
  3642. }
  3643. /**
  3644. * Create a new websocket connection with the given callbacks.
  3645. */
  3646. var WebSocketConnection = /** @class */ (function () {
  3647. /**
  3648. * @param connId identifier for this transport
  3649. * @param repoInfo The info for the websocket endpoint.
  3650. * @param applicationId The Firebase App ID for this project.
  3651. * @param appCheckToken The App Check Token for this client.
  3652. * @param authToken The Auth Token for this client.
  3653. * @param transportSessionId Optional transportSessionId if this is connecting
  3654. * to an existing transport session
  3655. * @param lastSessionId Optional lastSessionId if there was a previous
  3656. * connection
  3657. */
  3658. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  3659. this.connId = connId;
  3660. this.applicationId = applicationId;
  3661. this.appCheckToken = appCheckToken;
  3662. this.authToken = authToken;
  3663. this.keepaliveTimer = null;
  3664. this.frames = null;
  3665. this.totalFrames = 0;
  3666. this.bytesSent = 0;
  3667. this.bytesReceived = 0;
  3668. this.log_ = logWrapper(this.connId);
  3669. this.stats_ = statsManagerGetCollection(repoInfo);
  3670. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  3671. this.nodeAdmin = repoInfo.nodeAdmin;
  3672. }
  3673. /**
  3674. * @param repoInfo - The info for the websocket endpoint.
  3675. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  3676. * session
  3677. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  3678. * @returns connection url
  3679. */
  3680. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  3681. var urlParams = {};
  3682. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  3683. if (!util.isNodeSdk() &&
  3684. typeof location !== 'undefined' &&
  3685. location.hostname &&
  3686. FORGE_DOMAIN_RE.test(location.hostname)) {
  3687. urlParams[REFERER_PARAM] = FORGE_REF;
  3688. }
  3689. if (transportSessionId) {
  3690. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  3691. }
  3692. if (lastSessionId) {
  3693. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  3694. }
  3695. if (appCheckToken) {
  3696. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  3697. }
  3698. if (applicationId) {
  3699. urlParams[APPLICATION_ID_PARAM] = applicationId;
  3700. }
  3701. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  3702. };
  3703. /**
  3704. * @param onMessage - Callback when messages arrive
  3705. * @param onDisconnect - Callback with connection lost.
  3706. */
  3707. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  3708. var _this = this;
  3709. this.onDisconnect = onDisconnect;
  3710. this.onMessage = onMessage;
  3711. this.log_('Websocket connecting to ' + this.connURL);
  3712. this.everConnected_ = false;
  3713. // Assume failure until proven otherwise.
  3714. PersistentStorage.set('previous_websocket_failure', true);
  3715. try {
  3716. var options = void 0;
  3717. if (util.isNodeSdk()) {
  3718. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  3719. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  3720. options = {
  3721. headers: {
  3722. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  3723. 'X-Firebase-GMPID': this.applicationId || ''
  3724. }
  3725. };
  3726. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  3727. // Note that we send the credentials here even if they aren't admin credentials, which is
  3728. // not a problem.
  3729. // Note that this header is just used to bypass appcheck, and the token should still be sent
  3730. // through the websocket connection once it is established.
  3731. if (this.authToken) {
  3732. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  3733. }
  3734. if (this.appCheckToken) {
  3735. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  3736. }
  3737. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  3738. var env = process['env'];
  3739. var proxy = this.connURL.indexOf('wss://') === 0
  3740. ? env['HTTPS_PROXY'] || env['https_proxy']
  3741. : env['HTTP_PROXY'] || env['http_proxy'];
  3742. if (proxy) {
  3743. options['proxy'] = { origin: proxy };
  3744. }
  3745. }
  3746. this.mySock = new WebSocketImpl(this.connURL, [], options);
  3747. }
  3748. catch (e) {
  3749. this.log_('Error instantiating WebSocket.');
  3750. var error = e.message || e.data;
  3751. if (error) {
  3752. this.log_(error);
  3753. }
  3754. this.onClosed_();
  3755. return;
  3756. }
  3757. this.mySock.onopen = function () {
  3758. _this.log_('Websocket connected.');
  3759. _this.everConnected_ = true;
  3760. };
  3761. this.mySock.onclose = function () {
  3762. _this.log_('Websocket connection was disconnected.');
  3763. _this.mySock = null;
  3764. _this.onClosed_();
  3765. };
  3766. this.mySock.onmessage = function (m) {
  3767. _this.handleIncomingFrame(m);
  3768. };
  3769. this.mySock.onerror = function (e) {
  3770. _this.log_('WebSocket error. Closing connection.');
  3771. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3772. var error = e.message || e.data;
  3773. if (error) {
  3774. _this.log_(error);
  3775. }
  3776. _this.onClosed_();
  3777. };
  3778. };
  3779. /**
  3780. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  3781. */
  3782. WebSocketConnection.prototype.start = function () { };
  3783. WebSocketConnection.forceDisallow = function () {
  3784. WebSocketConnection.forceDisallow_ = true;
  3785. };
  3786. WebSocketConnection.isAvailable = function () {
  3787. var isOldAndroid = false;
  3788. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  3789. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  3790. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  3791. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  3792. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  3793. isOldAndroid = true;
  3794. }
  3795. }
  3796. }
  3797. return (!isOldAndroid &&
  3798. WebSocketImpl !== null &&
  3799. !WebSocketConnection.forceDisallow_);
  3800. };
  3801. /**
  3802. * Returns true if we previously failed to connect with this transport.
  3803. */
  3804. WebSocketConnection.previouslyFailed = function () {
  3805. // If our persistent storage is actually only in-memory storage,
  3806. // we default to assuming that it previously failed to be safe.
  3807. return (PersistentStorage.isInMemoryStorage ||
  3808. PersistentStorage.get('previous_websocket_failure') === true);
  3809. };
  3810. WebSocketConnection.prototype.markConnectionHealthy = function () {
  3811. PersistentStorage.remove('previous_websocket_failure');
  3812. };
  3813. WebSocketConnection.prototype.appendFrame_ = function (data) {
  3814. this.frames.push(data);
  3815. if (this.frames.length === this.totalFrames) {
  3816. var fullMess = this.frames.join('');
  3817. this.frames = null;
  3818. var jsonMess = util.jsonEval(fullMess);
  3819. //handle the message
  3820. this.onMessage(jsonMess);
  3821. }
  3822. };
  3823. /**
  3824. * @param frameCount - The number of frames we are expecting from the server
  3825. */
  3826. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  3827. this.totalFrames = frameCount;
  3828. this.frames = [];
  3829. };
  3830. /**
  3831. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  3832. * @returns Any remaining data to be process, or null if there is none
  3833. */
  3834. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  3835. util.assert(this.frames === null, 'We already have a frame buffer');
  3836. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  3837. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  3838. if (data.length <= 6) {
  3839. var frameCount = Number(data);
  3840. if (!isNaN(frameCount)) {
  3841. this.handleNewFrameCount_(frameCount);
  3842. return null;
  3843. }
  3844. }
  3845. this.handleNewFrameCount_(1);
  3846. return data;
  3847. };
  3848. /**
  3849. * Process a websocket frame that has arrived from the server.
  3850. * @param mess - The frame data
  3851. */
  3852. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  3853. if (this.mySock === null) {
  3854. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  3855. }
  3856. var data = mess['data'];
  3857. this.bytesReceived += data.length;
  3858. this.stats_.incrementCounter('bytes_received', data.length);
  3859. this.resetKeepAlive();
  3860. if (this.frames !== null) {
  3861. // we're buffering
  3862. this.appendFrame_(data);
  3863. }
  3864. else {
  3865. // try to parse out a frame count, otherwise, assume 1 and process it
  3866. var remainingData = this.extractFrameCount_(data);
  3867. if (remainingData !== null) {
  3868. this.appendFrame_(remainingData);
  3869. }
  3870. }
  3871. };
  3872. /**
  3873. * Send a message to the server
  3874. * @param data - The JSON object to transmit
  3875. */
  3876. WebSocketConnection.prototype.send = function (data) {
  3877. this.resetKeepAlive();
  3878. var dataStr = util.stringify(data);
  3879. this.bytesSent += dataStr.length;
  3880. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  3881. //We can only fit a certain amount in each websocket frame, so we need to split this request
  3882. //up into multiple pieces if it doesn't fit in one request.
  3883. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  3884. //Send the length header
  3885. if (dataSegs.length > 1) {
  3886. this.sendString_(String(dataSegs.length));
  3887. }
  3888. //Send the actual data in segments.
  3889. for (var i = 0; i < dataSegs.length; i++) {
  3890. this.sendString_(dataSegs[i]);
  3891. }
  3892. };
  3893. WebSocketConnection.prototype.shutdown_ = function () {
  3894. this.isClosed_ = true;
  3895. if (this.keepaliveTimer) {
  3896. clearInterval(this.keepaliveTimer);
  3897. this.keepaliveTimer = null;
  3898. }
  3899. if (this.mySock) {
  3900. this.mySock.close();
  3901. this.mySock = null;
  3902. }
  3903. };
  3904. WebSocketConnection.prototype.onClosed_ = function () {
  3905. if (!this.isClosed_) {
  3906. this.log_('WebSocket is closing itself');
  3907. this.shutdown_();
  3908. // since this is an internal close, trigger the close listener
  3909. if (this.onDisconnect) {
  3910. this.onDisconnect(this.everConnected_);
  3911. this.onDisconnect = null;
  3912. }
  3913. }
  3914. };
  3915. /**
  3916. * External-facing close handler.
  3917. * Close the websocket and kill the connection.
  3918. */
  3919. WebSocketConnection.prototype.close = function () {
  3920. if (!this.isClosed_) {
  3921. this.log_('WebSocket is being closed');
  3922. this.shutdown_();
  3923. }
  3924. };
  3925. /**
  3926. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  3927. * the last activity.
  3928. */
  3929. WebSocketConnection.prototype.resetKeepAlive = function () {
  3930. var _this = this;
  3931. clearInterval(this.keepaliveTimer);
  3932. this.keepaliveTimer = setInterval(function () {
  3933. //If there has been no websocket activity for a while, send a no-op
  3934. if (_this.mySock) {
  3935. _this.sendString_('0');
  3936. }
  3937. _this.resetKeepAlive();
  3938. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3939. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  3940. };
  3941. /**
  3942. * Send a string over the websocket.
  3943. *
  3944. * @param str - String to send.
  3945. */
  3946. WebSocketConnection.prototype.sendString_ = function (str) {
  3947. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  3948. // calls for some unknown reason. We treat these as an error and disconnect.
  3949. // See https://app.asana.com/0/58926111402292/68021340250410
  3950. try {
  3951. this.mySock.send(str);
  3952. }
  3953. catch (e) {
  3954. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  3955. setTimeout(this.onClosed_.bind(this), 0);
  3956. }
  3957. };
  3958. /**
  3959. * Number of response before we consider the connection "healthy."
  3960. */
  3961. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  3962. /**
  3963. * Time to wait for the connection te become healthy before giving up.
  3964. */
  3965. WebSocketConnection.healthyTimeout = 30000;
  3966. return WebSocketConnection;
  3967. }());
  3968. /**
  3969. * @license
  3970. * Copyright 2021 Google LLC
  3971. *
  3972. * Licensed under the Apache License, Version 2.0 (the "License");
  3973. * you may not use this file except in compliance with the License.
  3974. * You may obtain a copy of the License at
  3975. *
  3976. * http://www.apache.org/licenses/LICENSE-2.0
  3977. *
  3978. * Unless required by applicable law or agreed to in writing, software
  3979. * distributed under the License is distributed on an "AS IS" BASIS,
  3980. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3981. * See the License for the specific language governing permissions and
  3982. * limitations under the License.
  3983. */
  3984. /**
  3985. * Abstraction around AppCheck's token fetching capabilities.
  3986. */
  3987. var AppCheckTokenProvider = /** @class */ (function () {
  3988. function AppCheckTokenProvider(appName_, appCheckProvider) {
  3989. var _this = this;
  3990. this.appName_ = appName_;
  3991. this.appCheckProvider = appCheckProvider;
  3992. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  3993. if (!this.appCheck) {
  3994. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  3995. }
  3996. }
  3997. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  3998. var _this = this;
  3999. if (!this.appCheck) {
  4000. return new Promise(function (resolve, reject) {
  4001. // Support delayed initialization of FirebaseAppCheck. This allows our
  4002. // customers to initialize the RTDB SDK before initializing Firebase
  4003. // AppCheck and ensures that all requests are authenticated if a token
  4004. // becomes available before the timoeout below expires.
  4005. setTimeout(function () {
  4006. if (_this.appCheck) {
  4007. _this.getToken(forceRefresh).then(resolve, reject);
  4008. }
  4009. else {
  4010. resolve(null);
  4011. }
  4012. }, 0);
  4013. });
  4014. }
  4015. return this.appCheck.getToken(forceRefresh);
  4016. };
  4017. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  4018. var _a;
  4019. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  4020. };
  4021. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  4022. warn$1("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  4023. 'are invalid. This usually indicates your app was not initialized correctly.');
  4024. };
  4025. return AppCheckTokenProvider;
  4026. }());
  4027. /**
  4028. * @license
  4029. * Copyright 2017 Google LLC
  4030. *
  4031. * Licensed under the Apache License, Version 2.0 (the "License");
  4032. * you may not use this file except in compliance with the License.
  4033. * You may obtain a copy of the License at
  4034. *
  4035. * http://www.apache.org/licenses/LICENSE-2.0
  4036. *
  4037. * Unless required by applicable law or agreed to in writing, software
  4038. * distributed under the License is distributed on an "AS IS" BASIS,
  4039. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4040. * See the License for the specific language governing permissions and
  4041. * limitations under the License.
  4042. */
  4043. /**
  4044. * Abstraction around FirebaseApp's token fetching capabilities.
  4045. */
  4046. var FirebaseAuthTokenProvider = /** @class */ (function () {
  4047. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  4048. var _this = this;
  4049. this.appName_ = appName_;
  4050. this.firebaseOptions_ = firebaseOptions_;
  4051. this.authProvider_ = authProvider_;
  4052. this.auth_ = null;
  4053. this.auth_ = authProvider_.getImmediate({ optional: true });
  4054. if (!this.auth_) {
  4055. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  4056. }
  4057. }
  4058. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  4059. var _this = this;
  4060. if (!this.auth_) {
  4061. return new Promise(function (resolve, reject) {
  4062. // Support delayed initialization of FirebaseAuth. This allows our
  4063. // customers to initialize the RTDB SDK before initializing Firebase
  4064. // Auth and ensures that all requests are authenticated if a token
  4065. // becomes available before the timoeout below expires.
  4066. setTimeout(function () {
  4067. if (_this.auth_) {
  4068. _this.getToken(forceRefresh).then(resolve, reject);
  4069. }
  4070. else {
  4071. resolve(null);
  4072. }
  4073. }, 0);
  4074. });
  4075. }
  4076. return this.auth_.getToken(forceRefresh).catch(function (error) {
  4077. // TODO: Need to figure out all the cases this is raised and whether
  4078. // this makes sense.
  4079. if (error && error.code === 'auth/token-not-initialized') {
  4080. log('Got auth/token-not-initialized error. Treating as null token.');
  4081. return null;
  4082. }
  4083. else {
  4084. return Promise.reject(error);
  4085. }
  4086. });
  4087. };
  4088. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  4089. // TODO: We might want to wrap the listener and call it with no args to
  4090. // avoid a leaky abstraction, but that makes removing the listener harder.
  4091. if (this.auth_) {
  4092. this.auth_.addAuthTokenListener(listener);
  4093. }
  4094. else {
  4095. this.authProvider_
  4096. .get()
  4097. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  4098. }
  4099. };
  4100. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  4101. this.authProvider_
  4102. .get()
  4103. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  4104. };
  4105. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  4106. var errorMessage = 'Provided authentication credentials for the app named "' +
  4107. this.appName_ +
  4108. '" are invalid. This usually indicates your app was not ' +
  4109. 'initialized correctly. ';
  4110. if ('credential' in this.firebaseOptions_) {
  4111. errorMessage +=
  4112. 'Make sure the "credential" property provided to initializeApp() ' +
  4113. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  4114. 'project.';
  4115. }
  4116. else if ('serviceAccount' in this.firebaseOptions_) {
  4117. errorMessage +=
  4118. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  4119. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  4120. 'project.';
  4121. }
  4122. else {
  4123. errorMessage +=
  4124. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  4125. 'initializeApp() match the values provided for your app at ' +
  4126. 'https://console.firebase.google.com/.';
  4127. }
  4128. warn$1(errorMessage);
  4129. };
  4130. return FirebaseAuthTokenProvider;
  4131. }());
  4132. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  4133. var EmulatorTokenProvider = /** @class */ (function () {
  4134. function EmulatorTokenProvider(accessToken) {
  4135. this.accessToken = accessToken;
  4136. }
  4137. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  4138. return Promise.resolve({
  4139. accessToken: this.accessToken
  4140. });
  4141. };
  4142. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  4143. // Invoke the listener immediately to match the behavior in Firebase Auth
  4144. // (see packages/auth/src/auth.js#L1807)
  4145. listener(this.accessToken);
  4146. };
  4147. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  4148. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  4149. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  4150. EmulatorTokenProvider.OWNER = 'owner';
  4151. return EmulatorTokenProvider;
  4152. }());
  4153. /**
  4154. * @license
  4155. * Copyright 2017 Google LLC
  4156. *
  4157. * Licensed under the Apache License, Version 2.0 (the "License");
  4158. * you may not use this file except in compliance with the License.
  4159. * You may obtain a copy of the License at
  4160. *
  4161. * http://www.apache.org/licenses/LICENSE-2.0
  4162. *
  4163. * Unless required by applicable law or agreed to in writing, software
  4164. * distributed under the License is distributed on an "AS IS" BASIS,
  4165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4166. * See the License for the specific language governing permissions and
  4167. * limitations under the License.
  4168. */
  4169. /**
  4170. * This class ensures the packets from the server arrive in order
  4171. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  4172. */
  4173. var PacketReceiver = /** @class */ (function () {
  4174. /**
  4175. * @param onMessage_
  4176. */
  4177. function PacketReceiver(onMessage_) {
  4178. this.onMessage_ = onMessage_;
  4179. this.pendingResponses = [];
  4180. this.currentResponseNum = 0;
  4181. this.closeAfterResponse = -1;
  4182. this.onClose = null;
  4183. }
  4184. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  4185. this.closeAfterResponse = responseNum;
  4186. this.onClose = callback;
  4187. if (this.closeAfterResponse < this.currentResponseNum) {
  4188. this.onClose();
  4189. this.onClose = null;
  4190. }
  4191. };
  4192. /**
  4193. * Each message from the server comes with a response number, and an array of data. The responseNumber
  4194. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  4195. * browsers will respond in the same order as the requests we sent
  4196. */
  4197. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  4198. var _this = this;
  4199. this.pendingResponses[requestNum] = data;
  4200. var _loop_1 = function () {
  4201. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  4202. delete this_1.pendingResponses[this_1.currentResponseNum];
  4203. var _loop_2 = function (i) {
  4204. if (toProcess[i]) {
  4205. exceptionGuard(function () {
  4206. _this.onMessage_(toProcess[i]);
  4207. });
  4208. }
  4209. };
  4210. for (var i = 0; i < toProcess.length; ++i) {
  4211. _loop_2(i);
  4212. }
  4213. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  4214. if (this_1.onClose) {
  4215. this_1.onClose();
  4216. this_1.onClose = null;
  4217. }
  4218. return "break";
  4219. }
  4220. this_1.currentResponseNum++;
  4221. };
  4222. var this_1 = this;
  4223. while (this.pendingResponses[this.currentResponseNum]) {
  4224. var state_1 = _loop_1();
  4225. if (state_1 === "break")
  4226. break;
  4227. }
  4228. };
  4229. return PacketReceiver;
  4230. }());
  4231. /**
  4232. * @license
  4233. * Copyright 2017 Google LLC
  4234. *
  4235. * Licensed under the Apache License, Version 2.0 (the "License");
  4236. * you may not use this file except in compliance with the License.
  4237. * You may obtain a copy of the License at
  4238. *
  4239. * http://www.apache.org/licenses/LICENSE-2.0
  4240. *
  4241. * Unless required by applicable law or agreed to in writing, software
  4242. * distributed under the License is distributed on an "AS IS" BASIS,
  4243. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4244. * See the License for the specific language governing permissions and
  4245. * limitations under the License.
  4246. */
  4247. // URL query parameters associated with longpolling
  4248. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  4249. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  4250. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  4251. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  4252. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  4253. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  4254. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  4255. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  4256. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  4257. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  4258. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  4259. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  4260. //Data size constants.
  4261. //TODO: Perf: the maximum length actually differs from browser to browser.
  4262. // We should check what browser we're on and set accordingly.
  4263. var MAX_URL_DATA_SIZE = 1870;
  4264. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  4265. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  4266. /**
  4267. * Keepalive period
  4268. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  4269. * length of 30 seconds that we can't exceed.
  4270. */
  4271. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  4272. /**
  4273. * How long to wait before aborting a long-polling connection attempt.
  4274. */
  4275. var LP_CONNECT_TIMEOUT = 30000;
  4276. /**
  4277. * This class manages a single long-polling connection.
  4278. */
  4279. var BrowserPollConnection = /** @class */ (function () {
  4280. /**
  4281. * @param connId An identifier for this connection, used for logging
  4282. * @param repoInfo The info for the endpoint to send data to.
  4283. * @param applicationId The Firebase App ID for this project.
  4284. * @param appCheckToken The AppCheck token for this client.
  4285. * @param authToken The AuthToken to use for this connection.
  4286. * @param transportSessionId Optional transportSessionid if we are
  4287. * reconnecting for an existing transport session
  4288. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  4289. * already created a connection previously
  4290. */
  4291. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  4292. var _this = this;
  4293. this.connId = connId;
  4294. this.repoInfo = repoInfo;
  4295. this.applicationId = applicationId;
  4296. this.appCheckToken = appCheckToken;
  4297. this.authToken = authToken;
  4298. this.transportSessionId = transportSessionId;
  4299. this.lastSessionId = lastSessionId;
  4300. this.bytesSent = 0;
  4301. this.bytesReceived = 0;
  4302. this.everConnected_ = false;
  4303. this.log_ = logWrapper(connId);
  4304. this.stats_ = statsManagerGetCollection(repoInfo);
  4305. this.urlFn = function (params) {
  4306. // Always add the token if we have one.
  4307. if (_this.appCheckToken) {
  4308. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  4309. }
  4310. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  4311. };
  4312. }
  4313. /**
  4314. * @param onMessage - Callback when messages arrive
  4315. * @param onDisconnect - Callback with connection lost.
  4316. */
  4317. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  4318. var _this = this;
  4319. this.curSegmentNum = 0;
  4320. this.onDisconnect_ = onDisconnect;
  4321. this.myPacketOrderer = new PacketReceiver(onMessage);
  4322. this.isClosed_ = false;
  4323. this.connectTimeoutTimer_ = setTimeout(function () {
  4324. _this.log_('Timed out trying to connect.');
  4325. // Make sure we clear the host cache
  4326. _this.onClosed_();
  4327. _this.connectTimeoutTimer_ = null;
  4328. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4329. }, Math.floor(LP_CONNECT_TIMEOUT));
  4330. // Ensure we delay the creation of the iframe until the DOM is loaded.
  4331. executeWhenDOMReady(function () {
  4332. if (_this.isClosed_) {
  4333. return;
  4334. }
  4335. //Set up a callback that gets triggered once a connection is set up.
  4336. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  4337. var args = [];
  4338. for (var _i = 0; _i < arguments.length; _i++) {
  4339. args[_i] = arguments[_i];
  4340. }
  4341. var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  4342. _this.incrementIncomingBytes_(args);
  4343. if (!_this.scriptTagHolder) {
  4344. return; // we closed the connection.
  4345. }
  4346. if (_this.connectTimeoutTimer_) {
  4347. clearTimeout(_this.connectTimeoutTimer_);
  4348. _this.connectTimeoutTimer_ = null;
  4349. }
  4350. _this.everConnected_ = true;
  4351. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  4352. _this.id = arg1;
  4353. _this.password = arg2;
  4354. }
  4355. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  4356. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  4357. if (arg1) {
  4358. // We aren't expecting any more data (other than what the server's already in the process of sending us
  4359. // through our already open polls), so don't send any more.
  4360. _this.scriptTagHolder.sendNewPolls = false;
  4361. // arg1 in this case is the last response number sent by the server. We should try to receive
  4362. // all of the responses up to this one before closing
  4363. _this.myPacketOrderer.closeAfter(arg1, function () {
  4364. _this.onClosed_();
  4365. });
  4366. }
  4367. else {
  4368. _this.onClosed_();
  4369. }
  4370. }
  4371. else {
  4372. throw new Error('Unrecognized command received: ' + command);
  4373. }
  4374. }, function () {
  4375. var args = [];
  4376. for (var _i = 0; _i < arguments.length; _i++) {
  4377. args[_i] = arguments[_i];
  4378. }
  4379. var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
  4380. _this.incrementIncomingBytes_(args);
  4381. _this.myPacketOrderer.handleResponse(pN, data);
  4382. }, function () {
  4383. _this.onClosed_();
  4384. }, _this.urlFn);
  4385. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  4386. //from cache.
  4387. var urlParams = {};
  4388. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  4389. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  4390. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  4391. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  4392. _this.scriptTagHolder.uniqueCallbackIdentifier;
  4393. }
  4394. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  4395. if (_this.transportSessionId) {
  4396. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  4397. }
  4398. if (_this.lastSessionId) {
  4399. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  4400. }
  4401. if (_this.applicationId) {
  4402. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  4403. }
  4404. if (_this.appCheckToken) {
  4405. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  4406. }
  4407. if (typeof location !== 'undefined' &&
  4408. location.hostname &&
  4409. FORGE_DOMAIN_RE.test(location.hostname)) {
  4410. urlParams[REFERER_PARAM] = FORGE_REF;
  4411. }
  4412. var connectURL = _this.urlFn(urlParams);
  4413. _this.log_('Connecting via long-poll to ' + connectURL);
  4414. _this.scriptTagHolder.addTag(connectURL, function () {
  4415. /* do nothing */
  4416. });
  4417. });
  4418. };
  4419. /**
  4420. * Call this when a handshake has completed successfully and we want to consider the connection established
  4421. */
  4422. BrowserPollConnection.prototype.start = function () {
  4423. this.scriptTagHolder.startLongPoll(this.id, this.password);
  4424. this.addDisconnectPingFrame(this.id, this.password);
  4425. };
  4426. /**
  4427. * Forces long polling to be considered as a potential transport
  4428. */
  4429. BrowserPollConnection.forceAllow = function () {
  4430. BrowserPollConnection.forceAllow_ = true;
  4431. };
  4432. /**
  4433. * Forces longpolling to not be considered as a potential transport
  4434. */
  4435. BrowserPollConnection.forceDisallow = function () {
  4436. BrowserPollConnection.forceDisallow_ = true;
  4437. };
  4438. // Static method, use string literal so it can be accessed in a generic way
  4439. BrowserPollConnection.isAvailable = function () {
  4440. if (util.isNodeSdk()) {
  4441. return false;
  4442. }
  4443. else if (BrowserPollConnection.forceAllow_) {
  4444. return true;
  4445. }
  4446. else {
  4447. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  4448. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  4449. return (!BrowserPollConnection.forceDisallow_ &&
  4450. typeof document !== 'undefined' &&
  4451. document.createElement != null &&
  4452. !isChromeExtensionContentScript() &&
  4453. !isWindowsStoreApp());
  4454. }
  4455. };
  4456. /**
  4457. * No-op for polling
  4458. */
  4459. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  4460. /**
  4461. * Stops polling and cleans up the iframe
  4462. */
  4463. BrowserPollConnection.prototype.shutdown_ = function () {
  4464. this.isClosed_ = true;
  4465. if (this.scriptTagHolder) {
  4466. this.scriptTagHolder.close();
  4467. this.scriptTagHolder = null;
  4468. }
  4469. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  4470. if (this.myDisconnFrame) {
  4471. document.body.removeChild(this.myDisconnFrame);
  4472. this.myDisconnFrame = null;
  4473. }
  4474. if (this.connectTimeoutTimer_) {
  4475. clearTimeout(this.connectTimeoutTimer_);
  4476. this.connectTimeoutTimer_ = null;
  4477. }
  4478. };
  4479. /**
  4480. * Triggered when this transport is closed
  4481. */
  4482. BrowserPollConnection.prototype.onClosed_ = function () {
  4483. if (!this.isClosed_) {
  4484. this.log_('Longpoll is closing itself');
  4485. this.shutdown_();
  4486. if (this.onDisconnect_) {
  4487. this.onDisconnect_(this.everConnected_);
  4488. this.onDisconnect_ = null;
  4489. }
  4490. }
  4491. };
  4492. /**
  4493. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  4494. * that we've left.
  4495. */
  4496. BrowserPollConnection.prototype.close = function () {
  4497. if (!this.isClosed_) {
  4498. this.log_('Longpoll is being closed.');
  4499. this.shutdown_();
  4500. }
  4501. };
  4502. /**
  4503. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  4504. * broken into chunks (since URLs have a small maximum length).
  4505. * @param data - The JSON data to transmit.
  4506. */
  4507. BrowserPollConnection.prototype.send = function (data) {
  4508. var dataStr = util.stringify(data);
  4509. this.bytesSent += dataStr.length;
  4510. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  4511. //first, lets get the base64-encoded data
  4512. var base64data = util.base64Encode(dataStr);
  4513. //We can only fit a certain amount in each URL, so we need to split this request
  4514. //up into multiple pieces if it doesn't fit in one request.
  4515. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  4516. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  4517. //of segments so that we can reassemble the packet on the server.
  4518. for (var i = 0; i < dataSegs.length; i++) {
  4519. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  4520. this.curSegmentNum++;
  4521. }
  4522. };
  4523. /**
  4524. * This is how we notify the server that we're leaving.
  4525. * We aren't able to send requests with DHTML on a window close event, but we can
  4526. * trigger XHR requests in some browsers (everything but Opera basically).
  4527. */
  4528. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  4529. if (util.isNodeSdk()) {
  4530. return;
  4531. }
  4532. this.myDisconnFrame = document.createElement('iframe');
  4533. var urlParams = {};
  4534. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  4535. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  4536. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  4537. this.myDisconnFrame.src = this.urlFn(urlParams);
  4538. this.myDisconnFrame.style.display = 'none';
  4539. document.body.appendChild(this.myDisconnFrame);
  4540. };
  4541. /**
  4542. * Used to track the bytes received by this client
  4543. */
  4544. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  4545. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  4546. var bytesReceived = util.stringify(args).length;
  4547. this.bytesReceived += bytesReceived;
  4548. this.stats_.incrementCounter('bytes_received', bytesReceived);
  4549. };
  4550. return BrowserPollConnection;
  4551. }());
  4552. /*********************************************************************************************
  4553. * A wrapper around an iframe that is used as a long-polling script holder.
  4554. *********************************************************************************************/
  4555. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  4556. /**
  4557. * @param commandCB - The callback to be called when control commands are recevied from the server.
  4558. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  4559. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  4560. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  4561. */
  4562. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  4563. this.onDisconnect = onDisconnect;
  4564. this.urlFn = urlFn;
  4565. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  4566. //problems in some browsers.
  4567. this.outstandingRequests = new Set();
  4568. //A queue of the pending segments waiting for transmission to the server.
  4569. this.pendingSegs = [];
  4570. //A serial number. We use this for two things:
  4571. // 1) A way to ensure the browser doesn't cache responses to polls
  4572. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  4573. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  4574. // JSONP code in the order it was added to the iframe.
  4575. this.currentSerial = Math.floor(Math.random() * 100000000);
  4576. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  4577. // incoming data from the server that we're waiting for).
  4578. this.sendNewPolls = true;
  4579. if (!util.isNodeSdk()) {
  4580. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  4581. //iframes where we put the long-polling script tags. We have two callbacks:
  4582. // 1) Command Callback - Triggered for control issues, like starting a connection.
  4583. // 2) Message Callback - Triggered when new data arrives.
  4584. this.uniqueCallbackIdentifier = LUIDGenerator();
  4585. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  4586. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  4587. onMessageCB;
  4588. //Create an iframe for us to add script tags to.
  4589. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  4590. // Set the iframe's contents.
  4591. var script = '';
  4592. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  4593. // for ie9, but ie8 needs to do it again in the document itself.
  4594. if (this.myIFrame.src &&
  4595. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  4596. var currentDomain = document.domain;
  4597. script = '<script>document.domain="' + currentDomain + '";</script>';
  4598. }
  4599. var iframeContents = '<html><body>' + script + '</body></html>';
  4600. try {
  4601. this.myIFrame.doc.open();
  4602. this.myIFrame.doc.write(iframeContents);
  4603. this.myIFrame.doc.close();
  4604. }
  4605. catch (e) {
  4606. log('frame writing exception');
  4607. if (e.stack) {
  4608. log(e.stack);
  4609. }
  4610. log(e);
  4611. }
  4612. }
  4613. else {
  4614. this.commandCB = commandCB;
  4615. this.onMessageCB = onMessageCB;
  4616. }
  4617. }
  4618. /**
  4619. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  4620. * actually use.
  4621. */
  4622. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  4623. var iframe = document.createElement('iframe');
  4624. iframe.style.display = 'none';
  4625. // This is necessary in order to initialize the document inside the iframe
  4626. if (document.body) {
  4627. document.body.appendChild(iframe);
  4628. try {
  4629. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  4630. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  4631. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  4632. var a = iframe.contentWindow.document;
  4633. if (!a) {
  4634. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  4635. log('No IE domain setting required');
  4636. }
  4637. }
  4638. catch (e) {
  4639. var domain = document.domain;
  4640. iframe.src =
  4641. "javascript:void((function(){document.open();document.domain='" +
  4642. domain +
  4643. "';document.close();})())";
  4644. }
  4645. }
  4646. else {
  4647. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  4648. // never gets hit.
  4649. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  4650. }
  4651. // Get the document of the iframe in a browser-specific way.
  4652. if (iframe.contentDocument) {
  4653. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  4654. }
  4655. else if (iframe.contentWindow) {
  4656. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  4657. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4658. }
  4659. else if (iframe.document) {
  4660. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4661. iframe.doc = iframe.document; //others?
  4662. }
  4663. return iframe;
  4664. };
  4665. /**
  4666. * Cancel all outstanding queries and remove the frame.
  4667. */
  4668. FirebaseIFrameScriptHolder.prototype.close = function () {
  4669. var _this = this;
  4670. //Mark this iframe as dead, so no new requests are sent.
  4671. this.alive = false;
  4672. if (this.myIFrame) {
  4673. //We have to actually remove all of the html inside this iframe before removing it from the
  4674. //window, or IE will continue loading and executing the script tags we've already added, which
  4675. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  4676. this.myIFrame.doc.body.textContent = '';
  4677. setTimeout(function () {
  4678. if (_this.myIFrame !== null) {
  4679. document.body.removeChild(_this.myIFrame);
  4680. _this.myIFrame = null;
  4681. }
  4682. }, Math.floor(0));
  4683. }
  4684. // Protect from being called recursively.
  4685. var onDisconnect = this.onDisconnect;
  4686. if (onDisconnect) {
  4687. this.onDisconnect = null;
  4688. onDisconnect();
  4689. }
  4690. };
  4691. /**
  4692. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  4693. * @param id - The ID of this connection
  4694. * @param pw - The password for this connection
  4695. */
  4696. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  4697. this.myID = id;
  4698. this.myPW = pw;
  4699. this.alive = true;
  4700. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  4701. while (this.newRequest_()) { }
  4702. };
  4703. /**
  4704. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  4705. * too many outstanding requests and we are still alive.
  4706. *
  4707. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  4708. * needed.
  4709. */
  4710. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  4711. // We keep one outstanding request open all the time to receive data, but if we need to send data
  4712. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  4713. // close the old request.
  4714. if (this.alive &&
  4715. this.sendNewPolls &&
  4716. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  4717. //construct our url
  4718. this.currentSerial++;
  4719. var urlParams = {};
  4720. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  4721. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  4722. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  4723. var theURL = this.urlFn(urlParams);
  4724. //Now add as much data as we can.
  4725. var curDataString = '';
  4726. var i = 0;
  4727. while (this.pendingSegs.length > 0) {
  4728. //first, lets see if the next segment will fit.
  4729. var nextSeg = this.pendingSegs[0];
  4730. if (nextSeg.d.length +
  4731. SEG_HEADER_SIZE +
  4732. curDataString.length <=
  4733. MAX_URL_DATA_SIZE) {
  4734. //great, the segment will fit. Lets append it.
  4735. var theSeg = this.pendingSegs.shift();
  4736. curDataString =
  4737. curDataString +
  4738. '&' +
  4739. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  4740. i +
  4741. '=' +
  4742. theSeg.seg +
  4743. '&' +
  4744. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  4745. i +
  4746. '=' +
  4747. theSeg.ts +
  4748. '&' +
  4749. FIREBASE_LONGPOLL_DATA_PARAM +
  4750. i +
  4751. '=' +
  4752. theSeg.d;
  4753. i++;
  4754. }
  4755. else {
  4756. break;
  4757. }
  4758. }
  4759. theURL = theURL + curDataString;
  4760. this.addLongPollTag_(theURL, this.currentSerial);
  4761. return true;
  4762. }
  4763. else {
  4764. return false;
  4765. }
  4766. };
  4767. /**
  4768. * Queue a packet for transmission to the server.
  4769. * @param segnum - A sequential id for this packet segment used for reassembly
  4770. * @param totalsegs - The total number of segments in this packet
  4771. * @param data - The data for this segment.
  4772. */
  4773. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  4774. //add this to the queue of segments to send.
  4775. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  4776. //send the data immediately if there isn't already data being transmitted, unless
  4777. //startLongPoll hasn't been called yet.
  4778. if (this.alive) {
  4779. this.newRequest_();
  4780. }
  4781. };
  4782. /**
  4783. * Add a script tag for a regular long-poll request.
  4784. * @param url - The URL of the script tag.
  4785. * @param serial - The serial number of the request.
  4786. */
  4787. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  4788. var _this = this;
  4789. //remember that we sent this request.
  4790. this.outstandingRequests.add(serial);
  4791. var doNewRequest = function () {
  4792. _this.outstandingRequests.delete(serial);
  4793. _this.newRequest_();
  4794. };
  4795. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  4796. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  4797. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  4798. var readyStateCB = function () {
  4799. // Request completed. Cancel the keepalive.
  4800. clearTimeout(keepaliveTimeout);
  4801. // Trigger a new request so we can continue receiving data.
  4802. doNewRequest();
  4803. };
  4804. this.addTag(url, readyStateCB);
  4805. };
  4806. /**
  4807. * Add an arbitrary script tag to the iframe.
  4808. * @param url - The URL for the script tag source.
  4809. * @param loadCB - A callback to be triggered once the script has loaded.
  4810. */
  4811. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  4812. var _this = this;
  4813. if (util.isNodeSdk()) {
  4814. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4815. this.doNodeLongPoll(url, loadCB);
  4816. }
  4817. else {
  4818. setTimeout(function () {
  4819. try {
  4820. // if we're already closed, don't add this poll
  4821. if (!_this.sendNewPolls) {
  4822. return;
  4823. }
  4824. var newScript_1 = _this.myIFrame.doc.createElement('script');
  4825. newScript_1.type = 'text/javascript';
  4826. newScript_1.async = true;
  4827. newScript_1.src = url;
  4828. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4829. newScript_1.onload = newScript_1.onreadystatechange =
  4830. function () {
  4831. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4832. var rstate = newScript_1.readyState;
  4833. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  4834. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4835. newScript_1.onload = newScript_1.onreadystatechange = null;
  4836. if (newScript_1.parentNode) {
  4837. newScript_1.parentNode.removeChild(newScript_1);
  4838. }
  4839. loadCB();
  4840. }
  4841. };
  4842. newScript_1.onerror = function () {
  4843. log('Long-poll script failed to load: ' + url);
  4844. _this.sendNewPolls = false;
  4845. _this.close();
  4846. };
  4847. _this.myIFrame.doc.body.appendChild(newScript_1);
  4848. }
  4849. catch (e) {
  4850. // TODO: we should make this error visible somehow
  4851. }
  4852. }, Math.floor(1));
  4853. }
  4854. };
  4855. return FirebaseIFrameScriptHolder;
  4856. }());
  4857. /**
  4858. * @license
  4859. * Copyright 2017 Google LLC
  4860. *
  4861. * Licensed under the Apache License, Version 2.0 (the "License");
  4862. * you may not use this file except in compliance with the License.
  4863. * You may obtain a copy of the License at
  4864. *
  4865. * http://www.apache.org/licenses/LICENSE-2.0
  4866. *
  4867. * Unless required by applicable law or agreed to in writing, software
  4868. * distributed under the License is distributed on an "AS IS" BASIS,
  4869. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4870. * See the License for the specific language governing permissions and
  4871. * limitations under the License.
  4872. */
  4873. /**
  4874. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  4875. * lifecycle.
  4876. *
  4877. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  4878. * they are available.
  4879. */
  4880. var TransportManager = /** @class */ (function () {
  4881. /**
  4882. * @param repoInfo - Metadata around the namespace we're connecting to
  4883. */
  4884. function TransportManager(repoInfo) {
  4885. this.initTransports_(repoInfo);
  4886. }
  4887. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  4888. get: function () {
  4889. return [BrowserPollConnection, WebSocketConnection];
  4890. },
  4891. enumerable: false,
  4892. configurable: true
  4893. });
  4894. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  4895. /**
  4896. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  4897. * TransportManager has already set up transports_
  4898. */
  4899. get: function () {
  4900. return this.globalTransportInitialized_;
  4901. },
  4902. enumerable: false,
  4903. configurable: true
  4904. });
  4905. TransportManager.prototype.initTransports_ = function (repoInfo) {
  4906. var e_1, _a;
  4907. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  4908. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  4909. if (repoInfo.webSocketOnly) {
  4910. if (!isWebSocketsAvailable) {
  4911. warn$1("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  4912. }
  4913. isSkipPollConnection = true;
  4914. }
  4915. if (isSkipPollConnection) {
  4916. this.transports_ = [WebSocketConnection];
  4917. }
  4918. else {
  4919. var transports = (this.transports_ = []);
  4920. try {
  4921. for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  4922. var transport = _c.value;
  4923. if (transport && transport['isAvailable']()) {
  4924. transports.push(transport);
  4925. }
  4926. }
  4927. }
  4928. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4929. finally {
  4930. try {
  4931. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  4932. }
  4933. finally { if (e_1) throw e_1.error; }
  4934. }
  4935. TransportManager.globalTransportInitialized_ = true;
  4936. }
  4937. };
  4938. /**
  4939. * @returns The constructor for the initial transport to use
  4940. */
  4941. TransportManager.prototype.initialTransport = function () {
  4942. if (this.transports_.length > 0) {
  4943. return this.transports_[0];
  4944. }
  4945. else {
  4946. throw new Error('No transports available');
  4947. }
  4948. };
  4949. /**
  4950. * @returns The constructor for the next transport, or null
  4951. */
  4952. TransportManager.prototype.upgradeTransport = function () {
  4953. if (this.transports_.length > 1) {
  4954. return this.transports_[1];
  4955. }
  4956. else {
  4957. return null;
  4958. }
  4959. };
  4960. // Keeps track of whether the TransportManager has already chosen a transport to use
  4961. TransportManager.globalTransportInitialized_ = false;
  4962. return TransportManager;
  4963. }());
  4964. /**
  4965. * @license
  4966. * Copyright 2017 Google LLC
  4967. *
  4968. * Licensed under the Apache License, Version 2.0 (the "License");
  4969. * you may not use this file except in compliance with the License.
  4970. * You may obtain a copy of the License at
  4971. *
  4972. * http://www.apache.org/licenses/LICENSE-2.0
  4973. *
  4974. * Unless required by applicable law or agreed to in writing, software
  4975. * distributed under the License is distributed on an "AS IS" BASIS,
  4976. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4977. * See the License for the specific language governing permissions and
  4978. * limitations under the License.
  4979. */
  4980. // Abort upgrade attempt if it takes longer than 60s.
  4981. var UPGRADE_TIMEOUT = 60000;
  4982. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  4983. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  4984. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  4985. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  4986. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  4987. // but we've sent/received enough bytes, we don't cancel the connection.
  4988. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  4989. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  4990. var MESSAGE_TYPE = 't';
  4991. var MESSAGE_DATA = 'd';
  4992. var CONTROL_SHUTDOWN = 's';
  4993. var CONTROL_RESET = 'r';
  4994. var CONTROL_ERROR = 'e';
  4995. var CONTROL_PONG = 'o';
  4996. var SWITCH_ACK = 'a';
  4997. var END_TRANSMISSION = 'n';
  4998. var PING = 'p';
  4999. var SERVER_HELLO = 'h';
  5000. /**
  5001. * Creates a new real-time connection to the server using whichever method works
  5002. * best in the current browser.
  5003. */
  5004. var Connection = /** @class */ (function () {
  5005. /**
  5006. * @param id - an id for this connection
  5007. * @param repoInfo_ - the info for the endpoint to connect to
  5008. * @param applicationId_ - the Firebase App ID for this project
  5009. * @param appCheckToken_ - The App Check Token for this device.
  5010. * @param authToken_ - The auth token for this session.
  5011. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  5012. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  5013. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  5014. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  5015. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  5016. */
  5017. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  5018. this.id = id;
  5019. this.repoInfo_ = repoInfo_;
  5020. this.applicationId_ = applicationId_;
  5021. this.appCheckToken_ = appCheckToken_;
  5022. this.authToken_ = authToken_;
  5023. this.onMessage_ = onMessage_;
  5024. this.onReady_ = onReady_;
  5025. this.onDisconnect_ = onDisconnect_;
  5026. this.onKill_ = onKill_;
  5027. this.lastSessionId = lastSessionId;
  5028. this.connectionCount = 0;
  5029. this.pendingDataMessages = [];
  5030. this.state_ = 0 /* RealtimeState.CONNECTING */;
  5031. this.log_ = logWrapper('c:' + this.id + ':');
  5032. this.transportManager_ = new TransportManager(repoInfo_);
  5033. this.log_('Connection created');
  5034. this.start_();
  5035. }
  5036. /**
  5037. * Starts a connection attempt
  5038. */
  5039. Connection.prototype.start_ = function () {
  5040. var _this = this;
  5041. var conn = this.transportManager_.initialTransport();
  5042. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  5043. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  5044. // can consider the transport healthy.
  5045. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  5046. var onMessageReceived = this.connReceiver_(this.conn_);
  5047. var onConnectionLost = this.disconnReceiver_(this.conn_);
  5048. this.tx_ = this.conn_;
  5049. this.rx_ = this.conn_;
  5050. this.secondaryConn_ = null;
  5051. this.isHealthy_ = false;
  5052. /*
  5053. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  5054. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  5055. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  5056. * still have the context of your originating frame.
  5057. */
  5058. setTimeout(function () {
  5059. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  5060. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  5061. }, Math.floor(0));
  5062. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  5063. if (healthyTimeoutMS > 0) {
  5064. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  5065. _this.healthyTimeout_ = null;
  5066. if (!_this.isHealthy_) {
  5067. if (_this.conn_ &&
  5068. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  5069. _this.log_('Connection exceeded healthy timeout but has received ' +
  5070. _this.conn_.bytesReceived +
  5071. ' bytes. Marking connection healthy.');
  5072. _this.isHealthy_ = true;
  5073. _this.conn_.markConnectionHealthy();
  5074. }
  5075. else if (_this.conn_ &&
  5076. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  5077. _this.log_('Connection exceeded healthy timeout but has sent ' +
  5078. _this.conn_.bytesSent +
  5079. ' bytes. Leaving connection alive.');
  5080. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  5081. // the server.
  5082. }
  5083. else {
  5084. _this.log_('Closing unhealthy connection after timeout.');
  5085. _this.close();
  5086. }
  5087. }
  5088. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5089. }, Math.floor(healthyTimeoutMS));
  5090. }
  5091. };
  5092. Connection.prototype.nextTransportId_ = function () {
  5093. return 'c:' + this.id + ':' + this.connectionCount++;
  5094. };
  5095. Connection.prototype.disconnReceiver_ = function (conn) {
  5096. var _this = this;
  5097. return function (everConnected) {
  5098. if (conn === _this.conn_) {
  5099. _this.onConnectionLost_(everConnected);
  5100. }
  5101. else if (conn === _this.secondaryConn_) {
  5102. _this.log_('Secondary connection lost.');
  5103. _this.onSecondaryConnectionLost_();
  5104. }
  5105. else {
  5106. _this.log_('closing an old connection');
  5107. }
  5108. };
  5109. };
  5110. Connection.prototype.connReceiver_ = function (conn) {
  5111. var _this = this;
  5112. return function (message) {
  5113. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  5114. if (conn === _this.rx_) {
  5115. _this.onPrimaryMessageReceived_(message);
  5116. }
  5117. else if (conn === _this.secondaryConn_) {
  5118. _this.onSecondaryMessageReceived_(message);
  5119. }
  5120. else {
  5121. _this.log_('message on old connection');
  5122. }
  5123. }
  5124. };
  5125. };
  5126. /**
  5127. * @param dataMsg - An arbitrary data message to be sent to the server
  5128. */
  5129. Connection.prototype.sendRequest = function (dataMsg) {
  5130. // wrap in a data message envelope and send it on
  5131. var msg = { t: 'd', d: dataMsg };
  5132. this.sendData_(msg);
  5133. };
  5134. Connection.prototype.tryCleanupConnection = function () {
  5135. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  5136. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  5137. this.conn_ = this.secondaryConn_;
  5138. this.secondaryConn_ = null;
  5139. // the server will shutdown the old connection
  5140. }
  5141. };
  5142. Connection.prototype.onSecondaryControl_ = function (controlData) {
  5143. if (MESSAGE_TYPE in controlData) {
  5144. var cmd = controlData[MESSAGE_TYPE];
  5145. if (cmd === SWITCH_ACK) {
  5146. this.upgradeIfSecondaryHealthy_();
  5147. }
  5148. else if (cmd === CONTROL_RESET) {
  5149. // Most likely the session wasn't valid. Abandon the switch attempt
  5150. this.log_('Got a reset on secondary, closing it');
  5151. this.secondaryConn_.close();
  5152. // If we were already using this connection for something, than we need to fully close
  5153. if (this.tx_ === this.secondaryConn_ ||
  5154. this.rx_ === this.secondaryConn_) {
  5155. this.close();
  5156. }
  5157. }
  5158. else if (cmd === CONTROL_PONG) {
  5159. this.log_('got pong on secondary.');
  5160. this.secondaryResponsesRequired_--;
  5161. this.upgradeIfSecondaryHealthy_();
  5162. }
  5163. }
  5164. };
  5165. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  5166. var layer = requireKey('t', parsedData);
  5167. var data = requireKey('d', parsedData);
  5168. if (layer === 'c') {
  5169. this.onSecondaryControl_(data);
  5170. }
  5171. else if (layer === 'd') {
  5172. // got a data message, but we're still second connection. Need to buffer it up
  5173. this.pendingDataMessages.push(data);
  5174. }
  5175. else {
  5176. throw new Error('Unknown protocol layer: ' + layer);
  5177. }
  5178. };
  5179. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  5180. if (this.secondaryResponsesRequired_ <= 0) {
  5181. this.log_('Secondary connection is healthy.');
  5182. this.isHealthy_ = true;
  5183. this.secondaryConn_.markConnectionHealthy();
  5184. this.proceedWithUpgrade_();
  5185. }
  5186. else {
  5187. // Send a ping to make sure the connection is healthy.
  5188. this.log_('sending ping on secondary.');
  5189. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  5190. }
  5191. };
  5192. Connection.prototype.proceedWithUpgrade_ = function () {
  5193. // tell this connection to consider itself open
  5194. this.secondaryConn_.start();
  5195. // send ack
  5196. this.log_('sending client ack on secondary');
  5197. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  5198. // send end packet on primary transport, switch to sending on this one
  5199. // can receive on this one, buffer responses until end received on primary transport
  5200. this.log_('Ending transmission on primary');
  5201. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  5202. this.tx_ = this.secondaryConn_;
  5203. this.tryCleanupConnection();
  5204. };
  5205. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  5206. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  5207. var layer = requireKey('t', parsedData);
  5208. var data = requireKey('d', parsedData);
  5209. if (layer === 'c') {
  5210. this.onControl_(data);
  5211. }
  5212. else if (layer === 'd') {
  5213. this.onDataMessage_(data);
  5214. }
  5215. };
  5216. Connection.prototype.onDataMessage_ = function (message) {
  5217. this.onPrimaryResponse_();
  5218. // We don't do anything with data messages, just kick them up a level
  5219. this.onMessage_(message);
  5220. };
  5221. Connection.prototype.onPrimaryResponse_ = function () {
  5222. if (!this.isHealthy_) {
  5223. this.primaryResponsesRequired_--;
  5224. if (this.primaryResponsesRequired_ <= 0) {
  5225. this.log_('Primary connection is healthy.');
  5226. this.isHealthy_ = true;
  5227. this.conn_.markConnectionHealthy();
  5228. }
  5229. }
  5230. };
  5231. Connection.prototype.onControl_ = function (controlData) {
  5232. var cmd = requireKey(MESSAGE_TYPE, controlData);
  5233. if (MESSAGE_DATA in controlData) {
  5234. var payload = controlData[MESSAGE_DATA];
  5235. if (cmd === SERVER_HELLO) {
  5236. this.onHandshake_(payload);
  5237. }
  5238. else if (cmd === END_TRANSMISSION) {
  5239. this.log_('recvd end transmission on primary');
  5240. this.rx_ = this.secondaryConn_;
  5241. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  5242. this.onDataMessage_(this.pendingDataMessages[i]);
  5243. }
  5244. this.pendingDataMessages = [];
  5245. this.tryCleanupConnection();
  5246. }
  5247. else if (cmd === CONTROL_SHUTDOWN) {
  5248. // This was previously the 'onKill' callback passed to the lower-level connection
  5249. // payload in this case is the reason for the shutdown. Generally a human-readable error
  5250. this.onConnectionShutdown_(payload);
  5251. }
  5252. else if (cmd === CONTROL_RESET) {
  5253. // payload in this case is the host we should contact
  5254. this.onReset_(payload);
  5255. }
  5256. else if (cmd === CONTROL_ERROR) {
  5257. error('Server Error: ' + payload);
  5258. }
  5259. else if (cmd === CONTROL_PONG) {
  5260. this.log_('got pong on primary.');
  5261. this.onPrimaryResponse_();
  5262. this.sendPingOnPrimaryIfNecessary_();
  5263. }
  5264. else {
  5265. error('Unknown control packet command: ' + cmd);
  5266. }
  5267. }
  5268. };
  5269. /**
  5270. * @param handshake - The handshake data returned from the server
  5271. */
  5272. Connection.prototype.onHandshake_ = function (handshake) {
  5273. var timestamp = handshake.ts;
  5274. var version = handshake.v;
  5275. var host = handshake.h;
  5276. this.sessionId = handshake.s;
  5277. this.repoInfo_.host = host;
  5278. // if we've already closed the connection, then don't bother trying to progress further
  5279. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  5280. this.conn_.start();
  5281. this.onConnectionEstablished_(this.conn_, timestamp);
  5282. if (PROTOCOL_VERSION !== version) {
  5283. warn$1('Protocol version mismatch detected');
  5284. }
  5285. // TODO: do we want to upgrade? when? maybe a delay?
  5286. this.tryStartUpgrade_();
  5287. }
  5288. };
  5289. Connection.prototype.tryStartUpgrade_ = function () {
  5290. var conn = this.transportManager_.upgradeTransport();
  5291. if (conn) {
  5292. this.startUpgrade_(conn);
  5293. }
  5294. };
  5295. Connection.prototype.startUpgrade_ = function (conn) {
  5296. var _this = this;
  5297. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  5298. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  5299. // can consider the transport healthy.
  5300. this.secondaryResponsesRequired_ =
  5301. conn['responsesRequiredToBeHealthy'] || 0;
  5302. var onMessage = this.connReceiver_(this.secondaryConn_);
  5303. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  5304. this.secondaryConn_.open(onMessage, onDisconnect);
  5305. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  5306. setTimeoutNonBlocking(function () {
  5307. if (_this.secondaryConn_) {
  5308. _this.log_('Timed out trying to upgrade.');
  5309. _this.secondaryConn_.close();
  5310. }
  5311. }, Math.floor(UPGRADE_TIMEOUT));
  5312. };
  5313. Connection.prototype.onReset_ = function (host) {
  5314. this.log_('Reset packet received. New host: ' + host);
  5315. this.repoInfo_.host = host;
  5316. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  5317. // We don't currently support resets after the connection has already been established
  5318. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5319. this.close();
  5320. }
  5321. else {
  5322. // Close whatever connections we have open and start again.
  5323. this.closeConnections_();
  5324. this.start_();
  5325. }
  5326. };
  5327. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  5328. var _this = this;
  5329. this.log_('Realtime connection established.');
  5330. this.conn_ = conn;
  5331. this.state_ = 1 /* RealtimeState.CONNECTED */;
  5332. if (this.onReady_) {
  5333. this.onReady_(timestamp, this.sessionId);
  5334. this.onReady_ = null;
  5335. }
  5336. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  5337. // send some pings.
  5338. if (this.primaryResponsesRequired_ === 0) {
  5339. this.log_('Primary connection is healthy.');
  5340. this.isHealthy_ = true;
  5341. }
  5342. else {
  5343. setTimeoutNonBlocking(function () {
  5344. _this.sendPingOnPrimaryIfNecessary_();
  5345. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  5346. }
  5347. };
  5348. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  5349. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  5350. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5351. this.log_('sending ping on primary.');
  5352. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  5353. }
  5354. };
  5355. Connection.prototype.onSecondaryConnectionLost_ = function () {
  5356. var conn = this.secondaryConn_;
  5357. this.secondaryConn_ = null;
  5358. if (this.tx_ === conn || this.rx_ === conn) {
  5359. // we are relying on this connection already in some capacity. Therefore, a failure is real
  5360. this.close();
  5361. }
  5362. };
  5363. /**
  5364. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  5365. * we should flush the host cache
  5366. */
  5367. Connection.prototype.onConnectionLost_ = function (everConnected) {
  5368. this.conn_ = null;
  5369. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  5370. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  5371. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  5372. this.log_('Realtime connection failed.');
  5373. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  5374. if (this.repoInfo_.isCacheableHost()) {
  5375. PersistentStorage.remove('host:' + this.repoInfo_.host);
  5376. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  5377. this.repoInfo_.internalHost = this.repoInfo_.host;
  5378. }
  5379. }
  5380. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  5381. this.log_('Realtime connection lost.');
  5382. }
  5383. this.close();
  5384. };
  5385. Connection.prototype.onConnectionShutdown_ = function (reason) {
  5386. this.log_('Connection shutdown command received. Shutting down...');
  5387. if (this.onKill_) {
  5388. this.onKill_(reason);
  5389. this.onKill_ = null;
  5390. }
  5391. // We intentionally don't want to fire onDisconnect (kill is a different case),
  5392. // so clear the callback.
  5393. this.onDisconnect_ = null;
  5394. this.close();
  5395. };
  5396. Connection.prototype.sendData_ = function (data) {
  5397. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  5398. throw 'Connection is not connected';
  5399. }
  5400. else {
  5401. this.tx_.send(data);
  5402. }
  5403. };
  5404. /**
  5405. * Cleans up this connection, calling the appropriate callbacks
  5406. */
  5407. Connection.prototype.close = function () {
  5408. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  5409. this.log_('Closing realtime connection.');
  5410. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  5411. this.closeConnections_();
  5412. if (this.onDisconnect_) {
  5413. this.onDisconnect_();
  5414. this.onDisconnect_ = null;
  5415. }
  5416. }
  5417. };
  5418. Connection.prototype.closeConnections_ = function () {
  5419. this.log_('Shutting down all connections');
  5420. if (this.conn_) {
  5421. this.conn_.close();
  5422. this.conn_ = null;
  5423. }
  5424. if (this.secondaryConn_) {
  5425. this.secondaryConn_.close();
  5426. this.secondaryConn_ = null;
  5427. }
  5428. if (this.healthyTimeout_) {
  5429. clearTimeout(this.healthyTimeout_);
  5430. this.healthyTimeout_ = null;
  5431. }
  5432. };
  5433. return Connection;
  5434. }());
  5435. /**
  5436. * @license
  5437. * Copyright 2017 Google LLC
  5438. *
  5439. * Licensed under the Apache License, Version 2.0 (the "License");
  5440. * you may not use this file except in compliance with the License.
  5441. * You may obtain a copy of the License at
  5442. *
  5443. * http://www.apache.org/licenses/LICENSE-2.0
  5444. *
  5445. * Unless required by applicable law or agreed to in writing, software
  5446. * distributed under the License is distributed on an "AS IS" BASIS,
  5447. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5448. * See the License for the specific language governing permissions and
  5449. * limitations under the License.
  5450. */
  5451. /**
  5452. * Interface defining the set of actions that can be performed against the Firebase server
  5453. * (basically corresponds to our wire protocol).
  5454. *
  5455. * @interface
  5456. */
  5457. var ServerActions = /** @class */ (function () {
  5458. function ServerActions() {
  5459. }
  5460. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  5461. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  5462. /**
  5463. * Refreshes the auth token for the current connection.
  5464. * @param token - The authentication token
  5465. */
  5466. ServerActions.prototype.refreshAuthToken = function (token) { };
  5467. /**
  5468. * Refreshes the app check token for the current connection.
  5469. * @param token The app check token
  5470. */
  5471. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  5472. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  5473. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  5474. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  5475. ServerActions.prototype.reportStats = function (stats) { };
  5476. return ServerActions;
  5477. }());
  5478. /**
  5479. * @license
  5480. * Copyright 2017 Google LLC
  5481. *
  5482. * Licensed under the Apache License, Version 2.0 (the "License");
  5483. * you may not use this file except in compliance with the License.
  5484. * You may obtain a copy of the License at
  5485. *
  5486. * http://www.apache.org/licenses/LICENSE-2.0
  5487. *
  5488. * Unless required by applicable law or agreed to in writing, software
  5489. * distributed under the License is distributed on an "AS IS" BASIS,
  5490. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5491. * See the License for the specific language governing permissions and
  5492. * limitations under the License.
  5493. */
  5494. /**
  5495. * Base class to be used if you want to emit events. Call the constructor with
  5496. * the set of allowed event names.
  5497. */
  5498. var EventEmitter = /** @class */ (function () {
  5499. function EventEmitter(allowedEvents_) {
  5500. this.allowedEvents_ = allowedEvents_;
  5501. this.listeners_ = {};
  5502. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  5503. }
  5504. /**
  5505. * To be called by derived classes to trigger events.
  5506. */
  5507. EventEmitter.prototype.trigger = function (eventType) {
  5508. var varArgs = [];
  5509. for (var _i = 1; _i < arguments.length; _i++) {
  5510. varArgs[_i - 1] = arguments[_i];
  5511. }
  5512. if (Array.isArray(this.listeners_[eventType])) {
  5513. // Clone the list, since callbacks could add/remove listeners.
  5514. var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
  5515. for (var i = 0; i < listeners.length; i++) {
  5516. listeners[i].callback.apply(listeners[i].context, varArgs);
  5517. }
  5518. }
  5519. };
  5520. EventEmitter.prototype.on = function (eventType, callback, context) {
  5521. this.validateEventType_(eventType);
  5522. this.listeners_[eventType] = this.listeners_[eventType] || [];
  5523. this.listeners_[eventType].push({ callback: callback, context: context });
  5524. var eventData = this.getInitialEvent(eventType);
  5525. if (eventData) {
  5526. callback.apply(context, eventData);
  5527. }
  5528. };
  5529. EventEmitter.prototype.off = function (eventType, callback, context) {
  5530. this.validateEventType_(eventType);
  5531. var listeners = this.listeners_[eventType] || [];
  5532. for (var i = 0; i < listeners.length; i++) {
  5533. if (listeners[i].callback === callback &&
  5534. (!context || context === listeners[i].context)) {
  5535. listeners.splice(i, 1);
  5536. return;
  5537. }
  5538. }
  5539. };
  5540. EventEmitter.prototype.validateEventType_ = function (eventType) {
  5541. util.assert(this.allowedEvents_.find(function (et) {
  5542. return et === eventType;
  5543. }), 'Unknown event: ' + eventType);
  5544. };
  5545. return EventEmitter;
  5546. }());
  5547. /**
  5548. * @license
  5549. * Copyright 2017 Google LLC
  5550. *
  5551. * Licensed under the Apache License, Version 2.0 (the "License");
  5552. * you may not use this file except in compliance with the License.
  5553. * You may obtain a copy of the License at
  5554. *
  5555. * http://www.apache.org/licenses/LICENSE-2.0
  5556. *
  5557. * Unless required by applicable law or agreed to in writing, software
  5558. * distributed under the License is distributed on an "AS IS" BASIS,
  5559. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5560. * See the License for the specific language governing permissions and
  5561. * limitations under the License.
  5562. */
  5563. /**
  5564. * Monitors online state (as reported by window.online/offline events).
  5565. *
  5566. * The expectation is that this could have many false positives (thinks we are online
  5567. * when we're not), but no false negatives. So we can safely use it to determine when
  5568. * we definitely cannot reach the internet.
  5569. */
  5570. var OnlineMonitor = /** @class */ (function (_super) {
  5571. tslib.__extends(OnlineMonitor, _super);
  5572. function OnlineMonitor() {
  5573. var _this = _super.call(this, ['online']) || this;
  5574. _this.online_ = true;
  5575. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  5576. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  5577. // It would seem that the 'online' event does not always fire consistently. So we disable it
  5578. // for Cordova.
  5579. if (typeof window !== 'undefined' &&
  5580. typeof window.addEventListener !== 'undefined' &&
  5581. !util.isMobileCordova()) {
  5582. window.addEventListener('online', function () {
  5583. if (!_this.online_) {
  5584. _this.online_ = true;
  5585. _this.trigger('online', true);
  5586. }
  5587. }, false);
  5588. window.addEventListener('offline', function () {
  5589. if (_this.online_) {
  5590. _this.online_ = false;
  5591. _this.trigger('online', false);
  5592. }
  5593. }, false);
  5594. }
  5595. return _this;
  5596. }
  5597. OnlineMonitor.getInstance = function () {
  5598. return new OnlineMonitor();
  5599. };
  5600. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  5601. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  5602. return [this.online_];
  5603. };
  5604. OnlineMonitor.prototype.currentlyOnline = function () {
  5605. return this.online_;
  5606. };
  5607. return OnlineMonitor;
  5608. }(EventEmitter));
  5609. /**
  5610. * @license
  5611. * Copyright 2017 Google LLC
  5612. *
  5613. * Licensed under the Apache License, Version 2.0 (the "License");
  5614. * you may not use this file except in compliance with the License.
  5615. * You may obtain a copy of the License at
  5616. *
  5617. * http://www.apache.org/licenses/LICENSE-2.0
  5618. *
  5619. * Unless required by applicable law or agreed to in writing, software
  5620. * distributed under the License is distributed on an "AS IS" BASIS,
  5621. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5622. * See the License for the specific language governing permissions and
  5623. * limitations under the License.
  5624. */
  5625. /** Maximum key depth. */
  5626. var MAX_PATH_DEPTH = 32;
  5627. /** Maximum number of (UTF8) bytes in a Firebase path. */
  5628. var MAX_PATH_LENGTH_BYTES = 768;
  5629. /**
  5630. * An immutable object representing a parsed path. It's immutable so that you
  5631. * can pass them around to other functions without worrying about them changing
  5632. * it.
  5633. */
  5634. var Path = /** @class */ (function () {
  5635. /**
  5636. * @param pathOrString - Path string to parse, or another path, or the raw
  5637. * tokens array
  5638. */
  5639. function Path(pathOrString, pieceNum) {
  5640. if (pieceNum === void 0) {
  5641. this.pieces_ = pathOrString.split('/');
  5642. // Remove empty pieces.
  5643. var copyTo = 0;
  5644. for (var i = 0; i < this.pieces_.length; i++) {
  5645. if (this.pieces_[i].length > 0) {
  5646. this.pieces_[copyTo] = this.pieces_[i];
  5647. copyTo++;
  5648. }
  5649. }
  5650. this.pieces_.length = copyTo;
  5651. this.pieceNum_ = 0;
  5652. }
  5653. else {
  5654. this.pieces_ = pathOrString;
  5655. this.pieceNum_ = pieceNum;
  5656. }
  5657. }
  5658. Path.prototype.toString = function () {
  5659. var pathString = '';
  5660. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  5661. if (this.pieces_[i] !== '') {
  5662. pathString += '/' + this.pieces_[i];
  5663. }
  5664. }
  5665. return pathString || '/';
  5666. };
  5667. return Path;
  5668. }());
  5669. function newEmptyPath() {
  5670. return new Path('');
  5671. }
  5672. function pathGetFront(path) {
  5673. if (path.pieceNum_ >= path.pieces_.length) {
  5674. return null;
  5675. }
  5676. return path.pieces_[path.pieceNum_];
  5677. }
  5678. /**
  5679. * @returns The number of segments in this path
  5680. */
  5681. function pathGetLength(path) {
  5682. return path.pieces_.length - path.pieceNum_;
  5683. }
  5684. function pathPopFront(path) {
  5685. var pieceNum = path.pieceNum_;
  5686. if (pieceNum < path.pieces_.length) {
  5687. pieceNum++;
  5688. }
  5689. return new Path(path.pieces_, pieceNum);
  5690. }
  5691. function pathGetBack(path) {
  5692. if (path.pieceNum_ < path.pieces_.length) {
  5693. return path.pieces_[path.pieces_.length - 1];
  5694. }
  5695. return null;
  5696. }
  5697. function pathToUrlEncodedString(path) {
  5698. var pathString = '';
  5699. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  5700. if (path.pieces_[i] !== '') {
  5701. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  5702. }
  5703. }
  5704. return pathString || '/';
  5705. }
  5706. /**
  5707. * Shallow copy of the parts of the path.
  5708. *
  5709. */
  5710. function pathSlice(path, begin) {
  5711. if (begin === void 0) { begin = 0; }
  5712. return path.pieces_.slice(path.pieceNum_ + begin);
  5713. }
  5714. function pathParent(path) {
  5715. if (path.pieceNum_ >= path.pieces_.length) {
  5716. return null;
  5717. }
  5718. var pieces = [];
  5719. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  5720. pieces.push(path.pieces_[i]);
  5721. }
  5722. return new Path(pieces, 0);
  5723. }
  5724. function pathChild(path, childPathObj) {
  5725. var pieces = [];
  5726. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  5727. pieces.push(path.pieces_[i]);
  5728. }
  5729. if (childPathObj instanceof Path) {
  5730. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  5731. pieces.push(childPathObj.pieces_[i]);
  5732. }
  5733. }
  5734. else {
  5735. var childPieces = childPathObj.split('/');
  5736. for (var i = 0; i < childPieces.length; i++) {
  5737. if (childPieces[i].length > 0) {
  5738. pieces.push(childPieces[i]);
  5739. }
  5740. }
  5741. }
  5742. return new Path(pieces, 0);
  5743. }
  5744. /**
  5745. * @returns True if there are no segments in this path
  5746. */
  5747. function pathIsEmpty(path) {
  5748. return path.pieceNum_ >= path.pieces_.length;
  5749. }
  5750. /**
  5751. * @returns The path from outerPath to innerPath
  5752. */
  5753. function newRelativePath(outerPath, innerPath) {
  5754. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  5755. if (outer === null) {
  5756. return innerPath;
  5757. }
  5758. else if (outer === inner) {
  5759. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  5760. }
  5761. else {
  5762. throw new Error('INTERNAL ERROR: innerPath (' +
  5763. innerPath +
  5764. ') is not within ' +
  5765. 'outerPath (' +
  5766. outerPath +
  5767. ')');
  5768. }
  5769. }
  5770. /**
  5771. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  5772. */
  5773. function pathCompare(left, right) {
  5774. var leftKeys = pathSlice(left, 0);
  5775. var rightKeys = pathSlice(right, 0);
  5776. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  5777. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  5778. if (cmp !== 0) {
  5779. return cmp;
  5780. }
  5781. }
  5782. if (leftKeys.length === rightKeys.length) {
  5783. return 0;
  5784. }
  5785. return leftKeys.length < rightKeys.length ? -1 : 1;
  5786. }
  5787. /**
  5788. * @returns true if paths are the same.
  5789. */
  5790. function pathEquals(path, other) {
  5791. if (pathGetLength(path) !== pathGetLength(other)) {
  5792. return false;
  5793. }
  5794. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  5795. if (path.pieces_[i] !== other.pieces_[j]) {
  5796. return false;
  5797. }
  5798. }
  5799. return true;
  5800. }
  5801. /**
  5802. * @returns True if this path is a parent of (or the same as) other
  5803. */
  5804. function pathContains(path, other) {
  5805. var i = path.pieceNum_;
  5806. var j = other.pieceNum_;
  5807. if (pathGetLength(path) > pathGetLength(other)) {
  5808. return false;
  5809. }
  5810. while (i < path.pieces_.length) {
  5811. if (path.pieces_[i] !== other.pieces_[j]) {
  5812. return false;
  5813. }
  5814. ++i;
  5815. ++j;
  5816. }
  5817. return true;
  5818. }
  5819. /**
  5820. * Dynamic (mutable) path used to count path lengths.
  5821. *
  5822. * This class is used to efficiently check paths for valid
  5823. * length (in UTF8 bytes) and depth (used in path validation).
  5824. *
  5825. * Throws Error exception if path is ever invalid.
  5826. *
  5827. * The definition of a path always begins with '/'.
  5828. */
  5829. var ValidationPath = /** @class */ (function () {
  5830. /**
  5831. * @param path - Initial Path.
  5832. * @param errorPrefix_ - Prefix for any error messages.
  5833. */
  5834. function ValidationPath(path, errorPrefix_) {
  5835. this.errorPrefix_ = errorPrefix_;
  5836. this.parts_ = pathSlice(path, 0);
  5837. /** Initialize to number of '/' chars needed in path. */
  5838. this.byteLength_ = Math.max(1, this.parts_.length);
  5839. for (var i = 0; i < this.parts_.length; i++) {
  5840. this.byteLength_ += util.stringLength(this.parts_[i]);
  5841. }
  5842. validationPathCheckValid(this);
  5843. }
  5844. return ValidationPath;
  5845. }());
  5846. function validationPathPush(validationPath, child) {
  5847. // Count the needed '/'
  5848. if (validationPath.parts_.length > 0) {
  5849. validationPath.byteLength_ += 1;
  5850. }
  5851. validationPath.parts_.push(child);
  5852. validationPath.byteLength_ += util.stringLength(child);
  5853. validationPathCheckValid(validationPath);
  5854. }
  5855. function validationPathPop(validationPath) {
  5856. var last = validationPath.parts_.pop();
  5857. validationPath.byteLength_ -= util.stringLength(last);
  5858. // Un-count the previous '/'
  5859. if (validationPath.parts_.length > 0) {
  5860. validationPath.byteLength_ -= 1;
  5861. }
  5862. }
  5863. function validationPathCheckValid(validationPath) {
  5864. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  5865. throw new Error(validationPath.errorPrefix_ +
  5866. 'has a key path longer than ' +
  5867. MAX_PATH_LENGTH_BYTES +
  5868. ' bytes (' +
  5869. validationPath.byteLength_ +
  5870. ').');
  5871. }
  5872. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  5873. throw new Error(validationPath.errorPrefix_ +
  5874. 'path specified exceeds the maximum depth that can be written (' +
  5875. MAX_PATH_DEPTH +
  5876. ') or object contains a cycle ' +
  5877. validationPathToErrorString(validationPath));
  5878. }
  5879. }
  5880. /**
  5881. * String for use in error messages - uses '.' notation for path.
  5882. */
  5883. function validationPathToErrorString(validationPath) {
  5884. if (validationPath.parts_.length === 0) {
  5885. return '';
  5886. }
  5887. return "in property '" + validationPath.parts_.join('.') + "'";
  5888. }
  5889. /**
  5890. * @license
  5891. * Copyright 2017 Google LLC
  5892. *
  5893. * Licensed under the Apache License, Version 2.0 (the "License");
  5894. * you may not use this file except in compliance with the License.
  5895. * You may obtain a copy of the License at
  5896. *
  5897. * http://www.apache.org/licenses/LICENSE-2.0
  5898. *
  5899. * Unless required by applicable law or agreed to in writing, software
  5900. * distributed under the License is distributed on an "AS IS" BASIS,
  5901. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5902. * See the License for the specific language governing permissions and
  5903. * limitations under the License.
  5904. */
  5905. var VisibilityMonitor = /** @class */ (function (_super) {
  5906. tslib.__extends(VisibilityMonitor, _super);
  5907. function VisibilityMonitor() {
  5908. var _this = _super.call(this, ['visible']) || this;
  5909. var hidden;
  5910. var visibilityChange;
  5911. if (typeof document !== 'undefined' &&
  5912. typeof document.addEventListener !== 'undefined') {
  5913. if (typeof document['hidden'] !== 'undefined') {
  5914. // Opera 12.10 and Firefox 18 and later support
  5915. visibilityChange = 'visibilitychange';
  5916. hidden = 'hidden';
  5917. }
  5918. else if (typeof document['mozHidden'] !== 'undefined') {
  5919. visibilityChange = 'mozvisibilitychange';
  5920. hidden = 'mozHidden';
  5921. }
  5922. else if (typeof document['msHidden'] !== 'undefined') {
  5923. visibilityChange = 'msvisibilitychange';
  5924. hidden = 'msHidden';
  5925. }
  5926. else if (typeof document['webkitHidden'] !== 'undefined') {
  5927. visibilityChange = 'webkitvisibilitychange';
  5928. hidden = 'webkitHidden';
  5929. }
  5930. }
  5931. // Initially, we always assume we are visible. This ensures that in browsers
  5932. // without page visibility support or in cases where we are never visible
  5933. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  5934. // reconnects
  5935. _this.visible_ = true;
  5936. if (visibilityChange) {
  5937. document.addEventListener(visibilityChange, function () {
  5938. var visible = !document[hidden];
  5939. if (visible !== _this.visible_) {
  5940. _this.visible_ = visible;
  5941. _this.trigger('visible', visible);
  5942. }
  5943. }, false);
  5944. }
  5945. return _this;
  5946. }
  5947. VisibilityMonitor.getInstance = function () {
  5948. return new VisibilityMonitor();
  5949. };
  5950. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  5951. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  5952. return [this.visible_];
  5953. };
  5954. return VisibilityMonitor;
  5955. }(EventEmitter));
  5956. /**
  5957. * @license
  5958. * Copyright 2017 Google LLC
  5959. *
  5960. * Licensed under the Apache License, Version 2.0 (the "License");
  5961. * you may not use this file except in compliance with the License.
  5962. * You may obtain a copy of the License at
  5963. *
  5964. * http://www.apache.org/licenses/LICENSE-2.0
  5965. *
  5966. * Unless required by applicable law or agreed to in writing, software
  5967. * distributed under the License is distributed on an "AS IS" BASIS,
  5968. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5969. * See the License for the specific language governing permissions and
  5970. * limitations under the License.
  5971. */
  5972. var RECONNECT_MIN_DELAY = 1000;
  5973. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  5974. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  5975. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  5976. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  5977. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  5978. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  5979. var INVALID_TOKEN_THRESHOLD = 3;
  5980. /**
  5981. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  5982. *
  5983. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  5984. * in quotes to make sure the closure compiler does not minify them.
  5985. */
  5986. var PersistentConnection = /** @class */ (function (_super) {
  5987. tslib.__extends(PersistentConnection, _super);
  5988. /**
  5989. * @param repoInfo_ - Data about the namespace we are connecting to
  5990. * @param applicationId_ - The Firebase App ID for this project
  5991. * @param onDataUpdate_ - A callback for new data from the server
  5992. */
  5993. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  5994. var _this = _super.call(this) || this;
  5995. _this.repoInfo_ = repoInfo_;
  5996. _this.applicationId_ = applicationId_;
  5997. _this.onDataUpdate_ = onDataUpdate_;
  5998. _this.onConnectStatus_ = onConnectStatus_;
  5999. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  6000. _this.authTokenProvider_ = authTokenProvider_;
  6001. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6002. _this.authOverride_ = authOverride_;
  6003. // Used for diagnostic logging.
  6004. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  6005. _this.log_ = logWrapper('p:' + _this.id + ':');
  6006. _this.interruptReasons_ = {};
  6007. _this.listens = new Map();
  6008. _this.outstandingPuts_ = [];
  6009. _this.outstandingGets_ = [];
  6010. _this.outstandingPutCount_ = 0;
  6011. _this.outstandingGetCount_ = 0;
  6012. _this.onDisconnectRequestQueue_ = [];
  6013. _this.connected_ = false;
  6014. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6015. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  6016. _this.securityDebugCallback_ = null;
  6017. _this.lastSessionId = null;
  6018. _this.establishConnectionTimer_ = null;
  6019. _this.visible_ = false;
  6020. // Before we get connected, we keep a queue of pending messages to send.
  6021. _this.requestCBHash_ = {};
  6022. _this.requestNumber_ = 0;
  6023. _this.realtime_ = null;
  6024. _this.authToken_ = null;
  6025. _this.appCheckToken_ = null;
  6026. _this.forceTokenRefresh_ = false;
  6027. _this.invalidAuthTokenCount_ = 0;
  6028. _this.invalidAppCheckTokenCount_ = 0;
  6029. _this.firstConnection_ = true;
  6030. _this.lastConnectionAttemptTime_ = null;
  6031. _this.lastConnectionEstablishedTime_ = null;
  6032. if (authOverride_ && !util.isNodeSdk()) {
  6033. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  6034. }
  6035. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  6036. if (repoInfo_.host.indexOf('fblocal') === -1) {
  6037. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  6038. }
  6039. return _this;
  6040. }
  6041. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  6042. var curReqNum = ++this.requestNumber_;
  6043. var msg = { r: curReqNum, a: action, b: body };
  6044. this.log_(util.stringify(msg));
  6045. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  6046. this.realtime_.sendRequest(msg);
  6047. if (onResponse) {
  6048. this.requestCBHash_[curReqNum] = onResponse;
  6049. }
  6050. };
  6051. PersistentConnection.prototype.get = function (query) {
  6052. this.initConnection_();
  6053. var deferred = new util.Deferred();
  6054. var request = {
  6055. p: query._path.toString(),
  6056. q: query._queryObject
  6057. };
  6058. var outstandingGet = {
  6059. action: 'g',
  6060. request: request,
  6061. onComplete: function (message) {
  6062. var payload = message['d'];
  6063. if (message['s'] === 'ok') {
  6064. deferred.resolve(payload);
  6065. }
  6066. else {
  6067. deferred.reject(payload);
  6068. }
  6069. }
  6070. };
  6071. this.outstandingGets_.push(outstandingGet);
  6072. this.outstandingGetCount_++;
  6073. var index = this.outstandingGets_.length - 1;
  6074. if (this.connected_) {
  6075. this.sendGet_(index);
  6076. }
  6077. return deferred.promise;
  6078. };
  6079. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6080. this.initConnection_();
  6081. var queryId = query._queryIdentifier;
  6082. var pathString = query._path.toString();
  6083. this.log_('Listen called for ' + pathString + ' ' + queryId);
  6084. if (!this.listens.has(pathString)) {
  6085. this.listens.set(pathString, new Map());
  6086. }
  6087. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  6088. util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  6089. var listenSpec = {
  6090. onComplete: onComplete,
  6091. hashFn: currentHashFn,
  6092. query: query,
  6093. tag: tag
  6094. };
  6095. this.listens.get(pathString).set(queryId, listenSpec);
  6096. if (this.connected_) {
  6097. this.sendListen_(listenSpec);
  6098. }
  6099. };
  6100. PersistentConnection.prototype.sendGet_ = function (index) {
  6101. var _this = this;
  6102. var get = this.outstandingGets_[index];
  6103. this.sendRequest('g', get.request, function (message) {
  6104. delete _this.outstandingGets_[index];
  6105. _this.outstandingGetCount_--;
  6106. if (_this.outstandingGetCount_ === 0) {
  6107. _this.outstandingGets_ = [];
  6108. }
  6109. if (get.onComplete) {
  6110. get.onComplete(message);
  6111. }
  6112. });
  6113. };
  6114. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  6115. var _this = this;
  6116. var query = listenSpec.query;
  6117. var pathString = query._path.toString();
  6118. var queryId = query._queryIdentifier;
  6119. this.log_('Listen on ' + pathString + ' for ' + queryId);
  6120. var req = { /*path*/ p: pathString };
  6121. var action = 'q';
  6122. // Only bother to send query if it's non-default.
  6123. if (listenSpec.tag) {
  6124. req['q'] = query._queryObject;
  6125. req['t'] = listenSpec.tag;
  6126. }
  6127. req[ /*hash*/'h'] = listenSpec.hashFn();
  6128. this.sendRequest(action, req, function (message) {
  6129. var payload = message[ /*data*/'d'];
  6130. var status = message[ /*status*/'s'];
  6131. // print warnings in any case...
  6132. PersistentConnection.warnOnListenWarnings_(payload, query);
  6133. var currentListenSpec = _this.listens.get(pathString) &&
  6134. _this.listens.get(pathString).get(queryId);
  6135. // only trigger actions if the listen hasn't been removed and readded
  6136. if (currentListenSpec === listenSpec) {
  6137. _this.log_('listen response', message);
  6138. if (status !== 'ok') {
  6139. _this.removeListen_(pathString, queryId);
  6140. }
  6141. if (listenSpec.onComplete) {
  6142. listenSpec.onComplete(status, payload);
  6143. }
  6144. }
  6145. });
  6146. };
  6147. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  6148. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  6149. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6150. var warnings = util.safeGet(payload, 'w');
  6151. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  6152. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  6153. var indexPath = query._path.toString();
  6154. warn$1("Using an unspecified index. Your data will be downloaded and " +
  6155. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  6156. "".concat(indexPath, " to your security rules for better performance."));
  6157. }
  6158. }
  6159. };
  6160. PersistentConnection.prototype.refreshAuthToken = function (token) {
  6161. this.authToken_ = token;
  6162. this.log_('Auth token refreshed');
  6163. if (this.authToken_) {
  6164. this.tryAuth();
  6165. }
  6166. else {
  6167. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  6168. //the credential so we dont become authenticated next time we connect.
  6169. if (this.connected_) {
  6170. this.sendRequest('unauth', {}, function () { });
  6171. }
  6172. }
  6173. this.reduceReconnectDelayIfAdminCredential_(token);
  6174. };
  6175. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  6176. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  6177. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  6178. var isFirebaseSecret = credential && credential.length === 40;
  6179. if (isFirebaseSecret || util.isAdmin(credential)) {
  6180. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  6181. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  6182. }
  6183. };
  6184. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  6185. this.appCheckToken_ = token;
  6186. this.log_('App check token refreshed');
  6187. if (this.appCheckToken_) {
  6188. this.tryAppCheck();
  6189. }
  6190. else {
  6191. //If we're connected we want to let the server know to unauthenticate us.
  6192. //If we're not connected, simply delete the credential so we dont become
  6193. // authenticated next time we connect.
  6194. if (this.connected_) {
  6195. this.sendRequest('unappeck', {}, function () { });
  6196. }
  6197. }
  6198. };
  6199. /**
  6200. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  6201. * a auth revoked (the connection is closed).
  6202. */
  6203. PersistentConnection.prototype.tryAuth = function () {
  6204. var _this = this;
  6205. if (this.connected_ && this.authToken_) {
  6206. var token_1 = this.authToken_;
  6207. var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
  6208. var requestData = { cred: token_1 };
  6209. if (this.authOverride_ === null) {
  6210. requestData['noauth'] = true;
  6211. }
  6212. else if (typeof this.authOverride_ === 'object') {
  6213. requestData['authvar'] = this.authOverride_;
  6214. }
  6215. this.sendRequest(authMethod, requestData, function (res) {
  6216. var status = res[ /*status*/'s'];
  6217. var data = res[ /*data*/'d'] || 'error';
  6218. if (_this.authToken_ === token_1) {
  6219. if (status === 'ok') {
  6220. _this.invalidAuthTokenCount_ = 0;
  6221. }
  6222. else {
  6223. // Triggers reconnect and force refresh for auth token
  6224. _this.onAuthRevoked_(status, data);
  6225. }
  6226. }
  6227. });
  6228. }
  6229. };
  6230. /**
  6231. * Attempts to authenticate with the given token. If the authentication
  6232. * attempt fails, it's triggered like the token was revoked (the connection is
  6233. * closed).
  6234. */
  6235. PersistentConnection.prototype.tryAppCheck = function () {
  6236. var _this = this;
  6237. if (this.connected_ && this.appCheckToken_) {
  6238. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  6239. var status = res[ /*status*/'s'];
  6240. var data = res[ /*data*/'d'] || 'error';
  6241. if (status === 'ok') {
  6242. _this.invalidAppCheckTokenCount_ = 0;
  6243. }
  6244. else {
  6245. _this.onAppCheckRevoked_(status, data);
  6246. }
  6247. });
  6248. }
  6249. };
  6250. /**
  6251. * @inheritDoc
  6252. */
  6253. PersistentConnection.prototype.unlisten = function (query, tag) {
  6254. var pathString = query._path.toString();
  6255. var queryId = query._queryIdentifier;
  6256. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  6257. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  6258. var listen = this.removeListen_(pathString, queryId);
  6259. if (listen && this.connected_) {
  6260. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  6261. }
  6262. };
  6263. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  6264. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  6265. var req = { /*path*/ p: pathString };
  6266. var action = 'n';
  6267. // Only bother sending queryId if it's non-default.
  6268. if (tag) {
  6269. req['q'] = queryObj;
  6270. req['t'] = tag;
  6271. }
  6272. this.sendRequest(action, req);
  6273. };
  6274. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  6275. this.initConnection_();
  6276. if (this.connected_) {
  6277. this.sendOnDisconnect_('o', pathString, data, onComplete);
  6278. }
  6279. else {
  6280. this.onDisconnectRequestQueue_.push({
  6281. pathString: pathString,
  6282. action: 'o',
  6283. data: data,
  6284. onComplete: onComplete
  6285. });
  6286. }
  6287. };
  6288. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  6289. this.initConnection_();
  6290. if (this.connected_) {
  6291. this.sendOnDisconnect_('om', pathString, data, onComplete);
  6292. }
  6293. else {
  6294. this.onDisconnectRequestQueue_.push({
  6295. pathString: pathString,
  6296. action: 'om',
  6297. data: data,
  6298. onComplete: onComplete
  6299. });
  6300. }
  6301. };
  6302. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  6303. this.initConnection_();
  6304. if (this.connected_) {
  6305. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  6306. }
  6307. else {
  6308. this.onDisconnectRequestQueue_.push({
  6309. pathString: pathString,
  6310. action: 'oc',
  6311. data: null,
  6312. onComplete: onComplete
  6313. });
  6314. }
  6315. };
  6316. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  6317. var request = { /*path*/ p: pathString, /*data*/ d: data };
  6318. this.log_('onDisconnect ' + action, request);
  6319. this.sendRequest(action, request, function (response) {
  6320. if (onComplete) {
  6321. setTimeout(function () {
  6322. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  6323. }, Math.floor(0));
  6324. }
  6325. });
  6326. };
  6327. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  6328. this.putInternal('p', pathString, data, onComplete, hash);
  6329. };
  6330. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  6331. this.putInternal('m', pathString, data, onComplete, hash);
  6332. };
  6333. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  6334. this.initConnection_();
  6335. var request = {
  6336. /*path*/ p: pathString,
  6337. /*data*/ d: data
  6338. };
  6339. if (hash !== undefined) {
  6340. request[ /*hash*/'h'] = hash;
  6341. }
  6342. // TODO: Only keep track of the most recent put for a given path?
  6343. this.outstandingPuts_.push({
  6344. action: action,
  6345. request: request,
  6346. onComplete: onComplete
  6347. });
  6348. this.outstandingPutCount_++;
  6349. var index = this.outstandingPuts_.length - 1;
  6350. if (this.connected_) {
  6351. this.sendPut_(index);
  6352. }
  6353. else {
  6354. this.log_('Buffering put: ' + pathString);
  6355. }
  6356. };
  6357. PersistentConnection.prototype.sendPut_ = function (index) {
  6358. var _this = this;
  6359. var action = this.outstandingPuts_[index].action;
  6360. var request = this.outstandingPuts_[index].request;
  6361. var onComplete = this.outstandingPuts_[index].onComplete;
  6362. this.outstandingPuts_[index].queued = this.connected_;
  6363. this.sendRequest(action, request, function (message) {
  6364. _this.log_(action + ' response', message);
  6365. delete _this.outstandingPuts_[index];
  6366. _this.outstandingPutCount_--;
  6367. // Clean up array occasionally.
  6368. if (_this.outstandingPutCount_ === 0) {
  6369. _this.outstandingPuts_ = [];
  6370. }
  6371. if (onComplete) {
  6372. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  6373. }
  6374. });
  6375. };
  6376. PersistentConnection.prototype.reportStats = function (stats) {
  6377. var _this = this;
  6378. // If we're not connected, we just drop the stats.
  6379. if (this.connected_) {
  6380. var request = { /*counters*/ c: stats };
  6381. this.log_('reportStats', request);
  6382. this.sendRequest(/*stats*/ 's', request, function (result) {
  6383. var status = result[ /*status*/'s'];
  6384. if (status !== 'ok') {
  6385. var errorReason = result[ /* data */'d'];
  6386. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  6387. }
  6388. });
  6389. }
  6390. };
  6391. PersistentConnection.prototype.onDataMessage_ = function (message) {
  6392. if ('r' in message) {
  6393. // this is a response
  6394. this.log_('from server: ' + util.stringify(message));
  6395. var reqNum = message['r'];
  6396. var onResponse = this.requestCBHash_[reqNum];
  6397. if (onResponse) {
  6398. delete this.requestCBHash_[reqNum];
  6399. onResponse(message[ /*body*/'b']);
  6400. }
  6401. }
  6402. else if ('error' in message) {
  6403. throw 'A server-side error has occurred: ' + message['error'];
  6404. }
  6405. else if ('a' in message) {
  6406. // a and b are action and body, respectively
  6407. this.onDataPush_(message['a'], message['b']);
  6408. }
  6409. };
  6410. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  6411. this.log_('handleServerMessage', action, body);
  6412. if (action === 'd') {
  6413. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  6414. /*isMerge*/ false, body['t']);
  6415. }
  6416. else if (action === 'm') {
  6417. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  6418. /*isMerge=*/ true, body['t']);
  6419. }
  6420. else if (action === 'c') {
  6421. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  6422. }
  6423. else if (action === 'ac') {
  6424. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  6425. }
  6426. else if (action === 'apc') {
  6427. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  6428. }
  6429. else if (action === 'sd') {
  6430. this.onSecurityDebugPacket_(body);
  6431. }
  6432. else {
  6433. error('Unrecognized action received from server: ' +
  6434. util.stringify(action) +
  6435. '\nAre you using the latest client?');
  6436. }
  6437. };
  6438. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  6439. this.log_('connection ready');
  6440. this.connected_ = true;
  6441. this.lastConnectionEstablishedTime_ = new Date().getTime();
  6442. this.handleTimestamp_(timestamp);
  6443. this.lastSessionId = sessionId;
  6444. if (this.firstConnection_) {
  6445. this.sendConnectStats_();
  6446. }
  6447. this.restoreState_();
  6448. this.firstConnection_ = false;
  6449. this.onConnectStatus_(true);
  6450. };
  6451. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  6452. var _this = this;
  6453. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  6454. if (this.establishConnectionTimer_) {
  6455. clearTimeout(this.establishConnectionTimer_);
  6456. }
  6457. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  6458. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  6459. this.establishConnectionTimer_ = setTimeout(function () {
  6460. _this.establishConnectionTimer_ = null;
  6461. _this.establishConnection_();
  6462. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6463. }, Math.floor(timeout));
  6464. };
  6465. PersistentConnection.prototype.initConnection_ = function () {
  6466. if (!this.realtime_ && this.firstConnection_) {
  6467. this.scheduleConnect_(0);
  6468. }
  6469. };
  6470. PersistentConnection.prototype.onVisible_ = function (visible) {
  6471. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  6472. if (visible &&
  6473. !this.visible_ &&
  6474. this.reconnectDelay_ === this.maxReconnectDelay_) {
  6475. this.log_('Window became visible. Reducing delay.');
  6476. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6477. if (!this.realtime_) {
  6478. this.scheduleConnect_(0);
  6479. }
  6480. }
  6481. this.visible_ = visible;
  6482. };
  6483. PersistentConnection.prototype.onOnline_ = function (online) {
  6484. if (online) {
  6485. this.log_('Browser went online.');
  6486. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6487. if (!this.realtime_) {
  6488. this.scheduleConnect_(0);
  6489. }
  6490. }
  6491. else {
  6492. this.log_('Browser went offline. Killing connection.');
  6493. if (this.realtime_) {
  6494. this.realtime_.close();
  6495. }
  6496. }
  6497. };
  6498. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  6499. this.log_('data client disconnected');
  6500. this.connected_ = false;
  6501. this.realtime_ = null;
  6502. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  6503. this.cancelSentTransactions_();
  6504. // Clear out the pending requests.
  6505. this.requestCBHash_ = {};
  6506. if (this.shouldReconnect_()) {
  6507. if (!this.visible_) {
  6508. this.log_("Window isn't visible. Delaying reconnect.");
  6509. this.reconnectDelay_ = this.maxReconnectDelay_;
  6510. this.lastConnectionAttemptTime_ = new Date().getTime();
  6511. }
  6512. else if (this.lastConnectionEstablishedTime_) {
  6513. // If we've been connected long enough, reset reconnect delay to minimum.
  6514. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  6515. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  6516. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6517. }
  6518. this.lastConnectionEstablishedTime_ = null;
  6519. }
  6520. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  6521. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  6522. reconnectDelay = Math.random() * reconnectDelay;
  6523. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  6524. this.scheduleConnect_(reconnectDelay);
  6525. // Adjust reconnect delay for next time.
  6526. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  6527. }
  6528. this.onConnectStatus_(false);
  6529. };
  6530. PersistentConnection.prototype.establishConnection_ = function () {
  6531. return tslib.__awaiter(this, void 0, void 0, function () {
  6532. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  6533. var _this = this;
  6534. return tslib.__generator(this, function (_b) {
  6535. switch (_b.label) {
  6536. case 0:
  6537. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  6538. this.log_('Making a connection attempt');
  6539. this.lastConnectionAttemptTime_ = new Date().getTime();
  6540. this.lastConnectionEstablishedTime_ = null;
  6541. onDataMessage = this.onDataMessage_.bind(this);
  6542. onReady = this.onReady_.bind(this);
  6543. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  6544. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  6545. lastSessionId = this.lastSessionId;
  6546. canceled_1 = false;
  6547. connection_1 = null;
  6548. closeFn = function () {
  6549. if (connection_1) {
  6550. connection_1.close();
  6551. }
  6552. else {
  6553. canceled_1 = true;
  6554. onDisconnect_1();
  6555. }
  6556. };
  6557. sendRequestFn = function (msg) {
  6558. util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
  6559. connection_1.sendRequest(msg);
  6560. };
  6561. this.realtime_ = {
  6562. close: closeFn,
  6563. sendRequest: sendRequestFn
  6564. };
  6565. forceRefresh = this.forceTokenRefresh_;
  6566. this.forceTokenRefresh_ = false;
  6567. _b.label = 1;
  6568. case 1:
  6569. _b.trys.push([1, 3, , 4]);
  6570. return [4 /*yield*/, Promise.all([
  6571. this.authTokenProvider_.getToken(forceRefresh),
  6572. this.appCheckTokenProvider_.getToken(forceRefresh)
  6573. ])];
  6574. case 2:
  6575. _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  6576. if (!canceled_1) {
  6577. log('getToken() completed. Creating connection.');
  6578. this.authToken_ = authToken && authToken.accessToken;
  6579. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  6580. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  6581. /* onKill= */ function (reason) {
  6582. warn$1(reason + ' (' + _this.repoInfo_.toString() + ')');
  6583. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  6584. }, lastSessionId);
  6585. }
  6586. else {
  6587. log('getToken() completed but was canceled');
  6588. }
  6589. return [3 /*break*/, 4];
  6590. case 3:
  6591. error_1 = _b.sent();
  6592. this.log_('Failed to get token: ' + error_1);
  6593. if (!canceled_1) {
  6594. if (this.repoInfo_.nodeAdmin) {
  6595. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  6596. // But getToken() may also just have temporarily failed, so we still want to
  6597. // continue retrying.
  6598. warn$1(error_1);
  6599. }
  6600. closeFn();
  6601. }
  6602. return [3 /*break*/, 4];
  6603. case 4: return [2 /*return*/];
  6604. }
  6605. });
  6606. });
  6607. };
  6608. PersistentConnection.prototype.interrupt = function (reason) {
  6609. log('Interrupting connection for reason: ' + reason);
  6610. this.interruptReasons_[reason] = true;
  6611. if (this.realtime_) {
  6612. this.realtime_.close();
  6613. }
  6614. else {
  6615. if (this.establishConnectionTimer_) {
  6616. clearTimeout(this.establishConnectionTimer_);
  6617. this.establishConnectionTimer_ = null;
  6618. }
  6619. if (this.connected_) {
  6620. this.onRealtimeDisconnect_();
  6621. }
  6622. }
  6623. };
  6624. PersistentConnection.prototype.resume = function (reason) {
  6625. log('Resuming connection for reason: ' + reason);
  6626. delete this.interruptReasons_[reason];
  6627. if (util.isEmpty(this.interruptReasons_)) {
  6628. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  6629. if (!this.realtime_) {
  6630. this.scheduleConnect_(0);
  6631. }
  6632. }
  6633. };
  6634. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  6635. var delta = timestamp - new Date().getTime();
  6636. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  6637. };
  6638. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  6639. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  6640. var put = this.outstandingPuts_[i];
  6641. if (put && /*hash*/ 'h' in put.request && put.queued) {
  6642. if (put.onComplete) {
  6643. put.onComplete('disconnect');
  6644. }
  6645. delete this.outstandingPuts_[i];
  6646. this.outstandingPutCount_--;
  6647. }
  6648. }
  6649. // Clean up array occasionally.
  6650. if (this.outstandingPutCount_ === 0) {
  6651. this.outstandingPuts_ = [];
  6652. }
  6653. };
  6654. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  6655. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  6656. var queryId;
  6657. if (!query) {
  6658. queryId = 'default';
  6659. }
  6660. else {
  6661. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  6662. }
  6663. var listen = this.removeListen_(pathString, queryId);
  6664. if (listen && listen.onComplete) {
  6665. listen.onComplete('permission_denied');
  6666. }
  6667. };
  6668. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  6669. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  6670. var listen;
  6671. if (this.listens.has(normalizedPathString)) {
  6672. var map = this.listens.get(normalizedPathString);
  6673. listen = map.get(queryId);
  6674. map.delete(queryId);
  6675. if (map.size === 0) {
  6676. this.listens.delete(normalizedPathString);
  6677. }
  6678. }
  6679. else {
  6680. // all listens for this path has already been removed
  6681. listen = undefined;
  6682. }
  6683. return listen;
  6684. };
  6685. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  6686. log('Auth token revoked: ' + statusCode + '/' + explanation);
  6687. this.authToken_ = null;
  6688. this.forceTokenRefresh_ = true;
  6689. this.realtime_.close();
  6690. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  6691. // We'll wait a couple times before logging the warning / increasing the
  6692. // retry period since oauth tokens will report as "invalid" if they're
  6693. // just expired. Plus there may be transient issues that resolve themselves.
  6694. this.invalidAuthTokenCount_++;
  6695. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  6696. // Set a long reconnect delay because recovery is unlikely
  6697. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  6698. // Notify the auth token provider that the token is invalid, which will log
  6699. // a warning
  6700. this.authTokenProvider_.notifyForInvalidToken();
  6701. }
  6702. }
  6703. };
  6704. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  6705. log('App check token revoked: ' + statusCode + '/' + explanation);
  6706. this.appCheckToken_ = null;
  6707. this.forceTokenRefresh_ = true;
  6708. // Note: We don't close the connection as the developer may not have
  6709. // enforcement enabled. The backend closes connections with enforcements.
  6710. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  6711. // We'll wait a couple times before logging the warning / increasing the
  6712. // retry period since oauth tokens will report as "invalid" if they're
  6713. // just expired. Plus there may be transient issues that resolve themselves.
  6714. this.invalidAppCheckTokenCount_++;
  6715. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  6716. this.appCheckTokenProvider_.notifyForInvalidToken();
  6717. }
  6718. }
  6719. };
  6720. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  6721. if (this.securityDebugCallback_) {
  6722. this.securityDebugCallback_(body);
  6723. }
  6724. else {
  6725. if ('msg' in body) {
  6726. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  6727. }
  6728. }
  6729. };
  6730. PersistentConnection.prototype.restoreState_ = function () {
  6731. var e_1, _a, e_2, _b;
  6732. //Re-authenticate ourselves if we have a credential stored.
  6733. this.tryAuth();
  6734. this.tryAppCheck();
  6735. try {
  6736. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  6737. // make sure to send listens before puts.
  6738. for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  6739. var queries = _d.value;
  6740. try {
  6741. for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  6742. var listenSpec = _f.value;
  6743. this.sendListen_(listenSpec);
  6744. }
  6745. }
  6746. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  6747. finally {
  6748. try {
  6749. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  6750. }
  6751. finally { if (e_2) throw e_2.error; }
  6752. }
  6753. }
  6754. }
  6755. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  6756. finally {
  6757. try {
  6758. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  6759. }
  6760. finally { if (e_1) throw e_1.error; }
  6761. }
  6762. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  6763. if (this.outstandingPuts_[i]) {
  6764. this.sendPut_(i);
  6765. }
  6766. }
  6767. while (this.onDisconnectRequestQueue_.length) {
  6768. var request = this.onDisconnectRequestQueue_.shift();
  6769. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  6770. }
  6771. for (var i = 0; i < this.outstandingGets_.length; i++) {
  6772. if (this.outstandingGets_[i]) {
  6773. this.sendGet_(i);
  6774. }
  6775. }
  6776. };
  6777. /**
  6778. * Sends client stats for first connection
  6779. */
  6780. PersistentConnection.prototype.sendConnectStats_ = function () {
  6781. var stats = {};
  6782. var clientName = 'js';
  6783. if (util.isNodeSdk()) {
  6784. if (this.repoInfo_.nodeAdmin) {
  6785. clientName = 'admin_node';
  6786. }
  6787. else {
  6788. clientName = 'node';
  6789. }
  6790. }
  6791. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  6792. if (util.isMobileCordova()) {
  6793. stats['framework.cordova'] = 1;
  6794. }
  6795. else if (util.isReactNative()) {
  6796. stats['framework.reactnative'] = 1;
  6797. }
  6798. this.reportStats(stats);
  6799. };
  6800. PersistentConnection.prototype.shouldReconnect_ = function () {
  6801. var online = OnlineMonitor.getInstance().currentlyOnline();
  6802. return util.isEmpty(this.interruptReasons_) && online;
  6803. };
  6804. PersistentConnection.nextPersistentConnectionId_ = 0;
  6805. /**
  6806. * Counter for number of connections created. Mainly used for tagging in the logs
  6807. */
  6808. PersistentConnection.nextConnectionId_ = 0;
  6809. return PersistentConnection;
  6810. }(ServerActions));
  6811. /**
  6812. * @license
  6813. * Copyright 2017 Google LLC
  6814. *
  6815. * Licensed under the Apache License, Version 2.0 (the "License");
  6816. * you may not use this file except in compliance with the License.
  6817. * You may obtain a copy of the License at
  6818. *
  6819. * http://www.apache.org/licenses/LICENSE-2.0
  6820. *
  6821. * Unless required by applicable law or agreed to in writing, software
  6822. * distributed under the License is distributed on an "AS IS" BASIS,
  6823. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6824. * See the License for the specific language governing permissions and
  6825. * limitations under the License.
  6826. */
  6827. var NamedNode = /** @class */ (function () {
  6828. function NamedNode(name, node) {
  6829. this.name = name;
  6830. this.node = node;
  6831. }
  6832. NamedNode.Wrap = function (name, node) {
  6833. return new NamedNode(name, node);
  6834. };
  6835. return NamedNode;
  6836. }());
  6837. /**
  6838. * @license
  6839. * Copyright 2017 Google LLC
  6840. *
  6841. * Licensed under the Apache License, Version 2.0 (the "License");
  6842. * you may not use this file except in compliance with the License.
  6843. * You may obtain a copy of the License at
  6844. *
  6845. * http://www.apache.org/licenses/LICENSE-2.0
  6846. *
  6847. * Unless required by applicable law or agreed to in writing, software
  6848. * distributed under the License is distributed on an "AS IS" BASIS,
  6849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6850. * See the License for the specific language governing permissions and
  6851. * limitations under the License.
  6852. */
  6853. var Index = /** @class */ (function () {
  6854. function Index() {
  6855. }
  6856. /**
  6857. * @returns A standalone comparison function for
  6858. * this index
  6859. */
  6860. Index.prototype.getCompare = function () {
  6861. return this.compare.bind(this);
  6862. };
  6863. /**
  6864. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  6865. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  6866. *
  6867. *
  6868. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  6869. */
  6870. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  6871. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  6872. var newWrapped = new NamedNode(MIN_NAME, newNode);
  6873. return this.compare(oldWrapped, newWrapped) !== 0;
  6874. };
  6875. /**
  6876. * @returns a node wrapper that will sort equal to or less than
  6877. * any other node wrapper, using this index
  6878. */
  6879. Index.prototype.minPost = function () {
  6880. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6881. return NamedNode.MIN;
  6882. };
  6883. return Index;
  6884. }());
  6885. /**
  6886. * @license
  6887. * Copyright 2017 Google LLC
  6888. *
  6889. * Licensed under the Apache License, Version 2.0 (the "License");
  6890. * you may not use this file except in compliance with the License.
  6891. * You may obtain a copy of the License at
  6892. *
  6893. * http://www.apache.org/licenses/LICENSE-2.0
  6894. *
  6895. * Unless required by applicable law or agreed to in writing, software
  6896. * distributed under the License is distributed on an "AS IS" BASIS,
  6897. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6898. * See the License for the specific language governing permissions and
  6899. * limitations under the License.
  6900. */
  6901. var __EMPTY_NODE;
  6902. var KeyIndex = /** @class */ (function (_super) {
  6903. tslib.__extends(KeyIndex, _super);
  6904. function KeyIndex() {
  6905. return _super !== null && _super.apply(this, arguments) || this;
  6906. }
  6907. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  6908. get: function () {
  6909. return __EMPTY_NODE;
  6910. },
  6911. set: function (val) {
  6912. __EMPTY_NODE = val;
  6913. },
  6914. enumerable: false,
  6915. configurable: true
  6916. });
  6917. KeyIndex.prototype.compare = function (a, b) {
  6918. return nameCompare(a.name, b.name);
  6919. };
  6920. KeyIndex.prototype.isDefinedOn = function (node) {
  6921. // We could probably return true here (since every node has a key), but it's never called
  6922. // so just leaving unimplemented for now.
  6923. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  6924. };
  6925. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6926. return false; // The key for a node never changes.
  6927. };
  6928. KeyIndex.prototype.minPost = function () {
  6929. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6930. return NamedNode.MIN;
  6931. };
  6932. KeyIndex.prototype.maxPost = function () {
  6933. // TODO: This should really be created once and cached in a static property, but
  6934. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  6935. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  6936. };
  6937. KeyIndex.prototype.makePost = function (indexValue, name) {
  6938. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  6939. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  6940. return new NamedNode(indexValue, __EMPTY_NODE);
  6941. };
  6942. /**
  6943. * @returns String representation for inclusion in a query spec
  6944. */
  6945. KeyIndex.prototype.toString = function () {
  6946. return '.key';
  6947. };
  6948. return KeyIndex;
  6949. }(Index));
  6950. var KEY_INDEX = new KeyIndex();
  6951. /**
  6952. * @license
  6953. * Copyright 2017 Google LLC
  6954. *
  6955. * Licensed under the Apache License, Version 2.0 (the "License");
  6956. * you may not use this file except in compliance with the License.
  6957. * You may obtain a copy of the License at
  6958. *
  6959. * http://www.apache.org/licenses/LICENSE-2.0
  6960. *
  6961. * Unless required by applicable law or agreed to in writing, software
  6962. * distributed under the License is distributed on an "AS IS" BASIS,
  6963. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6964. * See the License for the specific language governing permissions and
  6965. * limitations under the License.
  6966. */
  6967. /**
  6968. * An iterator over an LLRBNode.
  6969. */
  6970. var SortedMapIterator = /** @class */ (function () {
  6971. /**
  6972. * @param node - Node to iterate.
  6973. * @param isReverse_ - Whether or not to iterate in reverse
  6974. */
  6975. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  6976. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  6977. this.isReverse_ = isReverse_;
  6978. this.resultGenerator_ = resultGenerator_;
  6979. this.nodeStack_ = [];
  6980. var cmp = 1;
  6981. while (!node.isEmpty()) {
  6982. node = node;
  6983. cmp = startKey ? comparator(node.key, startKey) : 1;
  6984. // flip the comparison if we're going in reverse
  6985. if (isReverse_) {
  6986. cmp *= -1;
  6987. }
  6988. if (cmp < 0) {
  6989. // This node is less than our start key. ignore it
  6990. if (this.isReverse_) {
  6991. node = node.left;
  6992. }
  6993. else {
  6994. node = node.right;
  6995. }
  6996. }
  6997. else if (cmp === 0) {
  6998. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  6999. this.nodeStack_.push(node);
  7000. break;
  7001. }
  7002. else {
  7003. // This node is greater than our start key, add it to the stack and move to the next one
  7004. this.nodeStack_.push(node);
  7005. if (this.isReverse_) {
  7006. node = node.right;
  7007. }
  7008. else {
  7009. node = node.left;
  7010. }
  7011. }
  7012. }
  7013. }
  7014. SortedMapIterator.prototype.getNext = function () {
  7015. if (this.nodeStack_.length === 0) {
  7016. return null;
  7017. }
  7018. var node = this.nodeStack_.pop();
  7019. var result;
  7020. if (this.resultGenerator_) {
  7021. result = this.resultGenerator_(node.key, node.value);
  7022. }
  7023. else {
  7024. result = { key: node.key, value: node.value };
  7025. }
  7026. if (this.isReverse_) {
  7027. node = node.left;
  7028. while (!node.isEmpty()) {
  7029. this.nodeStack_.push(node);
  7030. node = node.right;
  7031. }
  7032. }
  7033. else {
  7034. node = node.right;
  7035. while (!node.isEmpty()) {
  7036. this.nodeStack_.push(node);
  7037. node = node.left;
  7038. }
  7039. }
  7040. return result;
  7041. };
  7042. SortedMapIterator.prototype.hasNext = function () {
  7043. return this.nodeStack_.length > 0;
  7044. };
  7045. SortedMapIterator.prototype.peek = function () {
  7046. if (this.nodeStack_.length === 0) {
  7047. return null;
  7048. }
  7049. var node = this.nodeStack_[this.nodeStack_.length - 1];
  7050. if (this.resultGenerator_) {
  7051. return this.resultGenerator_(node.key, node.value);
  7052. }
  7053. else {
  7054. return { key: node.key, value: node.value };
  7055. }
  7056. };
  7057. return SortedMapIterator;
  7058. }());
  7059. /**
  7060. * Represents a node in a Left-leaning Red-Black tree.
  7061. */
  7062. var LLRBNode = /** @class */ (function () {
  7063. /**
  7064. * @param key - Key associated with this node.
  7065. * @param value - Value associated with this node.
  7066. * @param color - Whether this node is red.
  7067. * @param left - Left child.
  7068. * @param right - Right child.
  7069. */
  7070. function LLRBNode(key, value, color, left, right) {
  7071. this.key = key;
  7072. this.value = value;
  7073. this.color = color != null ? color : LLRBNode.RED;
  7074. this.left =
  7075. left != null ? left : SortedMap.EMPTY_NODE;
  7076. this.right =
  7077. right != null ? right : SortedMap.EMPTY_NODE;
  7078. }
  7079. /**
  7080. * Returns a copy of the current node, optionally replacing pieces of it.
  7081. *
  7082. * @param key - New key for the node, or null.
  7083. * @param value - New value for the node, or null.
  7084. * @param color - New color for the node, or null.
  7085. * @param left - New left child for the node, or null.
  7086. * @param right - New right child for the node, or null.
  7087. * @returns The node copy.
  7088. */
  7089. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  7090. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  7091. };
  7092. /**
  7093. * @returns The total number of nodes in the tree.
  7094. */
  7095. LLRBNode.prototype.count = function () {
  7096. return this.left.count() + 1 + this.right.count();
  7097. };
  7098. /**
  7099. * @returns True if the tree is empty.
  7100. */
  7101. LLRBNode.prototype.isEmpty = function () {
  7102. return false;
  7103. };
  7104. /**
  7105. * Traverses the tree in key order and calls the specified action function
  7106. * for each node.
  7107. *
  7108. * @param action - Callback function to be called for each
  7109. * node. If it returns true, traversal is aborted.
  7110. * @returns The first truthy value returned by action, or the last falsey
  7111. * value returned by action
  7112. */
  7113. LLRBNode.prototype.inorderTraversal = function (action) {
  7114. return (this.left.inorderTraversal(action) ||
  7115. !!action(this.key, this.value) ||
  7116. this.right.inorderTraversal(action));
  7117. };
  7118. /**
  7119. * Traverses the tree in reverse key order and calls the specified action function
  7120. * for each node.
  7121. *
  7122. * @param action - Callback function to be called for each
  7123. * node. If it returns true, traversal is aborted.
  7124. * @returns True if traversal was aborted.
  7125. */
  7126. LLRBNode.prototype.reverseTraversal = function (action) {
  7127. return (this.right.reverseTraversal(action) ||
  7128. action(this.key, this.value) ||
  7129. this.left.reverseTraversal(action));
  7130. };
  7131. /**
  7132. * @returns The minimum node in the tree.
  7133. */
  7134. LLRBNode.prototype.min_ = function () {
  7135. if (this.left.isEmpty()) {
  7136. return this;
  7137. }
  7138. else {
  7139. return this.left.min_();
  7140. }
  7141. };
  7142. /**
  7143. * @returns The maximum key in the tree.
  7144. */
  7145. LLRBNode.prototype.minKey = function () {
  7146. return this.min_().key;
  7147. };
  7148. /**
  7149. * @returns The maximum key in the tree.
  7150. */
  7151. LLRBNode.prototype.maxKey = function () {
  7152. if (this.right.isEmpty()) {
  7153. return this.key;
  7154. }
  7155. else {
  7156. return this.right.maxKey();
  7157. }
  7158. };
  7159. /**
  7160. * @param key - Key to insert.
  7161. * @param value - Value to insert.
  7162. * @param comparator - Comparator.
  7163. * @returns New tree, with the key/value added.
  7164. */
  7165. LLRBNode.prototype.insert = function (key, value, comparator) {
  7166. var n = this;
  7167. var cmp = comparator(key, n.key);
  7168. if (cmp < 0) {
  7169. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  7170. }
  7171. else if (cmp === 0) {
  7172. n = n.copy(null, value, null, null, null);
  7173. }
  7174. else {
  7175. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  7176. }
  7177. return n.fixUp_();
  7178. };
  7179. /**
  7180. * @returns New tree, with the minimum key removed.
  7181. */
  7182. LLRBNode.prototype.removeMin_ = function () {
  7183. if (this.left.isEmpty()) {
  7184. return SortedMap.EMPTY_NODE;
  7185. }
  7186. var n = this;
  7187. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  7188. n = n.moveRedLeft_();
  7189. }
  7190. n = n.copy(null, null, null, n.left.removeMin_(), null);
  7191. return n.fixUp_();
  7192. };
  7193. /**
  7194. * @param key - The key of the item to remove.
  7195. * @param comparator - Comparator.
  7196. * @returns New tree, with the specified item removed.
  7197. */
  7198. LLRBNode.prototype.remove = function (key, comparator) {
  7199. var n, smallest;
  7200. n = this;
  7201. if (comparator(key, n.key) < 0) {
  7202. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  7203. n = n.moveRedLeft_();
  7204. }
  7205. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  7206. }
  7207. else {
  7208. if (n.left.isRed_()) {
  7209. n = n.rotateRight_();
  7210. }
  7211. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  7212. n = n.moveRedRight_();
  7213. }
  7214. if (comparator(key, n.key) === 0) {
  7215. if (n.right.isEmpty()) {
  7216. return SortedMap.EMPTY_NODE;
  7217. }
  7218. else {
  7219. smallest = n.right.min_();
  7220. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  7221. }
  7222. }
  7223. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  7224. }
  7225. return n.fixUp_();
  7226. };
  7227. /**
  7228. * @returns Whether this is a RED node.
  7229. */
  7230. LLRBNode.prototype.isRed_ = function () {
  7231. return this.color;
  7232. };
  7233. /**
  7234. * @returns New tree after performing any needed rotations.
  7235. */
  7236. LLRBNode.prototype.fixUp_ = function () {
  7237. var n = this;
  7238. if (n.right.isRed_() && !n.left.isRed_()) {
  7239. n = n.rotateLeft_();
  7240. }
  7241. if (n.left.isRed_() && n.left.left.isRed_()) {
  7242. n = n.rotateRight_();
  7243. }
  7244. if (n.left.isRed_() && n.right.isRed_()) {
  7245. n = n.colorFlip_();
  7246. }
  7247. return n;
  7248. };
  7249. /**
  7250. * @returns New tree, after moveRedLeft.
  7251. */
  7252. LLRBNode.prototype.moveRedLeft_ = function () {
  7253. var n = this.colorFlip_();
  7254. if (n.right.left.isRed_()) {
  7255. n = n.copy(null, null, null, null, n.right.rotateRight_());
  7256. n = n.rotateLeft_();
  7257. n = n.colorFlip_();
  7258. }
  7259. return n;
  7260. };
  7261. /**
  7262. * @returns New tree, after moveRedRight.
  7263. */
  7264. LLRBNode.prototype.moveRedRight_ = function () {
  7265. var n = this.colorFlip_();
  7266. if (n.left.left.isRed_()) {
  7267. n = n.rotateRight_();
  7268. n = n.colorFlip_();
  7269. }
  7270. return n;
  7271. };
  7272. /**
  7273. * @returns New tree, after rotateLeft.
  7274. */
  7275. LLRBNode.prototype.rotateLeft_ = function () {
  7276. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  7277. return this.right.copy(null, null, this.color, nl, null);
  7278. };
  7279. /**
  7280. * @returns New tree, after rotateRight.
  7281. */
  7282. LLRBNode.prototype.rotateRight_ = function () {
  7283. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  7284. return this.left.copy(null, null, this.color, null, nr);
  7285. };
  7286. /**
  7287. * @returns Newt ree, after colorFlip.
  7288. */
  7289. LLRBNode.prototype.colorFlip_ = function () {
  7290. var left = this.left.copy(null, null, !this.left.color, null, null);
  7291. var right = this.right.copy(null, null, !this.right.color, null, null);
  7292. return this.copy(null, null, !this.color, left, right);
  7293. };
  7294. /**
  7295. * For testing.
  7296. *
  7297. * @returns True if all is well.
  7298. */
  7299. LLRBNode.prototype.checkMaxDepth_ = function () {
  7300. var blackDepth = this.check_();
  7301. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  7302. };
  7303. LLRBNode.prototype.check_ = function () {
  7304. if (this.isRed_() && this.left.isRed_()) {
  7305. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  7306. }
  7307. if (this.right.isRed_()) {
  7308. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  7309. }
  7310. var blackDepth = this.left.check_();
  7311. if (blackDepth !== this.right.check_()) {
  7312. throw new Error('Black depths differ');
  7313. }
  7314. else {
  7315. return blackDepth + (this.isRed_() ? 0 : 1);
  7316. }
  7317. };
  7318. LLRBNode.RED = true;
  7319. LLRBNode.BLACK = false;
  7320. return LLRBNode;
  7321. }());
  7322. /**
  7323. * Represents an empty node (a leaf node in the Red-Black Tree).
  7324. */
  7325. var LLRBEmptyNode = /** @class */ (function () {
  7326. function LLRBEmptyNode() {
  7327. }
  7328. /**
  7329. * Returns a copy of the current node.
  7330. *
  7331. * @returns The node copy.
  7332. */
  7333. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  7334. return this;
  7335. };
  7336. /**
  7337. * Returns a copy of the tree, with the specified key/value added.
  7338. *
  7339. * @param key - Key to be added.
  7340. * @param value - Value to be added.
  7341. * @param comparator - Comparator.
  7342. * @returns New tree, with item added.
  7343. */
  7344. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  7345. return new LLRBNode(key, value, null);
  7346. };
  7347. /**
  7348. * Returns a copy of the tree, with the specified key removed.
  7349. *
  7350. * @param key - The key to remove.
  7351. * @param comparator - Comparator.
  7352. * @returns New tree, with item removed.
  7353. */
  7354. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  7355. return this;
  7356. };
  7357. /**
  7358. * @returns The total number of nodes in the tree.
  7359. */
  7360. LLRBEmptyNode.prototype.count = function () {
  7361. return 0;
  7362. };
  7363. /**
  7364. * @returns True if the tree is empty.
  7365. */
  7366. LLRBEmptyNode.prototype.isEmpty = function () {
  7367. return true;
  7368. };
  7369. /**
  7370. * Traverses the tree in key order and calls the specified action function
  7371. * for each node.
  7372. *
  7373. * @param action - Callback function to be called for each
  7374. * node. If it returns true, traversal is aborted.
  7375. * @returns True if traversal was aborted.
  7376. */
  7377. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  7378. return false;
  7379. };
  7380. /**
  7381. * Traverses the tree in reverse key order and calls the specified action function
  7382. * for each node.
  7383. *
  7384. * @param action - Callback function to be called for each
  7385. * node. If it returns true, traversal is aborted.
  7386. * @returns True if traversal was aborted.
  7387. */
  7388. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  7389. return false;
  7390. };
  7391. LLRBEmptyNode.prototype.minKey = function () {
  7392. return null;
  7393. };
  7394. LLRBEmptyNode.prototype.maxKey = function () {
  7395. return null;
  7396. };
  7397. LLRBEmptyNode.prototype.check_ = function () {
  7398. return 0;
  7399. };
  7400. /**
  7401. * @returns Whether this node is red.
  7402. */
  7403. LLRBEmptyNode.prototype.isRed_ = function () {
  7404. return false;
  7405. };
  7406. return LLRBEmptyNode;
  7407. }());
  7408. /**
  7409. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  7410. * tree.
  7411. */
  7412. var SortedMap = /** @class */ (function () {
  7413. /**
  7414. * @param comparator_ - Key comparator.
  7415. * @param root_ - Optional root node for the map.
  7416. */
  7417. function SortedMap(comparator_, root_) {
  7418. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  7419. this.comparator_ = comparator_;
  7420. this.root_ = root_;
  7421. }
  7422. /**
  7423. * Returns a copy of the map, with the specified key/value added or replaced.
  7424. * (TODO: We should perhaps rename this method to 'put')
  7425. *
  7426. * @param key - Key to be added.
  7427. * @param value - Value to be added.
  7428. * @returns New map, with item added.
  7429. */
  7430. SortedMap.prototype.insert = function (key, value) {
  7431. return new SortedMap(this.comparator_, this.root_
  7432. .insert(key, value, this.comparator_)
  7433. .copy(null, null, LLRBNode.BLACK, null, null));
  7434. };
  7435. /**
  7436. * Returns a copy of the map, with the specified key removed.
  7437. *
  7438. * @param key - The key to remove.
  7439. * @returns New map, with item removed.
  7440. */
  7441. SortedMap.prototype.remove = function (key) {
  7442. return new SortedMap(this.comparator_, this.root_
  7443. .remove(key, this.comparator_)
  7444. .copy(null, null, LLRBNode.BLACK, null, null));
  7445. };
  7446. /**
  7447. * Returns the value of the node with the given key, or null.
  7448. *
  7449. * @param key - The key to look up.
  7450. * @returns The value of the node with the given key, or null if the
  7451. * key doesn't exist.
  7452. */
  7453. SortedMap.prototype.get = function (key) {
  7454. var cmp;
  7455. var node = this.root_;
  7456. while (!node.isEmpty()) {
  7457. cmp = this.comparator_(key, node.key);
  7458. if (cmp === 0) {
  7459. return node.value;
  7460. }
  7461. else if (cmp < 0) {
  7462. node = node.left;
  7463. }
  7464. else if (cmp > 0) {
  7465. node = node.right;
  7466. }
  7467. }
  7468. return null;
  7469. };
  7470. /**
  7471. * Returns the key of the item *before* the specified key, or null if key is the first item.
  7472. * @param key - The key to find the predecessor of
  7473. * @returns The predecessor key.
  7474. */
  7475. SortedMap.prototype.getPredecessorKey = function (key) {
  7476. var cmp, node = this.root_, rightParent = null;
  7477. while (!node.isEmpty()) {
  7478. cmp = this.comparator_(key, node.key);
  7479. if (cmp === 0) {
  7480. if (!node.left.isEmpty()) {
  7481. node = node.left;
  7482. while (!node.right.isEmpty()) {
  7483. node = node.right;
  7484. }
  7485. return node.key;
  7486. }
  7487. else if (rightParent) {
  7488. return rightParent.key;
  7489. }
  7490. else {
  7491. return null; // first item.
  7492. }
  7493. }
  7494. else if (cmp < 0) {
  7495. node = node.left;
  7496. }
  7497. else if (cmp > 0) {
  7498. rightParent = node;
  7499. node = node.right;
  7500. }
  7501. }
  7502. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  7503. };
  7504. /**
  7505. * @returns True if the map is empty.
  7506. */
  7507. SortedMap.prototype.isEmpty = function () {
  7508. return this.root_.isEmpty();
  7509. };
  7510. /**
  7511. * @returns The total number of nodes in the map.
  7512. */
  7513. SortedMap.prototype.count = function () {
  7514. return this.root_.count();
  7515. };
  7516. /**
  7517. * @returns The minimum key in the map.
  7518. */
  7519. SortedMap.prototype.minKey = function () {
  7520. return this.root_.minKey();
  7521. };
  7522. /**
  7523. * @returns The maximum key in the map.
  7524. */
  7525. SortedMap.prototype.maxKey = function () {
  7526. return this.root_.maxKey();
  7527. };
  7528. /**
  7529. * Traverses the map in key order and calls the specified action function
  7530. * for each key/value pair.
  7531. *
  7532. * @param action - Callback function to be called
  7533. * for each key/value pair. If action returns true, traversal is aborted.
  7534. * @returns The first truthy value returned by action, or the last falsey
  7535. * value returned by action
  7536. */
  7537. SortedMap.prototype.inorderTraversal = function (action) {
  7538. return this.root_.inorderTraversal(action);
  7539. };
  7540. /**
  7541. * Traverses the map in reverse key order and calls the specified action function
  7542. * for each key/value pair.
  7543. *
  7544. * @param action - Callback function to be called
  7545. * for each key/value pair. If action returns true, traversal is aborted.
  7546. * @returns True if the traversal was aborted.
  7547. */
  7548. SortedMap.prototype.reverseTraversal = function (action) {
  7549. return this.root_.reverseTraversal(action);
  7550. };
  7551. /**
  7552. * Returns an iterator over the SortedMap.
  7553. * @returns The iterator.
  7554. */
  7555. SortedMap.prototype.getIterator = function (resultGenerator) {
  7556. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  7557. };
  7558. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  7559. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  7560. };
  7561. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  7562. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  7563. };
  7564. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  7565. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  7566. };
  7567. /**
  7568. * Always use the same empty node, to reduce memory.
  7569. */
  7570. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  7571. return SortedMap;
  7572. }());
  7573. /**
  7574. * @license
  7575. * Copyright 2017 Google LLC
  7576. *
  7577. * Licensed under the Apache License, Version 2.0 (the "License");
  7578. * you may not use this file except in compliance with the License.
  7579. * You may obtain a copy of the License at
  7580. *
  7581. * http://www.apache.org/licenses/LICENSE-2.0
  7582. *
  7583. * Unless required by applicable law or agreed to in writing, software
  7584. * distributed under the License is distributed on an "AS IS" BASIS,
  7585. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7586. * See the License for the specific language governing permissions and
  7587. * limitations under the License.
  7588. */
  7589. function NAME_ONLY_COMPARATOR(left, right) {
  7590. return nameCompare(left.name, right.name);
  7591. }
  7592. function NAME_COMPARATOR(left, right) {
  7593. return nameCompare(left, right);
  7594. }
  7595. /**
  7596. * @license
  7597. * Copyright 2017 Google LLC
  7598. *
  7599. * Licensed under the Apache License, Version 2.0 (the "License");
  7600. * you may not use this file except in compliance with the License.
  7601. * You may obtain a copy of the License at
  7602. *
  7603. * http://www.apache.org/licenses/LICENSE-2.0
  7604. *
  7605. * Unless required by applicable law or agreed to in writing, software
  7606. * distributed under the License is distributed on an "AS IS" BASIS,
  7607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7608. * See the License for the specific language governing permissions and
  7609. * limitations under the License.
  7610. */
  7611. var MAX_NODE$2;
  7612. function setMaxNode$1(val) {
  7613. MAX_NODE$2 = val;
  7614. }
  7615. var priorityHashText = function (priority) {
  7616. if (typeof priority === 'number') {
  7617. return 'number:' + doubleToIEEE754String(priority);
  7618. }
  7619. else {
  7620. return 'string:' + priority;
  7621. }
  7622. };
  7623. /**
  7624. * Validates that a priority snapshot Node is valid.
  7625. */
  7626. var validatePriorityNode = function (priorityNode) {
  7627. if (priorityNode.isLeafNode()) {
  7628. var val = priorityNode.val();
  7629. util.assert(typeof val === 'string' ||
  7630. typeof val === 'number' ||
  7631. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  7632. }
  7633. else {
  7634. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  7635. }
  7636. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  7637. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  7638. };
  7639. /**
  7640. * @license
  7641. * Copyright 2017 Google LLC
  7642. *
  7643. * Licensed under the Apache License, Version 2.0 (the "License");
  7644. * you may not use this file except in compliance with the License.
  7645. * You may obtain a copy of the License at
  7646. *
  7647. * http://www.apache.org/licenses/LICENSE-2.0
  7648. *
  7649. * Unless required by applicable law or agreed to in writing, software
  7650. * distributed under the License is distributed on an "AS IS" BASIS,
  7651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7652. * See the License for the specific language governing permissions and
  7653. * limitations under the License.
  7654. */
  7655. var __childrenNodeConstructor;
  7656. /**
  7657. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  7658. * implements Node and stores the value of the node (a string,
  7659. * number, or boolean) accessible via getValue().
  7660. */
  7661. var LeafNode = /** @class */ (function () {
  7662. /**
  7663. * @param value_ - The value to store in this leaf node. The object type is
  7664. * possible in the event of a deferred value
  7665. * @param priorityNode_ - The priority of this node.
  7666. */
  7667. function LeafNode(value_, priorityNode_) {
  7668. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  7669. this.value_ = value_;
  7670. this.priorityNode_ = priorityNode_;
  7671. this.lazyHash_ = null;
  7672. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  7673. validatePriorityNode(this.priorityNode_);
  7674. }
  7675. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  7676. get: function () {
  7677. return __childrenNodeConstructor;
  7678. },
  7679. set: function (val) {
  7680. __childrenNodeConstructor = val;
  7681. },
  7682. enumerable: false,
  7683. configurable: true
  7684. });
  7685. /** @inheritDoc */
  7686. LeafNode.prototype.isLeafNode = function () {
  7687. return true;
  7688. };
  7689. /** @inheritDoc */
  7690. LeafNode.prototype.getPriority = function () {
  7691. return this.priorityNode_;
  7692. };
  7693. /** @inheritDoc */
  7694. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  7695. return new LeafNode(this.value_, newPriorityNode);
  7696. };
  7697. /** @inheritDoc */
  7698. LeafNode.prototype.getImmediateChild = function (childName) {
  7699. // Hack to treat priority as a regular child
  7700. if (childName === '.priority') {
  7701. return this.priorityNode_;
  7702. }
  7703. else {
  7704. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  7705. }
  7706. };
  7707. /** @inheritDoc */
  7708. LeafNode.prototype.getChild = function (path) {
  7709. if (pathIsEmpty(path)) {
  7710. return this;
  7711. }
  7712. else if (pathGetFront(path) === '.priority') {
  7713. return this.priorityNode_;
  7714. }
  7715. else {
  7716. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  7717. }
  7718. };
  7719. LeafNode.prototype.hasChild = function () {
  7720. return false;
  7721. };
  7722. /** @inheritDoc */
  7723. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  7724. return null;
  7725. };
  7726. /** @inheritDoc */
  7727. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  7728. if (childName === '.priority') {
  7729. return this.updatePriority(newChildNode);
  7730. }
  7731. else if (newChildNode.isEmpty() && childName !== '.priority') {
  7732. return this;
  7733. }
  7734. else {
  7735. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  7736. }
  7737. };
  7738. /** @inheritDoc */
  7739. LeafNode.prototype.updateChild = function (path, newChildNode) {
  7740. var front = pathGetFront(path);
  7741. if (front === null) {
  7742. return newChildNode;
  7743. }
  7744. else if (newChildNode.isEmpty() && front !== '.priority') {
  7745. return this;
  7746. }
  7747. else {
  7748. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  7749. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  7750. }
  7751. };
  7752. /** @inheritDoc */
  7753. LeafNode.prototype.isEmpty = function () {
  7754. return false;
  7755. };
  7756. /** @inheritDoc */
  7757. LeafNode.prototype.numChildren = function () {
  7758. return 0;
  7759. };
  7760. /** @inheritDoc */
  7761. LeafNode.prototype.forEachChild = function (index, action) {
  7762. return false;
  7763. };
  7764. LeafNode.prototype.val = function (exportFormat) {
  7765. if (exportFormat && !this.getPriority().isEmpty()) {
  7766. return {
  7767. '.value': this.getValue(),
  7768. '.priority': this.getPriority().val()
  7769. };
  7770. }
  7771. else {
  7772. return this.getValue();
  7773. }
  7774. };
  7775. /** @inheritDoc */
  7776. LeafNode.prototype.hash = function () {
  7777. if (this.lazyHash_ === null) {
  7778. var toHash = '';
  7779. if (!this.priorityNode_.isEmpty()) {
  7780. toHash +=
  7781. 'priority:' +
  7782. priorityHashText(this.priorityNode_.val()) +
  7783. ':';
  7784. }
  7785. var type = typeof this.value_;
  7786. toHash += type + ':';
  7787. if (type === 'number') {
  7788. toHash += doubleToIEEE754String(this.value_);
  7789. }
  7790. else {
  7791. toHash += this.value_;
  7792. }
  7793. this.lazyHash_ = sha1(toHash);
  7794. }
  7795. return this.lazyHash_;
  7796. };
  7797. /**
  7798. * Returns the value of the leaf node.
  7799. * @returns The value of the node.
  7800. */
  7801. LeafNode.prototype.getValue = function () {
  7802. return this.value_;
  7803. };
  7804. LeafNode.prototype.compareTo = function (other) {
  7805. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  7806. return 1;
  7807. }
  7808. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  7809. return -1;
  7810. }
  7811. else {
  7812. util.assert(other.isLeafNode(), 'Unknown node type');
  7813. return this.compareToLeafNode_(other);
  7814. }
  7815. };
  7816. /**
  7817. * Comparison specifically for two leaf nodes
  7818. */
  7819. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  7820. var otherLeafType = typeof otherLeaf.value_;
  7821. var thisLeafType = typeof this.value_;
  7822. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  7823. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  7824. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  7825. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  7826. if (otherIndex === thisIndex) {
  7827. // Same type, compare values
  7828. if (thisLeafType === 'object') {
  7829. // Deferred value nodes are all equal, but we should also never get to this point...
  7830. return 0;
  7831. }
  7832. else {
  7833. // Note that this works because true > false, all others are number or string comparisons
  7834. if (this.value_ < otherLeaf.value_) {
  7835. return -1;
  7836. }
  7837. else if (this.value_ === otherLeaf.value_) {
  7838. return 0;
  7839. }
  7840. else {
  7841. return 1;
  7842. }
  7843. }
  7844. }
  7845. else {
  7846. return thisIndex - otherIndex;
  7847. }
  7848. };
  7849. LeafNode.prototype.withIndex = function () {
  7850. return this;
  7851. };
  7852. LeafNode.prototype.isIndexed = function () {
  7853. return true;
  7854. };
  7855. LeafNode.prototype.equals = function (other) {
  7856. if (other === this) {
  7857. return true;
  7858. }
  7859. else if (other.isLeafNode()) {
  7860. var otherLeaf = other;
  7861. return (this.value_ === otherLeaf.value_ &&
  7862. this.priorityNode_.equals(otherLeaf.priorityNode_));
  7863. }
  7864. else {
  7865. return false;
  7866. }
  7867. };
  7868. /**
  7869. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  7870. * the same type, the comparison falls back to their value
  7871. */
  7872. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  7873. return LeafNode;
  7874. }());
  7875. /**
  7876. * @license
  7877. * Copyright 2017 Google LLC
  7878. *
  7879. * Licensed under the Apache License, Version 2.0 (the "License");
  7880. * you may not use this file except in compliance with the License.
  7881. * You may obtain a copy of the License at
  7882. *
  7883. * http://www.apache.org/licenses/LICENSE-2.0
  7884. *
  7885. * Unless required by applicable law or agreed to in writing, software
  7886. * distributed under the License is distributed on an "AS IS" BASIS,
  7887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7888. * See the License for the specific language governing permissions and
  7889. * limitations under the License.
  7890. */
  7891. var nodeFromJSON$1;
  7892. var MAX_NODE$1;
  7893. function setNodeFromJSON(val) {
  7894. nodeFromJSON$1 = val;
  7895. }
  7896. function setMaxNode(val) {
  7897. MAX_NODE$1 = val;
  7898. }
  7899. var PriorityIndex = /** @class */ (function (_super) {
  7900. tslib.__extends(PriorityIndex, _super);
  7901. function PriorityIndex() {
  7902. return _super !== null && _super.apply(this, arguments) || this;
  7903. }
  7904. PriorityIndex.prototype.compare = function (a, b) {
  7905. var aPriority = a.node.getPriority();
  7906. var bPriority = b.node.getPriority();
  7907. var indexCmp = aPriority.compareTo(bPriority);
  7908. if (indexCmp === 0) {
  7909. return nameCompare(a.name, b.name);
  7910. }
  7911. else {
  7912. return indexCmp;
  7913. }
  7914. };
  7915. PriorityIndex.prototype.isDefinedOn = function (node) {
  7916. return !node.getPriority().isEmpty();
  7917. };
  7918. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  7919. return !oldNode.getPriority().equals(newNode.getPriority());
  7920. };
  7921. PriorityIndex.prototype.minPost = function () {
  7922. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7923. return NamedNode.MIN;
  7924. };
  7925. PriorityIndex.prototype.maxPost = function () {
  7926. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  7927. };
  7928. PriorityIndex.prototype.makePost = function (indexValue, name) {
  7929. var priorityNode = nodeFromJSON$1(indexValue);
  7930. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  7931. };
  7932. /**
  7933. * @returns String representation for inclusion in a query spec
  7934. */
  7935. PriorityIndex.prototype.toString = function () {
  7936. return '.priority';
  7937. };
  7938. return PriorityIndex;
  7939. }(Index));
  7940. var PRIORITY_INDEX = new PriorityIndex();
  7941. /**
  7942. * @license
  7943. * Copyright 2017 Google LLC
  7944. *
  7945. * Licensed under the Apache License, Version 2.0 (the "License");
  7946. * you may not use this file except in compliance with the License.
  7947. * You may obtain a copy of the License at
  7948. *
  7949. * http://www.apache.org/licenses/LICENSE-2.0
  7950. *
  7951. * Unless required by applicable law or agreed to in writing, software
  7952. * distributed under the License is distributed on an "AS IS" BASIS,
  7953. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7954. * See the License for the specific language governing permissions and
  7955. * limitations under the License.
  7956. */
  7957. var LOG_2 = Math.log(2);
  7958. var Base12Num = /** @class */ (function () {
  7959. function Base12Num(length) {
  7960. var logBase2 = function (num) {
  7961. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7962. return parseInt((Math.log(num) / LOG_2), 10);
  7963. };
  7964. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  7965. this.count = logBase2(length + 1);
  7966. this.current_ = this.count - 1;
  7967. var mask = bitMask(this.count);
  7968. this.bits_ = (length + 1) & mask;
  7969. }
  7970. Base12Num.prototype.nextBitIsOne = function () {
  7971. //noinspection JSBitwiseOperatorUsage
  7972. var result = !(this.bits_ & (0x1 << this.current_));
  7973. this.current_--;
  7974. return result;
  7975. };
  7976. return Base12Num;
  7977. }());
  7978. /**
  7979. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  7980. * function
  7981. *
  7982. * Uses the algorithm described in the paper linked here:
  7983. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  7984. *
  7985. * @param childList - Unsorted list of children
  7986. * @param cmp - The comparison method to be used
  7987. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  7988. * type is not NamedNode
  7989. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  7990. */
  7991. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  7992. childList.sort(cmp);
  7993. var buildBalancedTree = function (low, high) {
  7994. var length = high - low;
  7995. var namedNode;
  7996. var key;
  7997. if (length === 0) {
  7998. return null;
  7999. }
  8000. else if (length === 1) {
  8001. namedNode = childList[low];
  8002. key = keyFn ? keyFn(namedNode) : namedNode;
  8003. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  8004. }
  8005. else {
  8006. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8007. var middle = parseInt((length / 2), 10) + low;
  8008. var left = buildBalancedTree(low, middle);
  8009. var right = buildBalancedTree(middle + 1, high);
  8010. namedNode = childList[middle];
  8011. key = keyFn ? keyFn(namedNode) : namedNode;
  8012. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  8013. }
  8014. };
  8015. var buildFrom12Array = function (base12) {
  8016. var node = null;
  8017. var root = null;
  8018. var index = childList.length;
  8019. var buildPennant = function (chunkSize, color) {
  8020. var low = index - chunkSize;
  8021. var high = index;
  8022. index -= chunkSize;
  8023. var childTree = buildBalancedTree(low + 1, high);
  8024. var namedNode = childList[low];
  8025. var key = keyFn ? keyFn(namedNode) : namedNode;
  8026. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  8027. };
  8028. var attachPennant = function (pennant) {
  8029. if (node) {
  8030. node.left = pennant;
  8031. node = pennant;
  8032. }
  8033. else {
  8034. root = pennant;
  8035. node = pennant;
  8036. }
  8037. };
  8038. for (var i = 0; i < base12.count; ++i) {
  8039. var isOne = base12.nextBitIsOne();
  8040. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  8041. var chunkSize = Math.pow(2, base12.count - (i + 1));
  8042. if (isOne) {
  8043. buildPennant(chunkSize, LLRBNode.BLACK);
  8044. }
  8045. else {
  8046. // current == 2
  8047. buildPennant(chunkSize, LLRBNode.BLACK);
  8048. buildPennant(chunkSize, LLRBNode.RED);
  8049. }
  8050. }
  8051. return root;
  8052. };
  8053. var base12 = new Base12Num(childList.length);
  8054. var root = buildFrom12Array(base12);
  8055. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8056. return new SortedMap(mapSortFn || cmp, root);
  8057. };
  8058. /**
  8059. * @license
  8060. * Copyright 2017 Google LLC
  8061. *
  8062. * Licensed under the Apache License, Version 2.0 (the "License");
  8063. * you may not use this file except in compliance with the License.
  8064. * You may obtain a copy of the License at
  8065. *
  8066. * http://www.apache.org/licenses/LICENSE-2.0
  8067. *
  8068. * Unless required by applicable law or agreed to in writing, software
  8069. * distributed under the License is distributed on an "AS IS" BASIS,
  8070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8071. * See the License for the specific language governing permissions and
  8072. * limitations under the License.
  8073. */
  8074. var _defaultIndexMap;
  8075. var fallbackObject = {};
  8076. var IndexMap = /** @class */ (function () {
  8077. function IndexMap(indexes_, indexSet_) {
  8078. this.indexes_ = indexes_;
  8079. this.indexSet_ = indexSet_;
  8080. }
  8081. Object.defineProperty(IndexMap, "Default", {
  8082. /**
  8083. * The default IndexMap for nodes without a priority
  8084. */
  8085. get: function () {
  8086. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  8087. _defaultIndexMap =
  8088. _defaultIndexMap ||
  8089. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  8090. return _defaultIndexMap;
  8091. },
  8092. enumerable: false,
  8093. configurable: true
  8094. });
  8095. IndexMap.prototype.get = function (indexKey) {
  8096. var sortedMap = util.safeGet(this.indexes_, indexKey);
  8097. if (!sortedMap) {
  8098. throw new Error('No index defined for ' + indexKey);
  8099. }
  8100. if (sortedMap instanceof SortedMap) {
  8101. return sortedMap;
  8102. }
  8103. else {
  8104. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  8105. // regular child map
  8106. return null;
  8107. }
  8108. };
  8109. IndexMap.prototype.hasIndex = function (indexDefinition) {
  8110. return util.contains(this.indexSet_, indexDefinition.toString());
  8111. };
  8112. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  8113. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  8114. var childList = [];
  8115. var sawIndexedValue = false;
  8116. var iter = existingChildren.getIterator(NamedNode.Wrap);
  8117. var next = iter.getNext();
  8118. while (next) {
  8119. sawIndexedValue =
  8120. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  8121. childList.push(next);
  8122. next = iter.getNext();
  8123. }
  8124. var newIndex;
  8125. if (sawIndexedValue) {
  8126. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  8127. }
  8128. else {
  8129. newIndex = fallbackObject;
  8130. }
  8131. var indexName = indexDefinition.toString();
  8132. var newIndexSet = tslib.__assign({}, this.indexSet_);
  8133. newIndexSet[indexName] = indexDefinition;
  8134. var newIndexes = tslib.__assign({}, this.indexes_);
  8135. newIndexes[indexName] = newIndex;
  8136. return new IndexMap(newIndexes, newIndexSet);
  8137. };
  8138. /**
  8139. * Ensure that this node is properly tracked in any indexes that we're maintaining
  8140. */
  8141. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  8142. var _this = this;
  8143. var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
  8144. var index = util.safeGet(_this.indexSet_, indexName);
  8145. util.assert(index, 'Missing index implementation for ' + indexName);
  8146. if (indexedChildren === fallbackObject) {
  8147. // Check to see if we need to index everything
  8148. if (index.isDefinedOn(namedNode.node)) {
  8149. // We need to build this index
  8150. var childList = [];
  8151. var iter = existingChildren.getIterator(NamedNode.Wrap);
  8152. var next = iter.getNext();
  8153. while (next) {
  8154. if (next.name !== namedNode.name) {
  8155. childList.push(next);
  8156. }
  8157. next = iter.getNext();
  8158. }
  8159. childList.push(namedNode);
  8160. return buildChildSet(childList, index.getCompare());
  8161. }
  8162. else {
  8163. // No change, this remains a fallback
  8164. return fallbackObject;
  8165. }
  8166. }
  8167. else {
  8168. var existingSnap = existingChildren.get(namedNode.name);
  8169. var newChildren = indexedChildren;
  8170. if (existingSnap) {
  8171. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  8172. }
  8173. return newChildren.insert(namedNode, namedNode.node);
  8174. }
  8175. });
  8176. return new IndexMap(newIndexes, this.indexSet_);
  8177. };
  8178. /**
  8179. * Create a new IndexMap instance with the given value removed
  8180. */
  8181. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  8182. var newIndexes = util.map(this.indexes_, function (indexedChildren) {
  8183. if (indexedChildren === fallbackObject) {
  8184. // This is the fallback. Just return it, nothing to do in this case
  8185. return indexedChildren;
  8186. }
  8187. else {
  8188. var existingSnap = existingChildren.get(namedNode.name);
  8189. if (existingSnap) {
  8190. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  8191. }
  8192. else {
  8193. // No record of this child
  8194. return indexedChildren;
  8195. }
  8196. }
  8197. });
  8198. return new IndexMap(newIndexes, this.indexSet_);
  8199. };
  8200. return IndexMap;
  8201. }());
  8202. /**
  8203. * @license
  8204. * Copyright 2017 Google LLC
  8205. *
  8206. * Licensed under the Apache License, Version 2.0 (the "License");
  8207. * you may not use this file except in compliance with the License.
  8208. * You may obtain a copy of the License at
  8209. *
  8210. * http://www.apache.org/licenses/LICENSE-2.0
  8211. *
  8212. * Unless required by applicable law or agreed to in writing, software
  8213. * distributed under the License is distributed on an "AS IS" BASIS,
  8214. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8215. * See the License for the specific language governing permissions and
  8216. * limitations under the License.
  8217. */
  8218. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  8219. var EMPTY_NODE;
  8220. /**
  8221. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  8222. * (i.e. nodes with children). It implements Node and stores the
  8223. * list of children in the children property, sorted by child name.
  8224. */
  8225. var ChildrenNode = /** @class */ (function () {
  8226. /**
  8227. * @param children_ - List of children of this node..
  8228. * @param priorityNode_ - The priority of this node (as a snapshot node).
  8229. */
  8230. function ChildrenNode(children_, priorityNode_, indexMap_) {
  8231. this.children_ = children_;
  8232. this.priorityNode_ = priorityNode_;
  8233. this.indexMap_ = indexMap_;
  8234. this.lazyHash_ = null;
  8235. /**
  8236. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  8237. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  8238. * class instead of an empty ChildrenNode.
  8239. */
  8240. if (this.priorityNode_) {
  8241. validatePriorityNode(this.priorityNode_);
  8242. }
  8243. if (this.children_.isEmpty()) {
  8244. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  8245. }
  8246. }
  8247. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  8248. get: function () {
  8249. return (EMPTY_NODE ||
  8250. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  8251. },
  8252. enumerable: false,
  8253. configurable: true
  8254. });
  8255. /** @inheritDoc */
  8256. ChildrenNode.prototype.isLeafNode = function () {
  8257. return false;
  8258. };
  8259. /** @inheritDoc */
  8260. ChildrenNode.prototype.getPriority = function () {
  8261. return this.priorityNode_ || EMPTY_NODE;
  8262. };
  8263. /** @inheritDoc */
  8264. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  8265. if (this.children_.isEmpty()) {
  8266. // Don't allow priorities on empty nodes
  8267. return this;
  8268. }
  8269. else {
  8270. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  8271. }
  8272. };
  8273. /** @inheritDoc */
  8274. ChildrenNode.prototype.getImmediateChild = function (childName) {
  8275. // Hack to treat priority as a regular child
  8276. if (childName === '.priority') {
  8277. return this.getPriority();
  8278. }
  8279. else {
  8280. var child = this.children_.get(childName);
  8281. return child === null ? EMPTY_NODE : child;
  8282. }
  8283. };
  8284. /** @inheritDoc */
  8285. ChildrenNode.prototype.getChild = function (path) {
  8286. var front = pathGetFront(path);
  8287. if (front === null) {
  8288. return this;
  8289. }
  8290. return this.getImmediateChild(front).getChild(pathPopFront(path));
  8291. };
  8292. /** @inheritDoc */
  8293. ChildrenNode.prototype.hasChild = function (childName) {
  8294. return this.children_.get(childName) !== null;
  8295. };
  8296. /** @inheritDoc */
  8297. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  8298. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  8299. if (childName === '.priority') {
  8300. return this.updatePriority(newChildNode);
  8301. }
  8302. else {
  8303. var namedNode = new NamedNode(childName, newChildNode);
  8304. var newChildren = void 0, newIndexMap = void 0;
  8305. if (newChildNode.isEmpty()) {
  8306. newChildren = this.children_.remove(childName);
  8307. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  8308. }
  8309. else {
  8310. newChildren = this.children_.insert(childName, newChildNode);
  8311. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  8312. }
  8313. var newPriority = newChildren.isEmpty()
  8314. ? EMPTY_NODE
  8315. : this.priorityNode_;
  8316. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  8317. }
  8318. };
  8319. /** @inheritDoc */
  8320. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  8321. var front = pathGetFront(path);
  8322. if (front === null) {
  8323. return newChildNode;
  8324. }
  8325. else {
  8326. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  8327. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  8328. return this.updateImmediateChild(front, newImmediateChild);
  8329. }
  8330. };
  8331. /** @inheritDoc */
  8332. ChildrenNode.prototype.isEmpty = function () {
  8333. return this.children_.isEmpty();
  8334. };
  8335. /** @inheritDoc */
  8336. ChildrenNode.prototype.numChildren = function () {
  8337. return this.children_.count();
  8338. };
  8339. /** @inheritDoc */
  8340. ChildrenNode.prototype.val = function (exportFormat) {
  8341. if (this.isEmpty()) {
  8342. return null;
  8343. }
  8344. var obj = {};
  8345. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  8346. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  8347. obj[key] = childNode.val(exportFormat);
  8348. numKeys++;
  8349. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  8350. maxKey = Math.max(maxKey, Number(key));
  8351. }
  8352. else {
  8353. allIntegerKeys = false;
  8354. }
  8355. });
  8356. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  8357. // convert to array.
  8358. var array = [];
  8359. // eslint-disable-next-line guard-for-in
  8360. for (var key in obj) {
  8361. array[key] = obj[key];
  8362. }
  8363. return array;
  8364. }
  8365. else {
  8366. if (exportFormat && !this.getPriority().isEmpty()) {
  8367. obj['.priority'] = this.getPriority().val();
  8368. }
  8369. return obj;
  8370. }
  8371. };
  8372. /** @inheritDoc */
  8373. ChildrenNode.prototype.hash = function () {
  8374. if (this.lazyHash_ === null) {
  8375. var toHash_1 = '';
  8376. if (!this.getPriority().isEmpty()) {
  8377. toHash_1 +=
  8378. 'priority:' +
  8379. priorityHashText(this.getPriority().val()) +
  8380. ':';
  8381. }
  8382. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  8383. var childHash = childNode.hash();
  8384. if (childHash !== '') {
  8385. toHash_1 += ':' + key + ':' + childHash;
  8386. }
  8387. });
  8388. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  8389. }
  8390. return this.lazyHash_;
  8391. };
  8392. /** @inheritDoc */
  8393. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  8394. var idx = this.resolveIndex_(index);
  8395. if (idx) {
  8396. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  8397. return predecessor ? predecessor.name : null;
  8398. }
  8399. else {
  8400. return this.children_.getPredecessorKey(childName);
  8401. }
  8402. };
  8403. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  8404. var idx = this.resolveIndex_(indexDefinition);
  8405. if (idx) {
  8406. var minKey = idx.minKey();
  8407. return minKey && minKey.name;
  8408. }
  8409. else {
  8410. return this.children_.minKey();
  8411. }
  8412. };
  8413. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  8414. var minKey = this.getFirstChildName(indexDefinition);
  8415. if (minKey) {
  8416. return new NamedNode(minKey, this.children_.get(minKey));
  8417. }
  8418. else {
  8419. return null;
  8420. }
  8421. };
  8422. /**
  8423. * Given an index, return the key name of the largest value we have, according to that index
  8424. */
  8425. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  8426. var idx = this.resolveIndex_(indexDefinition);
  8427. if (idx) {
  8428. var maxKey = idx.maxKey();
  8429. return maxKey && maxKey.name;
  8430. }
  8431. else {
  8432. return this.children_.maxKey();
  8433. }
  8434. };
  8435. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  8436. var maxKey = this.getLastChildName(indexDefinition);
  8437. if (maxKey) {
  8438. return new NamedNode(maxKey, this.children_.get(maxKey));
  8439. }
  8440. else {
  8441. return null;
  8442. }
  8443. };
  8444. ChildrenNode.prototype.forEachChild = function (index, action) {
  8445. var idx = this.resolveIndex_(index);
  8446. if (idx) {
  8447. return idx.inorderTraversal(function (wrappedNode) {
  8448. return action(wrappedNode.name, wrappedNode.node);
  8449. });
  8450. }
  8451. else {
  8452. return this.children_.inorderTraversal(action);
  8453. }
  8454. };
  8455. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  8456. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  8457. };
  8458. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  8459. var idx = this.resolveIndex_(indexDefinition);
  8460. if (idx) {
  8461. return idx.getIteratorFrom(startPost, function (key) { return key; });
  8462. }
  8463. else {
  8464. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  8465. var next = iterator.peek();
  8466. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  8467. iterator.getNext();
  8468. next = iterator.peek();
  8469. }
  8470. return iterator;
  8471. }
  8472. };
  8473. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  8474. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  8475. };
  8476. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  8477. var idx = this.resolveIndex_(indexDefinition);
  8478. if (idx) {
  8479. return idx.getReverseIteratorFrom(endPost, function (key) {
  8480. return key;
  8481. });
  8482. }
  8483. else {
  8484. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  8485. var next = iterator.peek();
  8486. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  8487. iterator.getNext();
  8488. next = iterator.peek();
  8489. }
  8490. return iterator;
  8491. }
  8492. };
  8493. ChildrenNode.prototype.compareTo = function (other) {
  8494. if (this.isEmpty()) {
  8495. if (other.isEmpty()) {
  8496. return 0;
  8497. }
  8498. else {
  8499. return -1;
  8500. }
  8501. }
  8502. else if (other.isLeafNode() || other.isEmpty()) {
  8503. return 1;
  8504. }
  8505. else if (other === MAX_NODE) {
  8506. return -1;
  8507. }
  8508. else {
  8509. // Must be another node with children.
  8510. return 0;
  8511. }
  8512. };
  8513. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  8514. if (indexDefinition === KEY_INDEX ||
  8515. this.indexMap_.hasIndex(indexDefinition)) {
  8516. return this;
  8517. }
  8518. else {
  8519. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  8520. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  8521. }
  8522. };
  8523. ChildrenNode.prototype.isIndexed = function (index) {
  8524. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  8525. };
  8526. ChildrenNode.prototype.equals = function (other) {
  8527. if (other === this) {
  8528. return true;
  8529. }
  8530. else if (other.isLeafNode()) {
  8531. return false;
  8532. }
  8533. else {
  8534. var otherChildrenNode = other;
  8535. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  8536. return false;
  8537. }
  8538. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  8539. var thisIter = this.getIterator(PRIORITY_INDEX);
  8540. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  8541. var thisCurrent = thisIter.getNext();
  8542. var otherCurrent = otherIter.getNext();
  8543. while (thisCurrent && otherCurrent) {
  8544. if (thisCurrent.name !== otherCurrent.name ||
  8545. !thisCurrent.node.equals(otherCurrent.node)) {
  8546. return false;
  8547. }
  8548. thisCurrent = thisIter.getNext();
  8549. otherCurrent = otherIter.getNext();
  8550. }
  8551. return thisCurrent === null && otherCurrent === null;
  8552. }
  8553. else {
  8554. return false;
  8555. }
  8556. }
  8557. };
  8558. /**
  8559. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  8560. * instead.
  8561. *
  8562. */
  8563. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  8564. if (indexDefinition === KEY_INDEX) {
  8565. return null;
  8566. }
  8567. else {
  8568. return this.indexMap_.get(indexDefinition.toString());
  8569. }
  8570. };
  8571. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  8572. return ChildrenNode;
  8573. }());
  8574. var MaxNode = /** @class */ (function (_super) {
  8575. tslib.__extends(MaxNode, _super);
  8576. function MaxNode() {
  8577. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  8578. }
  8579. MaxNode.prototype.compareTo = function (other) {
  8580. if (other === this) {
  8581. return 0;
  8582. }
  8583. else {
  8584. return 1;
  8585. }
  8586. };
  8587. MaxNode.prototype.equals = function (other) {
  8588. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  8589. return other === this;
  8590. };
  8591. MaxNode.prototype.getPriority = function () {
  8592. return this;
  8593. };
  8594. MaxNode.prototype.getImmediateChild = function (childName) {
  8595. return ChildrenNode.EMPTY_NODE;
  8596. };
  8597. MaxNode.prototype.isEmpty = function () {
  8598. return false;
  8599. };
  8600. return MaxNode;
  8601. }(ChildrenNode));
  8602. /**
  8603. * Marker that will sort higher than any other snapshot.
  8604. */
  8605. var MAX_NODE = new MaxNode();
  8606. Object.defineProperties(NamedNode, {
  8607. MIN: {
  8608. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  8609. },
  8610. MAX: {
  8611. value: new NamedNode(MAX_NAME, MAX_NODE)
  8612. }
  8613. });
  8614. /**
  8615. * Reference Extensions
  8616. */
  8617. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  8618. LeafNode.__childrenNodeConstructor = ChildrenNode;
  8619. setMaxNode$1(MAX_NODE);
  8620. setMaxNode(MAX_NODE);
  8621. /**
  8622. * @license
  8623. * Copyright 2017 Google LLC
  8624. *
  8625. * Licensed under the Apache License, Version 2.0 (the "License");
  8626. * you may not use this file except in compliance with the License.
  8627. * You may obtain a copy of the License at
  8628. *
  8629. * http://www.apache.org/licenses/LICENSE-2.0
  8630. *
  8631. * Unless required by applicable law or agreed to in writing, software
  8632. * distributed under the License is distributed on an "AS IS" BASIS,
  8633. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8634. * See the License for the specific language governing permissions and
  8635. * limitations under the License.
  8636. */
  8637. var USE_HINZE = true;
  8638. /**
  8639. * Constructs a snapshot node representing the passed JSON and returns it.
  8640. * @param json - JSON to create a node for.
  8641. * @param priority - Optional priority to use. This will be ignored if the
  8642. * passed JSON contains a .priority property.
  8643. */
  8644. function nodeFromJSON(json, priority) {
  8645. if (priority === void 0) { priority = null; }
  8646. if (json === null) {
  8647. return ChildrenNode.EMPTY_NODE;
  8648. }
  8649. if (typeof json === 'object' && '.priority' in json) {
  8650. priority = json['.priority'];
  8651. }
  8652. util.assert(priority === null ||
  8653. typeof priority === 'string' ||
  8654. typeof priority === 'number' ||
  8655. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  8656. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  8657. json = json['.value'];
  8658. }
  8659. // Valid leaf nodes include non-objects or server-value wrapper objects
  8660. if (typeof json !== 'object' || '.sv' in json) {
  8661. var jsonLeaf = json;
  8662. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  8663. }
  8664. if (!(json instanceof Array) && USE_HINZE) {
  8665. var children_1 = [];
  8666. var childrenHavePriority_1 = false;
  8667. var hinzeJsonObj = json;
  8668. each(hinzeJsonObj, function (key, child) {
  8669. if (key.substring(0, 1) !== '.') {
  8670. // Ignore metadata nodes
  8671. var childNode = nodeFromJSON(child);
  8672. if (!childNode.isEmpty()) {
  8673. childrenHavePriority_1 =
  8674. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  8675. children_1.push(new NamedNode(key, childNode));
  8676. }
  8677. }
  8678. });
  8679. if (children_1.length === 0) {
  8680. return ChildrenNode.EMPTY_NODE;
  8681. }
  8682. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  8683. if (childrenHavePriority_1) {
  8684. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  8685. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  8686. }
  8687. else {
  8688. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  8689. }
  8690. }
  8691. else {
  8692. var node_1 = ChildrenNode.EMPTY_NODE;
  8693. each(json, function (key, childData) {
  8694. if (util.contains(json, key)) {
  8695. if (key.substring(0, 1) !== '.') {
  8696. // ignore metadata nodes.
  8697. var childNode = nodeFromJSON(childData);
  8698. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  8699. node_1 = node_1.updateImmediateChild(key, childNode);
  8700. }
  8701. }
  8702. }
  8703. });
  8704. return node_1.updatePriority(nodeFromJSON(priority));
  8705. }
  8706. }
  8707. setNodeFromJSON(nodeFromJSON);
  8708. /**
  8709. * @license
  8710. * Copyright 2017 Google LLC
  8711. *
  8712. * Licensed under the Apache License, Version 2.0 (the "License");
  8713. * you may not use this file except in compliance with the License.
  8714. * You may obtain a copy of the License at
  8715. *
  8716. * http://www.apache.org/licenses/LICENSE-2.0
  8717. *
  8718. * Unless required by applicable law or agreed to in writing, software
  8719. * distributed under the License is distributed on an "AS IS" BASIS,
  8720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8721. * See the License for the specific language governing permissions and
  8722. * limitations under the License.
  8723. */
  8724. var PathIndex = /** @class */ (function (_super) {
  8725. tslib.__extends(PathIndex, _super);
  8726. function PathIndex(indexPath_) {
  8727. var _this = _super.call(this) || this;
  8728. _this.indexPath_ = indexPath_;
  8729. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  8730. return _this;
  8731. }
  8732. PathIndex.prototype.extractChild = function (snap) {
  8733. return snap.getChild(this.indexPath_);
  8734. };
  8735. PathIndex.prototype.isDefinedOn = function (node) {
  8736. return !node.getChild(this.indexPath_).isEmpty();
  8737. };
  8738. PathIndex.prototype.compare = function (a, b) {
  8739. var aChild = this.extractChild(a.node);
  8740. var bChild = this.extractChild(b.node);
  8741. var indexCmp = aChild.compareTo(bChild);
  8742. if (indexCmp === 0) {
  8743. return nameCompare(a.name, b.name);
  8744. }
  8745. else {
  8746. return indexCmp;
  8747. }
  8748. };
  8749. PathIndex.prototype.makePost = function (indexValue, name) {
  8750. var valueNode = nodeFromJSON(indexValue);
  8751. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  8752. return new NamedNode(name, node);
  8753. };
  8754. PathIndex.prototype.maxPost = function () {
  8755. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  8756. return new NamedNode(MAX_NAME, node);
  8757. };
  8758. PathIndex.prototype.toString = function () {
  8759. return pathSlice(this.indexPath_, 0).join('/');
  8760. };
  8761. return PathIndex;
  8762. }(Index));
  8763. /**
  8764. * @license
  8765. * Copyright 2017 Google LLC
  8766. *
  8767. * Licensed under the Apache License, Version 2.0 (the "License");
  8768. * you may not use this file except in compliance with the License.
  8769. * You may obtain a copy of the License at
  8770. *
  8771. * http://www.apache.org/licenses/LICENSE-2.0
  8772. *
  8773. * Unless required by applicable law or agreed to in writing, software
  8774. * distributed under the License is distributed on an "AS IS" BASIS,
  8775. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8776. * See the License for the specific language governing permissions and
  8777. * limitations under the License.
  8778. */
  8779. var ValueIndex = /** @class */ (function (_super) {
  8780. tslib.__extends(ValueIndex, _super);
  8781. function ValueIndex() {
  8782. return _super !== null && _super.apply(this, arguments) || this;
  8783. }
  8784. ValueIndex.prototype.compare = function (a, b) {
  8785. var indexCmp = a.node.compareTo(b.node);
  8786. if (indexCmp === 0) {
  8787. return nameCompare(a.name, b.name);
  8788. }
  8789. else {
  8790. return indexCmp;
  8791. }
  8792. };
  8793. ValueIndex.prototype.isDefinedOn = function (node) {
  8794. return true;
  8795. };
  8796. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  8797. return !oldNode.equals(newNode);
  8798. };
  8799. ValueIndex.prototype.minPost = function () {
  8800. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8801. return NamedNode.MIN;
  8802. };
  8803. ValueIndex.prototype.maxPost = function () {
  8804. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8805. return NamedNode.MAX;
  8806. };
  8807. ValueIndex.prototype.makePost = function (indexValue, name) {
  8808. var valueNode = nodeFromJSON(indexValue);
  8809. return new NamedNode(name, valueNode);
  8810. };
  8811. /**
  8812. * @returns String representation for inclusion in a query spec
  8813. */
  8814. ValueIndex.prototype.toString = function () {
  8815. return '.value';
  8816. };
  8817. return ValueIndex;
  8818. }(Index));
  8819. var VALUE_INDEX = new ValueIndex();
  8820. /**
  8821. * @license
  8822. * Copyright 2017 Google LLC
  8823. *
  8824. * Licensed under the Apache License, Version 2.0 (the "License");
  8825. * you may not use this file except in compliance with the License.
  8826. * You may obtain a copy of the License at
  8827. *
  8828. * http://www.apache.org/licenses/LICENSE-2.0
  8829. *
  8830. * Unless required by applicable law or agreed to in writing, software
  8831. * distributed under the License is distributed on an "AS IS" BASIS,
  8832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8833. * See the License for the specific language governing permissions and
  8834. * limitations under the License.
  8835. */
  8836. function changeValue(snapshotNode) {
  8837. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  8838. }
  8839. function changeChildAdded(childName, snapshotNode) {
  8840. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  8841. }
  8842. function changeChildRemoved(childName, snapshotNode) {
  8843. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  8844. }
  8845. function changeChildChanged(childName, snapshotNode, oldSnap) {
  8846. return {
  8847. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  8848. snapshotNode: snapshotNode,
  8849. childName: childName,
  8850. oldSnap: oldSnap
  8851. };
  8852. }
  8853. function changeChildMoved(childName, snapshotNode) {
  8854. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  8855. }
  8856. /**
  8857. * @license
  8858. * Copyright 2017 Google LLC
  8859. *
  8860. * Licensed under the Apache License, Version 2.0 (the "License");
  8861. * you may not use this file except in compliance with the License.
  8862. * You may obtain a copy of the License at
  8863. *
  8864. * http://www.apache.org/licenses/LICENSE-2.0
  8865. *
  8866. * Unless required by applicable law or agreed to in writing, software
  8867. * distributed under the License is distributed on an "AS IS" BASIS,
  8868. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8869. * See the License for the specific language governing permissions and
  8870. * limitations under the License.
  8871. */
  8872. /**
  8873. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  8874. */
  8875. var IndexedFilter = /** @class */ (function () {
  8876. function IndexedFilter(index_) {
  8877. this.index_ = index_;
  8878. }
  8879. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  8880. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  8881. var oldChild = snap.getImmediateChild(key);
  8882. // Check if anything actually changed.
  8883. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  8884. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  8885. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  8886. // to avoid treating these cases as "nothing changed."
  8887. if (oldChild.isEmpty() === newChild.isEmpty()) {
  8888. // Nothing changed.
  8889. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  8890. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  8891. return snap;
  8892. }
  8893. }
  8894. if (optChangeAccumulator != null) {
  8895. if (newChild.isEmpty()) {
  8896. if (snap.hasChild(key)) {
  8897. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  8898. }
  8899. else {
  8900. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  8901. }
  8902. }
  8903. else if (oldChild.isEmpty()) {
  8904. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  8905. }
  8906. else {
  8907. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  8908. }
  8909. }
  8910. if (snap.isLeafNode() && newChild.isEmpty()) {
  8911. return snap;
  8912. }
  8913. else {
  8914. // Make sure the node is indexed
  8915. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  8916. }
  8917. };
  8918. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  8919. if (optChangeAccumulator != null) {
  8920. if (!oldSnap.isLeafNode()) {
  8921. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  8922. if (!newSnap.hasChild(key)) {
  8923. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  8924. }
  8925. });
  8926. }
  8927. if (!newSnap.isLeafNode()) {
  8928. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  8929. if (oldSnap.hasChild(key)) {
  8930. var oldChild = oldSnap.getImmediateChild(key);
  8931. if (!oldChild.equals(childNode)) {
  8932. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  8933. }
  8934. }
  8935. else {
  8936. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  8937. }
  8938. });
  8939. }
  8940. }
  8941. return newSnap.withIndex(this.index_);
  8942. };
  8943. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  8944. if (oldSnap.isEmpty()) {
  8945. return ChildrenNode.EMPTY_NODE;
  8946. }
  8947. else {
  8948. return oldSnap.updatePriority(newPriority);
  8949. }
  8950. };
  8951. IndexedFilter.prototype.filtersNodes = function () {
  8952. return false;
  8953. };
  8954. IndexedFilter.prototype.getIndexedFilter = function () {
  8955. return this;
  8956. };
  8957. IndexedFilter.prototype.getIndex = function () {
  8958. return this.index_;
  8959. };
  8960. return IndexedFilter;
  8961. }());
  8962. /**
  8963. * @license
  8964. * Copyright 2017 Google LLC
  8965. *
  8966. * Licensed under the Apache License, Version 2.0 (the "License");
  8967. * you may not use this file except in compliance with the License.
  8968. * You may obtain a copy of the License at
  8969. *
  8970. * http://www.apache.org/licenses/LICENSE-2.0
  8971. *
  8972. * Unless required by applicable law or agreed to in writing, software
  8973. * distributed under the License is distributed on an "AS IS" BASIS,
  8974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8975. * See the License for the specific language governing permissions and
  8976. * limitations under the License.
  8977. */
  8978. /**
  8979. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  8980. */
  8981. var RangedFilter = /** @class */ (function () {
  8982. function RangedFilter(params) {
  8983. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  8984. this.index_ = params.getIndex();
  8985. this.startPost_ = RangedFilter.getStartPost_(params);
  8986. this.endPost_ = RangedFilter.getEndPost_(params);
  8987. this.startIsInclusive_ = !params.startAfterSet_;
  8988. this.endIsInclusive_ = !params.endBeforeSet_;
  8989. }
  8990. RangedFilter.prototype.getStartPost = function () {
  8991. return this.startPost_;
  8992. };
  8993. RangedFilter.prototype.getEndPost = function () {
  8994. return this.endPost_;
  8995. };
  8996. RangedFilter.prototype.matches = function (node) {
  8997. var isWithinStart = this.startIsInclusive_
  8998. ? this.index_.compare(this.getStartPost(), node) <= 0
  8999. : this.index_.compare(this.getStartPost(), node) < 0;
  9000. var isWithinEnd = this.endIsInclusive_
  9001. ? this.index_.compare(node, this.getEndPost()) <= 0
  9002. : this.index_.compare(node, this.getEndPost()) < 0;
  9003. return isWithinStart && isWithinEnd;
  9004. };
  9005. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  9006. if (!this.matches(new NamedNode(key, newChild))) {
  9007. newChild = ChildrenNode.EMPTY_NODE;
  9008. }
  9009. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  9010. };
  9011. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  9012. if (newSnap.isLeafNode()) {
  9013. // Make sure we have a children node with the correct index, not a leaf node;
  9014. newSnap = ChildrenNode.EMPTY_NODE;
  9015. }
  9016. var filtered = newSnap.withIndex(this.index_);
  9017. // Don't support priorities on queries
  9018. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  9019. var self = this;
  9020. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9021. if (!self.matches(new NamedNode(key, childNode))) {
  9022. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  9023. }
  9024. });
  9025. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  9026. };
  9027. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  9028. // Don't support priorities on queries
  9029. return oldSnap;
  9030. };
  9031. RangedFilter.prototype.filtersNodes = function () {
  9032. return true;
  9033. };
  9034. RangedFilter.prototype.getIndexedFilter = function () {
  9035. return this.indexedFilter_;
  9036. };
  9037. RangedFilter.prototype.getIndex = function () {
  9038. return this.index_;
  9039. };
  9040. RangedFilter.getStartPost_ = function (params) {
  9041. if (params.hasStart()) {
  9042. var startName = params.getIndexStartName();
  9043. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  9044. }
  9045. else {
  9046. return params.getIndex().minPost();
  9047. }
  9048. };
  9049. RangedFilter.getEndPost_ = function (params) {
  9050. if (params.hasEnd()) {
  9051. var endName = params.getIndexEndName();
  9052. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  9053. }
  9054. else {
  9055. return params.getIndex().maxPost();
  9056. }
  9057. };
  9058. return RangedFilter;
  9059. }());
  9060. /**
  9061. * @license
  9062. * Copyright 2017 Google LLC
  9063. *
  9064. * Licensed under the Apache License, Version 2.0 (the "License");
  9065. * you may not use this file except in compliance with the License.
  9066. * You may obtain a copy of the License at
  9067. *
  9068. * http://www.apache.org/licenses/LICENSE-2.0
  9069. *
  9070. * Unless required by applicable law or agreed to in writing, software
  9071. * distributed under the License is distributed on an "AS IS" BASIS,
  9072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9073. * See the License for the specific language governing permissions and
  9074. * limitations under the License.
  9075. */
  9076. /**
  9077. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  9078. */
  9079. var LimitedFilter = /** @class */ (function () {
  9080. function LimitedFilter(params) {
  9081. var _this = this;
  9082. this.withinDirectionalStart = function (node) {
  9083. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  9084. };
  9085. this.withinDirectionalEnd = function (node) {
  9086. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  9087. };
  9088. this.withinStartPost = function (node) {
  9089. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  9090. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  9091. };
  9092. this.withinEndPost = function (node) {
  9093. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  9094. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  9095. };
  9096. this.rangedFilter_ = new RangedFilter(params);
  9097. this.index_ = params.getIndex();
  9098. this.limit_ = params.getLimit();
  9099. this.reverse_ = !params.isViewFromLeft();
  9100. this.startIsInclusive_ = !params.startAfterSet_;
  9101. this.endIsInclusive_ = !params.endBeforeSet_;
  9102. }
  9103. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  9104. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  9105. newChild = ChildrenNode.EMPTY_NODE;
  9106. }
  9107. if (snap.getImmediateChild(key).equals(newChild)) {
  9108. // No change
  9109. return snap;
  9110. }
  9111. else if (snap.numChildren() < this.limit_) {
  9112. return this.rangedFilter_
  9113. .getIndexedFilter()
  9114. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  9115. }
  9116. else {
  9117. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  9118. }
  9119. };
  9120. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  9121. var filtered;
  9122. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  9123. // Make sure we have a children node with the correct index, not a leaf node;
  9124. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  9125. }
  9126. else {
  9127. if (this.limit_ * 2 < newSnap.numChildren() &&
  9128. newSnap.isIndexed(this.index_)) {
  9129. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  9130. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  9131. // anchor to the startPost, endPost, or last element as appropriate
  9132. var iterator = void 0;
  9133. if (this.reverse_) {
  9134. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  9135. }
  9136. else {
  9137. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  9138. }
  9139. var count = 0;
  9140. while (iterator.hasNext() && count < this.limit_) {
  9141. var next = iterator.getNext();
  9142. if (!this.withinDirectionalStart(next)) {
  9143. // if we have not reached the start, skip to the next element
  9144. continue;
  9145. }
  9146. else if (!this.withinDirectionalEnd(next)) {
  9147. // if we have reached the end, stop adding elements
  9148. break;
  9149. }
  9150. else {
  9151. filtered = filtered.updateImmediateChild(next.name, next.node);
  9152. count++;
  9153. }
  9154. }
  9155. }
  9156. else {
  9157. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  9158. filtered = newSnap.withIndex(this.index_);
  9159. // Don't support priorities on queries
  9160. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  9161. var iterator = void 0;
  9162. if (this.reverse_) {
  9163. iterator = filtered.getReverseIterator(this.index_);
  9164. }
  9165. else {
  9166. iterator = filtered.getIterator(this.index_);
  9167. }
  9168. var count = 0;
  9169. while (iterator.hasNext()) {
  9170. var next = iterator.getNext();
  9171. var inRange = count < this.limit_ &&
  9172. this.withinDirectionalStart(next) &&
  9173. this.withinDirectionalEnd(next);
  9174. if (inRange) {
  9175. count++;
  9176. }
  9177. else {
  9178. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  9179. }
  9180. }
  9181. }
  9182. }
  9183. return this.rangedFilter_
  9184. .getIndexedFilter()
  9185. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  9186. };
  9187. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  9188. // Don't support priorities on queries
  9189. return oldSnap;
  9190. };
  9191. LimitedFilter.prototype.filtersNodes = function () {
  9192. return true;
  9193. };
  9194. LimitedFilter.prototype.getIndexedFilter = function () {
  9195. return this.rangedFilter_.getIndexedFilter();
  9196. };
  9197. LimitedFilter.prototype.getIndex = function () {
  9198. return this.index_;
  9199. };
  9200. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  9201. // TODO: rename all cache stuff etc to general snap terminology
  9202. var cmp;
  9203. if (this.reverse_) {
  9204. var indexCmp_1 = this.index_.getCompare();
  9205. cmp = function (a, b) { return indexCmp_1(b, a); };
  9206. }
  9207. else {
  9208. cmp = this.index_.getCompare();
  9209. }
  9210. var oldEventCache = snap;
  9211. util.assert(oldEventCache.numChildren() === this.limit_, '');
  9212. var newChildNamedNode = new NamedNode(childKey, childSnap);
  9213. var windowBoundary = this.reverse_
  9214. ? oldEventCache.getFirstChild(this.index_)
  9215. : oldEventCache.getLastChild(this.index_);
  9216. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  9217. if (oldEventCache.hasChild(childKey)) {
  9218. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  9219. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  9220. while (nextChild != null &&
  9221. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  9222. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  9223. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  9224. // the limited filter...
  9225. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  9226. }
  9227. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  9228. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  9229. if (remainsInWindow) {
  9230. if (changeAccumulator != null) {
  9231. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  9232. }
  9233. return oldEventCache.updateImmediateChild(childKey, childSnap);
  9234. }
  9235. else {
  9236. if (changeAccumulator != null) {
  9237. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  9238. }
  9239. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  9240. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  9241. if (nextChildInRange) {
  9242. if (changeAccumulator != null) {
  9243. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  9244. }
  9245. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  9246. }
  9247. else {
  9248. return newEventCache;
  9249. }
  9250. }
  9251. }
  9252. else if (childSnap.isEmpty()) {
  9253. // we're deleting a node, but it was not in the window, so ignore it
  9254. return snap;
  9255. }
  9256. else if (inRange) {
  9257. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  9258. if (changeAccumulator != null) {
  9259. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  9260. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  9261. }
  9262. return oldEventCache
  9263. .updateImmediateChild(childKey, childSnap)
  9264. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  9265. }
  9266. else {
  9267. return snap;
  9268. }
  9269. }
  9270. else {
  9271. return snap;
  9272. }
  9273. };
  9274. return LimitedFilter;
  9275. }());
  9276. /**
  9277. * @license
  9278. * Copyright 2017 Google LLC
  9279. *
  9280. * Licensed under the Apache License, Version 2.0 (the "License");
  9281. * you may not use this file except in compliance with the License.
  9282. * You may obtain a copy of the License at
  9283. *
  9284. * http://www.apache.org/licenses/LICENSE-2.0
  9285. *
  9286. * Unless required by applicable law or agreed to in writing, software
  9287. * distributed under the License is distributed on an "AS IS" BASIS,
  9288. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9289. * See the License for the specific language governing permissions and
  9290. * limitations under the License.
  9291. */
  9292. /**
  9293. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  9294. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  9295. * user-facing API level, so it is not done here.
  9296. *
  9297. * @internal
  9298. */
  9299. var QueryParams = /** @class */ (function () {
  9300. function QueryParams() {
  9301. this.limitSet_ = false;
  9302. this.startSet_ = false;
  9303. this.startNameSet_ = false;
  9304. this.startAfterSet_ = false; // can only be true if startSet_ is true
  9305. this.endSet_ = false;
  9306. this.endNameSet_ = false;
  9307. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  9308. this.limit_ = 0;
  9309. this.viewFrom_ = '';
  9310. this.indexStartValue_ = null;
  9311. this.indexStartName_ = '';
  9312. this.indexEndValue_ = null;
  9313. this.indexEndName_ = '';
  9314. this.index_ = PRIORITY_INDEX;
  9315. }
  9316. QueryParams.prototype.hasStart = function () {
  9317. return this.startSet_;
  9318. };
  9319. /**
  9320. * @returns True if it would return from left.
  9321. */
  9322. QueryParams.prototype.isViewFromLeft = function () {
  9323. if (this.viewFrom_ === '') {
  9324. // limit(), rather than limitToFirst or limitToLast was called.
  9325. // This means that only one of startSet_ and endSet_ is true. Use them
  9326. // to calculate which side of the view to anchor to. If neither is set,
  9327. // anchor to the end.
  9328. return this.startSet_;
  9329. }
  9330. else {
  9331. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9332. }
  9333. };
  9334. /**
  9335. * Only valid to call if hasStart() returns true
  9336. */
  9337. QueryParams.prototype.getIndexStartValue = function () {
  9338. util.assert(this.startSet_, 'Only valid if start has been set');
  9339. return this.indexStartValue_;
  9340. };
  9341. /**
  9342. * Only valid to call if hasStart() returns true.
  9343. * Returns the starting key name for the range defined by these query parameters
  9344. */
  9345. QueryParams.prototype.getIndexStartName = function () {
  9346. util.assert(this.startSet_, 'Only valid if start has been set');
  9347. if (this.startNameSet_) {
  9348. return this.indexStartName_;
  9349. }
  9350. else {
  9351. return MIN_NAME;
  9352. }
  9353. };
  9354. QueryParams.prototype.hasEnd = function () {
  9355. return this.endSet_;
  9356. };
  9357. /**
  9358. * Only valid to call if hasEnd() returns true.
  9359. */
  9360. QueryParams.prototype.getIndexEndValue = function () {
  9361. util.assert(this.endSet_, 'Only valid if end has been set');
  9362. return this.indexEndValue_;
  9363. };
  9364. /**
  9365. * Only valid to call if hasEnd() returns true.
  9366. * Returns the end key name for the range defined by these query parameters
  9367. */
  9368. QueryParams.prototype.getIndexEndName = function () {
  9369. util.assert(this.endSet_, 'Only valid if end has been set');
  9370. if (this.endNameSet_) {
  9371. return this.indexEndName_;
  9372. }
  9373. else {
  9374. return MAX_NAME;
  9375. }
  9376. };
  9377. QueryParams.prototype.hasLimit = function () {
  9378. return this.limitSet_;
  9379. };
  9380. /**
  9381. * @returns True if a limit has been set and it has been explicitly anchored
  9382. */
  9383. QueryParams.prototype.hasAnchoredLimit = function () {
  9384. return this.limitSet_ && this.viewFrom_ !== '';
  9385. };
  9386. /**
  9387. * Only valid to call if hasLimit() returns true
  9388. */
  9389. QueryParams.prototype.getLimit = function () {
  9390. util.assert(this.limitSet_, 'Only valid if limit has been set');
  9391. return this.limit_;
  9392. };
  9393. QueryParams.prototype.getIndex = function () {
  9394. return this.index_;
  9395. };
  9396. QueryParams.prototype.loadsAllData = function () {
  9397. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  9398. };
  9399. QueryParams.prototype.isDefault = function () {
  9400. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  9401. };
  9402. QueryParams.prototype.copy = function () {
  9403. var copy = new QueryParams();
  9404. copy.limitSet_ = this.limitSet_;
  9405. copy.limit_ = this.limit_;
  9406. copy.startSet_ = this.startSet_;
  9407. copy.startAfterSet_ = this.startAfterSet_;
  9408. copy.indexStartValue_ = this.indexStartValue_;
  9409. copy.startNameSet_ = this.startNameSet_;
  9410. copy.indexStartName_ = this.indexStartName_;
  9411. copy.endSet_ = this.endSet_;
  9412. copy.endBeforeSet_ = this.endBeforeSet_;
  9413. copy.indexEndValue_ = this.indexEndValue_;
  9414. copy.endNameSet_ = this.endNameSet_;
  9415. copy.indexEndName_ = this.indexEndName_;
  9416. copy.index_ = this.index_;
  9417. copy.viewFrom_ = this.viewFrom_;
  9418. return copy;
  9419. };
  9420. return QueryParams;
  9421. }());
  9422. function queryParamsGetNodeFilter(queryParams) {
  9423. if (queryParams.loadsAllData()) {
  9424. return new IndexedFilter(queryParams.getIndex());
  9425. }
  9426. else if (queryParams.hasLimit()) {
  9427. return new LimitedFilter(queryParams);
  9428. }
  9429. else {
  9430. return new RangedFilter(queryParams);
  9431. }
  9432. }
  9433. function queryParamsLimitToFirst(queryParams, newLimit) {
  9434. var newParams = queryParams.copy();
  9435. newParams.limitSet_ = true;
  9436. newParams.limit_ = newLimit;
  9437. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9438. return newParams;
  9439. }
  9440. function queryParamsLimitToLast(queryParams, newLimit) {
  9441. var newParams = queryParams.copy();
  9442. newParams.limitSet_ = true;
  9443. newParams.limit_ = newLimit;
  9444. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  9445. return newParams;
  9446. }
  9447. function queryParamsStartAt(queryParams, indexValue, key) {
  9448. var newParams = queryParams.copy();
  9449. newParams.startSet_ = true;
  9450. if (indexValue === undefined) {
  9451. indexValue = null;
  9452. }
  9453. newParams.indexStartValue_ = indexValue;
  9454. if (key != null) {
  9455. newParams.startNameSet_ = true;
  9456. newParams.indexStartName_ = key;
  9457. }
  9458. else {
  9459. newParams.startNameSet_ = false;
  9460. newParams.indexStartName_ = '';
  9461. }
  9462. return newParams;
  9463. }
  9464. function queryParamsStartAfter(queryParams, indexValue, key) {
  9465. var params;
  9466. if (queryParams.index_ === KEY_INDEX || !!key) {
  9467. params = queryParamsStartAt(queryParams, indexValue, key);
  9468. }
  9469. else {
  9470. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  9471. }
  9472. params.startAfterSet_ = true;
  9473. return params;
  9474. }
  9475. function queryParamsEndAt(queryParams, indexValue, key) {
  9476. var newParams = queryParams.copy();
  9477. newParams.endSet_ = true;
  9478. if (indexValue === undefined) {
  9479. indexValue = null;
  9480. }
  9481. newParams.indexEndValue_ = indexValue;
  9482. if (key !== undefined) {
  9483. newParams.endNameSet_ = true;
  9484. newParams.indexEndName_ = key;
  9485. }
  9486. else {
  9487. newParams.endNameSet_ = false;
  9488. newParams.indexEndName_ = '';
  9489. }
  9490. return newParams;
  9491. }
  9492. function queryParamsEndBefore(queryParams, indexValue, key) {
  9493. var params;
  9494. if (queryParams.index_ === KEY_INDEX || !!key) {
  9495. params = queryParamsEndAt(queryParams, indexValue, key);
  9496. }
  9497. else {
  9498. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  9499. }
  9500. params.endBeforeSet_ = true;
  9501. return params;
  9502. }
  9503. function queryParamsOrderBy(queryParams, index) {
  9504. var newParams = queryParams.copy();
  9505. newParams.index_ = index;
  9506. return newParams;
  9507. }
  9508. /**
  9509. * Returns a set of REST query string parameters representing this query.
  9510. *
  9511. * @returns query string parameters
  9512. */
  9513. function queryParamsToRestQueryStringParameters(queryParams) {
  9514. var qs = {};
  9515. if (queryParams.isDefault()) {
  9516. return qs;
  9517. }
  9518. var orderBy;
  9519. if (queryParams.index_ === PRIORITY_INDEX) {
  9520. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  9521. }
  9522. else if (queryParams.index_ === VALUE_INDEX) {
  9523. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  9524. }
  9525. else if (queryParams.index_ === KEY_INDEX) {
  9526. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  9527. }
  9528. else {
  9529. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  9530. orderBy = queryParams.index_.toString();
  9531. }
  9532. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  9533. if (queryParams.startSet_) {
  9534. var startParam = queryParams.startAfterSet_
  9535. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  9536. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  9537. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  9538. if (queryParams.startNameSet_) {
  9539. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  9540. }
  9541. }
  9542. if (queryParams.endSet_) {
  9543. var endParam = queryParams.endBeforeSet_
  9544. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  9545. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  9546. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  9547. if (queryParams.endNameSet_) {
  9548. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  9549. }
  9550. }
  9551. if (queryParams.limitSet_) {
  9552. if (queryParams.isViewFromLeft()) {
  9553. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  9554. }
  9555. else {
  9556. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  9557. }
  9558. }
  9559. return qs;
  9560. }
  9561. function queryParamsGetQueryObject(queryParams) {
  9562. var obj = {};
  9563. if (queryParams.startSet_) {
  9564. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  9565. queryParams.indexStartValue_;
  9566. if (queryParams.startNameSet_) {
  9567. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  9568. queryParams.indexStartName_;
  9569. }
  9570. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  9571. !queryParams.startAfterSet_;
  9572. }
  9573. if (queryParams.endSet_) {
  9574. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  9575. if (queryParams.endNameSet_) {
  9576. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  9577. }
  9578. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  9579. !queryParams.endBeforeSet_;
  9580. }
  9581. if (queryParams.limitSet_) {
  9582. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  9583. var viewFrom = queryParams.viewFrom_;
  9584. if (viewFrom === '') {
  9585. if (queryParams.isViewFromLeft()) {
  9586. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  9587. }
  9588. else {
  9589. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  9590. }
  9591. }
  9592. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  9593. }
  9594. // For now, priority index is the default, so we only specify if it's some other index
  9595. if (queryParams.index_ !== PRIORITY_INDEX) {
  9596. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  9597. }
  9598. return obj;
  9599. }
  9600. /**
  9601. * @license
  9602. * Copyright 2017 Google LLC
  9603. *
  9604. * Licensed under the Apache License, Version 2.0 (the "License");
  9605. * you may not use this file except in compliance with the License.
  9606. * You may obtain a copy of the License at
  9607. *
  9608. * http://www.apache.org/licenses/LICENSE-2.0
  9609. *
  9610. * Unless required by applicable law or agreed to in writing, software
  9611. * distributed under the License is distributed on an "AS IS" BASIS,
  9612. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9613. * See the License for the specific language governing permissions and
  9614. * limitations under the License.
  9615. */
  9616. /**
  9617. * An implementation of ServerActions that communicates with the server via REST requests.
  9618. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  9619. * persistent connection (using WebSockets or long-polling)
  9620. */
  9621. var ReadonlyRestClient = /** @class */ (function (_super) {
  9622. tslib.__extends(ReadonlyRestClient, _super);
  9623. /**
  9624. * @param repoInfo_ - Data about the namespace we are connecting to
  9625. * @param onDataUpdate_ - A callback for new data from the server
  9626. */
  9627. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  9628. var _this = _super.call(this) || this;
  9629. _this.repoInfo_ = repoInfo_;
  9630. _this.onDataUpdate_ = onDataUpdate_;
  9631. _this.authTokenProvider_ = authTokenProvider_;
  9632. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  9633. /** @private {function(...[*])} */
  9634. _this.log_ = logWrapper('p:rest:');
  9635. /**
  9636. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  9637. * that's been removed. :-/
  9638. */
  9639. _this.listens_ = {};
  9640. return _this;
  9641. }
  9642. ReadonlyRestClient.prototype.reportStats = function (stats) {
  9643. throw new Error('Method not implemented.');
  9644. };
  9645. ReadonlyRestClient.getListenId_ = function (query, tag) {
  9646. if (tag !== undefined) {
  9647. return 'tag$' + tag;
  9648. }
  9649. else {
  9650. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  9651. return query._path.toString();
  9652. }
  9653. };
  9654. /** @inheritDoc */
  9655. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  9656. var _this = this;
  9657. var pathString = query._path.toString();
  9658. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  9659. // Mark this listener so we can tell if it's removed.
  9660. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  9661. var thisListen = {};
  9662. this.listens_[listenId] = thisListen;
  9663. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  9664. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  9665. var data = result;
  9666. if (error === 404) {
  9667. data = null;
  9668. error = null;
  9669. }
  9670. if (error === null) {
  9671. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  9672. }
  9673. if (util.safeGet(_this.listens_, listenId) === thisListen) {
  9674. var status_1;
  9675. if (!error) {
  9676. status_1 = 'ok';
  9677. }
  9678. else if (error === 401) {
  9679. status_1 = 'permission_denied';
  9680. }
  9681. else {
  9682. status_1 = 'rest_error:' + error;
  9683. }
  9684. onComplete(status_1, null);
  9685. }
  9686. });
  9687. };
  9688. /** @inheritDoc */
  9689. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  9690. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  9691. delete this.listens_[listenId];
  9692. };
  9693. ReadonlyRestClient.prototype.get = function (query) {
  9694. var _this = this;
  9695. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  9696. var pathString = query._path.toString();
  9697. var deferred = new util.Deferred();
  9698. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  9699. var data = result;
  9700. if (error === 404) {
  9701. data = null;
  9702. error = null;
  9703. }
  9704. if (error === null) {
  9705. _this.onDataUpdate_(pathString, data,
  9706. /*isMerge=*/ false,
  9707. /*tag=*/ null);
  9708. deferred.resolve(data);
  9709. }
  9710. else {
  9711. deferred.reject(new Error(data));
  9712. }
  9713. });
  9714. return deferred.promise;
  9715. };
  9716. /** @inheritDoc */
  9717. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  9718. // no-op since we just always call getToken.
  9719. };
  9720. /**
  9721. * Performs a REST request to the given path, with the provided query string parameters,
  9722. * and any auth credentials we have.
  9723. */
  9724. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  9725. var _this = this;
  9726. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  9727. queryStringParameters['format'] = 'export';
  9728. return Promise.all([
  9729. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  9730. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  9731. ]).then(function (_a) {
  9732. var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  9733. if (authToken && authToken.accessToken) {
  9734. queryStringParameters['auth'] = authToken.accessToken;
  9735. }
  9736. if (appCheckToken && appCheckToken.token) {
  9737. queryStringParameters['ac'] = appCheckToken.token;
  9738. }
  9739. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  9740. _this.repoInfo_.host +
  9741. pathString +
  9742. '?' +
  9743. 'ns=' +
  9744. _this.repoInfo_.namespace +
  9745. util.querystring(queryStringParameters);
  9746. _this.log_('Sending REST request for ' + url);
  9747. var xhr = new XMLHttpRequest();
  9748. xhr.onreadystatechange = function () {
  9749. if (callback && xhr.readyState === 4) {
  9750. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  9751. var res = null;
  9752. if (xhr.status >= 200 && xhr.status < 300) {
  9753. try {
  9754. res = util.jsonEval(xhr.responseText);
  9755. }
  9756. catch (e) {
  9757. warn$1('Failed to parse JSON response for ' +
  9758. url +
  9759. ': ' +
  9760. xhr.responseText);
  9761. }
  9762. callback(null, res);
  9763. }
  9764. else {
  9765. // 401 and 404 are expected.
  9766. if (xhr.status !== 401 && xhr.status !== 404) {
  9767. warn$1('Got unsuccessful REST response for ' +
  9768. url +
  9769. ' Status: ' +
  9770. xhr.status);
  9771. }
  9772. callback(xhr.status);
  9773. }
  9774. callback = null;
  9775. }
  9776. };
  9777. xhr.open('GET', url, /*asynchronous=*/ true);
  9778. xhr.send();
  9779. });
  9780. };
  9781. return ReadonlyRestClient;
  9782. }(ServerActions));
  9783. /**
  9784. * @license
  9785. * Copyright 2017 Google LLC
  9786. *
  9787. * Licensed under the Apache License, Version 2.0 (the "License");
  9788. * you may not use this file except in compliance with the License.
  9789. * You may obtain a copy of the License at
  9790. *
  9791. * http://www.apache.org/licenses/LICENSE-2.0
  9792. *
  9793. * Unless required by applicable law or agreed to in writing, software
  9794. * distributed under the License is distributed on an "AS IS" BASIS,
  9795. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9796. * See the License for the specific language governing permissions and
  9797. * limitations under the License.
  9798. */
  9799. /**
  9800. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  9801. */
  9802. var SnapshotHolder = /** @class */ (function () {
  9803. function SnapshotHolder() {
  9804. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  9805. }
  9806. SnapshotHolder.prototype.getNode = function (path) {
  9807. return this.rootNode_.getChild(path);
  9808. };
  9809. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  9810. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  9811. };
  9812. return SnapshotHolder;
  9813. }());
  9814. /**
  9815. * @license
  9816. * Copyright 2017 Google LLC
  9817. *
  9818. * Licensed under the Apache License, Version 2.0 (the "License");
  9819. * you may not use this file except in compliance with the License.
  9820. * You may obtain a copy of the License at
  9821. *
  9822. * http://www.apache.org/licenses/LICENSE-2.0
  9823. *
  9824. * Unless required by applicable law or agreed to in writing, software
  9825. * distributed under the License is distributed on an "AS IS" BASIS,
  9826. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9827. * See the License for the specific language governing permissions and
  9828. * limitations under the License.
  9829. */
  9830. function newSparseSnapshotTree() {
  9831. return {
  9832. value: null,
  9833. children: new Map()
  9834. };
  9835. }
  9836. /**
  9837. * Stores the given node at the specified path. If there is already a node
  9838. * at a shallower path, it merges the new data into that snapshot node.
  9839. *
  9840. * @param path - Path to look up snapshot for.
  9841. * @param data - The new data, or null.
  9842. */
  9843. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  9844. if (pathIsEmpty(path)) {
  9845. sparseSnapshotTree.value = data;
  9846. sparseSnapshotTree.children.clear();
  9847. }
  9848. else if (sparseSnapshotTree.value !== null) {
  9849. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  9850. }
  9851. else {
  9852. var childKey = pathGetFront(path);
  9853. if (!sparseSnapshotTree.children.has(childKey)) {
  9854. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  9855. }
  9856. var child = sparseSnapshotTree.children.get(childKey);
  9857. path = pathPopFront(path);
  9858. sparseSnapshotTreeRemember(child, path, data);
  9859. }
  9860. }
  9861. /**
  9862. * Purge the data at path from the cache.
  9863. *
  9864. * @param path - Path to look up snapshot for.
  9865. * @returns True if this node should now be removed.
  9866. */
  9867. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  9868. if (pathIsEmpty(path)) {
  9869. sparseSnapshotTree.value = null;
  9870. sparseSnapshotTree.children.clear();
  9871. return true;
  9872. }
  9873. else {
  9874. if (sparseSnapshotTree.value !== null) {
  9875. if (sparseSnapshotTree.value.isLeafNode()) {
  9876. // We're trying to forget a node that doesn't exist
  9877. return false;
  9878. }
  9879. else {
  9880. var value = sparseSnapshotTree.value;
  9881. sparseSnapshotTree.value = null;
  9882. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  9883. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  9884. });
  9885. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  9886. }
  9887. }
  9888. else if (sparseSnapshotTree.children.size > 0) {
  9889. var childKey = pathGetFront(path);
  9890. path = pathPopFront(path);
  9891. if (sparseSnapshotTree.children.has(childKey)) {
  9892. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  9893. if (safeToRemove) {
  9894. sparseSnapshotTree.children.delete(childKey);
  9895. }
  9896. }
  9897. return sparseSnapshotTree.children.size === 0;
  9898. }
  9899. else {
  9900. return true;
  9901. }
  9902. }
  9903. }
  9904. /**
  9905. * Recursively iterates through all of the stored tree and calls the
  9906. * callback on each one.
  9907. *
  9908. * @param prefixPath - Path to look up node for.
  9909. * @param func - The function to invoke for each tree.
  9910. */
  9911. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  9912. if (sparseSnapshotTree.value !== null) {
  9913. func(prefixPath, sparseSnapshotTree.value);
  9914. }
  9915. else {
  9916. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  9917. var path = new Path(prefixPath.toString() + '/' + key);
  9918. sparseSnapshotTreeForEachTree(tree, path, func);
  9919. });
  9920. }
  9921. }
  9922. /**
  9923. * Iterates through each immediate child and triggers the callback.
  9924. * Only seems to be used in tests.
  9925. *
  9926. * @param func - The function to invoke for each child.
  9927. */
  9928. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  9929. sparseSnapshotTree.children.forEach(function (tree, key) {
  9930. func(key, tree);
  9931. });
  9932. }
  9933. /**
  9934. * @license
  9935. * Copyright 2017 Google LLC
  9936. *
  9937. * Licensed under the Apache License, Version 2.0 (the "License");
  9938. * you may not use this file except in compliance with the License.
  9939. * You may obtain a copy of the License at
  9940. *
  9941. * http://www.apache.org/licenses/LICENSE-2.0
  9942. *
  9943. * Unless required by applicable law or agreed to in writing, software
  9944. * distributed under the License is distributed on an "AS IS" BASIS,
  9945. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9946. * See the License for the specific language governing permissions and
  9947. * limitations under the License.
  9948. */
  9949. /**
  9950. * Returns the delta from the previous call to get stats.
  9951. *
  9952. * @param collection_ - The collection to "listen" to.
  9953. */
  9954. var StatsListener = /** @class */ (function () {
  9955. function StatsListener(collection_) {
  9956. this.collection_ = collection_;
  9957. this.last_ = null;
  9958. }
  9959. StatsListener.prototype.get = function () {
  9960. var newStats = this.collection_.get();
  9961. var delta = tslib.__assign({}, newStats);
  9962. if (this.last_) {
  9963. each(this.last_, function (stat, value) {
  9964. delta[stat] = delta[stat] - value;
  9965. });
  9966. }
  9967. this.last_ = newStats;
  9968. return delta;
  9969. };
  9970. return StatsListener;
  9971. }());
  9972. /**
  9973. * @license
  9974. * Copyright 2017 Google LLC
  9975. *
  9976. * Licensed under the Apache License, Version 2.0 (the "License");
  9977. * you may not use this file except in compliance with the License.
  9978. * You may obtain a copy of the License at
  9979. *
  9980. * http://www.apache.org/licenses/LICENSE-2.0
  9981. *
  9982. * Unless required by applicable law or agreed to in writing, software
  9983. * distributed under the License is distributed on an "AS IS" BASIS,
  9984. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9985. * See the License for the specific language governing permissions and
  9986. * limitations under the License.
  9987. */
  9988. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  9989. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  9990. // seconds to try to ensure the Firebase connection is established / settled.
  9991. var FIRST_STATS_MIN_TIME = 10 * 1000;
  9992. var FIRST_STATS_MAX_TIME = 30 * 1000;
  9993. // We'll continue to report stats on average every 5 minutes.
  9994. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  9995. var StatsReporter = /** @class */ (function () {
  9996. function StatsReporter(collection, server_) {
  9997. this.server_ = server_;
  9998. this.statsToReport_ = {};
  9999. this.statsListener_ = new StatsListener(collection);
  10000. var timeout = FIRST_STATS_MIN_TIME +
  10001. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  10002. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  10003. }
  10004. StatsReporter.prototype.reportStats_ = function () {
  10005. var _this = this;
  10006. var stats = this.statsListener_.get();
  10007. var reportedStats = {};
  10008. var haveStatsToReport = false;
  10009. each(stats, function (stat, value) {
  10010. if (value > 0 && util.contains(_this.statsToReport_, stat)) {
  10011. reportedStats[stat] = value;
  10012. haveStatsToReport = true;
  10013. }
  10014. });
  10015. if (haveStatsToReport) {
  10016. this.server_.reportStats(reportedStats);
  10017. }
  10018. // queue our next run.
  10019. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  10020. };
  10021. return StatsReporter;
  10022. }());
  10023. /**
  10024. * @license
  10025. * Copyright 2017 Google LLC
  10026. *
  10027. * Licensed under the Apache License, Version 2.0 (the "License");
  10028. * you may not use this file except in compliance with the License.
  10029. * You may obtain a copy of the License at
  10030. *
  10031. * http://www.apache.org/licenses/LICENSE-2.0
  10032. *
  10033. * Unless required by applicable law or agreed to in writing, software
  10034. * distributed under the License is distributed on an "AS IS" BASIS,
  10035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10036. * See the License for the specific language governing permissions and
  10037. * limitations under the License.
  10038. */
  10039. /**
  10040. *
  10041. * @enum
  10042. */
  10043. var OperationType;
  10044. (function (OperationType) {
  10045. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  10046. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  10047. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  10048. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  10049. })(OperationType || (OperationType = {}));
  10050. function newOperationSourceUser() {
  10051. return {
  10052. fromUser: true,
  10053. fromServer: false,
  10054. queryId: null,
  10055. tagged: false
  10056. };
  10057. }
  10058. function newOperationSourceServer() {
  10059. return {
  10060. fromUser: false,
  10061. fromServer: true,
  10062. queryId: null,
  10063. tagged: false
  10064. };
  10065. }
  10066. function newOperationSourceServerTaggedQuery(queryId) {
  10067. return {
  10068. fromUser: false,
  10069. fromServer: true,
  10070. queryId: queryId,
  10071. tagged: true
  10072. };
  10073. }
  10074. /**
  10075. * @license
  10076. * Copyright 2017 Google LLC
  10077. *
  10078. * Licensed under the Apache License, Version 2.0 (the "License");
  10079. * you may not use this file except in compliance with the License.
  10080. * You may obtain a copy of the License at
  10081. *
  10082. * http://www.apache.org/licenses/LICENSE-2.0
  10083. *
  10084. * Unless required by applicable law or agreed to in writing, software
  10085. * distributed under the License is distributed on an "AS IS" BASIS,
  10086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10087. * See the License for the specific language governing permissions and
  10088. * limitations under the License.
  10089. */
  10090. var AckUserWrite = /** @class */ (function () {
  10091. /**
  10092. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  10093. */
  10094. function AckUserWrite(
  10095. /** @inheritDoc */ path,
  10096. /** @inheritDoc */ affectedTree,
  10097. /** @inheritDoc */ revert) {
  10098. this.path = path;
  10099. this.affectedTree = affectedTree;
  10100. this.revert = revert;
  10101. /** @inheritDoc */
  10102. this.type = OperationType.ACK_USER_WRITE;
  10103. /** @inheritDoc */
  10104. this.source = newOperationSourceUser();
  10105. }
  10106. AckUserWrite.prototype.operationForChild = function (childName) {
  10107. if (!pathIsEmpty(this.path)) {
  10108. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  10109. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  10110. }
  10111. else if (this.affectedTree.value != null) {
  10112. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  10113. // All child locations are affected as well; just return same operation.
  10114. return this;
  10115. }
  10116. else {
  10117. var childTree = this.affectedTree.subtree(new Path(childName));
  10118. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  10119. }
  10120. };
  10121. return AckUserWrite;
  10122. }());
  10123. /**
  10124. * @license
  10125. * Copyright 2017 Google LLC
  10126. *
  10127. * Licensed under the Apache License, Version 2.0 (the "License");
  10128. * you may not use this file except in compliance with the License.
  10129. * You may obtain a copy of the License at
  10130. *
  10131. * http://www.apache.org/licenses/LICENSE-2.0
  10132. *
  10133. * Unless required by applicable law or agreed to in writing, software
  10134. * distributed under the License is distributed on an "AS IS" BASIS,
  10135. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10136. * See the License for the specific language governing permissions and
  10137. * limitations under the License.
  10138. */
  10139. var ListenComplete = /** @class */ (function () {
  10140. function ListenComplete(source, path) {
  10141. this.source = source;
  10142. this.path = path;
  10143. /** @inheritDoc */
  10144. this.type = OperationType.LISTEN_COMPLETE;
  10145. }
  10146. ListenComplete.prototype.operationForChild = function (childName) {
  10147. if (pathIsEmpty(this.path)) {
  10148. return new ListenComplete(this.source, newEmptyPath());
  10149. }
  10150. else {
  10151. return new ListenComplete(this.source, pathPopFront(this.path));
  10152. }
  10153. };
  10154. return ListenComplete;
  10155. }());
  10156. /**
  10157. * @license
  10158. * Copyright 2017 Google LLC
  10159. *
  10160. * Licensed under the Apache License, Version 2.0 (the "License");
  10161. * you may not use this file except in compliance with the License.
  10162. * You may obtain a copy of the License at
  10163. *
  10164. * http://www.apache.org/licenses/LICENSE-2.0
  10165. *
  10166. * Unless required by applicable law or agreed to in writing, software
  10167. * distributed under the License is distributed on an "AS IS" BASIS,
  10168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10169. * See the License for the specific language governing permissions and
  10170. * limitations under the License.
  10171. */
  10172. var Overwrite = /** @class */ (function () {
  10173. function Overwrite(source, path, snap) {
  10174. this.source = source;
  10175. this.path = path;
  10176. this.snap = snap;
  10177. /** @inheritDoc */
  10178. this.type = OperationType.OVERWRITE;
  10179. }
  10180. Overwrite.prototype.operationForChild = function (childName) {
  10181. if (pathIsEmpty(this.path)) {
  10182. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  10183. }
  10184. else {
  10185. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  10186. }
  10187. };
  10188. return Overwrite;
  10189. }());
  10190. /**
  10191. * @license
  10192. * Copyright 2017 Google LLC
  10193. *
  10194. * Licensed under the Apache License, Version 2.0 (the "License");
  10195. * you may not use this file except in compliance with the License.
  10196. * You may obtain a copy of the License at
  10197. *
  10198. * http://www.apache.org/licenses/LICENSE-2.0
  10199. *
  10200. * Unless required by applicable law or agreed to in writing, software
  10201. * distributed under the License is distributed on an "AS IS" BASIS,
  10202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10203. * See the License for the specific language governing permissions and
  10204. * limitations under the License.
  10205. */
  10206. var Merge = /** @class */ (function () {
  10207. function Merge(
  10208. /** @inheritDoc */ source,
  10209. /** @inheritDoc */ path,
  10210. /** @inheritDoc */ children) {
  10211. this.source = source;
  10212. this.path = path;
  10213. this.children = children;
  10214. /** @inheritDoc */
  10215. this.type = OperationType.MERGE;
  10216. }
  10217. Merge.prototype.operationForChild = function (childName) {
  10218. if (pathIsEmpty(this.path)) {
  10219. var childTree = this.children.subtree(new Path(childName));
  10220. if (childTree.isEmpty()) {
  10221. // This child is unaffected
  10222. return null;
  10223. }
  10224. else if (childTree.value) {
  10225. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  10226. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  10227. }
  10228. else {
  10229. // This is a merge at a deeper level
  10230. return new Merge(this.source, newEmptyPath(), childTree);
  10231. }
  10232. }
  10233. else {
  10234. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  10235. return new Merge(this.source, pathPopFront(this.path), this.children);
  10236. }
  10237. };
  10238. Merge.prototype.toString = function () {
  10239. return ('Operation(' +
  10240. this.path +
  10241. ': ' +
  10242. this.source.toString() +
  10243. ' merge: ' +
  10244. this.children.toString() +
  10245. ')');
  10246. };
  10247. return Merge;
  10248. }());
  10249. /**
  10250. * @license
  10251. * Copyright 2017 Google LLC
  10252. *
  10253. * Licensed under the Apache License, Version 2.0 (the "License");
  10254. * you may not use this file except in compliance with the License.
  10255. * You may obtain a copy of the License at
  10256. *
  10257. * http://www.apache.org/licenses/LICENSE-2.0
  10258. *
  10259. * Unless required by applicable law or agreed to in writing, software
  10260. * distributed under the License is distributed on an "AS IS" BASIS,
  10261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10262. * See the License for the specific language governing permissions and
  10263. * limitations under the License.
  10264. */
  10265. /**
  10266. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  10267. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  10268. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  10269. * whether a node potentially had children removed due to a filter.
  10270. */
  10271. var CacheNode = /** @class */ (function () {
  10272. function CacheNode(node_, fullyInitialized_, filtered_) {
  10273. this.node_ = node_;
  10274. this.fullyInitialized_ = fullyInitialized_;
  10275. this.filtered_ = filtered_;
  10276. }
  10277. /**
  10278. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  10279. */
  10280. CacheNode.prototype.isFullyInitialized = function () {
  10281. return this.fullyInitialized_;
  10282. };
  10283. /**
  10284. * Returns whether this node is potentially missing children due to a filter applied to the node
  10285. */
  10286. CacheNode.prototype.isFiltered = function () {
  10287. return this.filtered_;
  10288. };
  10289. CacheNode.prototype.isCompleteForPath = function (path) {
  10290. if (pathIsEmpty(path)) {
  10291. return this.isFullyInitialized() && !this.filtered_;
  10292. }
  10293. var childKey = pathGetFront(path);
  10294. return this.isCompleteForChild(childKey);
  10295. };
  10296. CacheNode.prototype.isCompleteForChild = function (key) {
  10297. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  10298. };
  10299. CacheNode.prototype.getNode = function () {
  10300. return this.node_;
  10301. };
  10302. return CacheNode;
  10303. }());
  10304. /**
  10305. * @license
  10306. * Copyright 2017 Google LLC
  10307. *
  10308. * Licensed under the Apache License, Version 2.0 (the "License");
  10309. * you may not use this file except in compliance with the License.
  10310. * You may obtain a copy of the License at
  10311. *
  10312. * http://www.apache.org/licenses/LICENSE-2.0
  10313. *
  10314. * Unless required by applicable law or agreed to in writing, software
  10315. * distributed under the License is distributed on an "AS IS" BASIS,
  10316. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10317. * See the License for the specific language governing permissions and
  10318. * limitations under the License.
  10319. */
  10320. /**
  10321. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  10322. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  10323. * for details.
  10324. *
  10325. */
  10326. var EventGenerator = /** @class */ (function () {
  10327. function EventGenerator(query_) {
  10328. this.query_ = query_;
  10329. this.index_ = this.query_._queryParams.getIndex();
  10330. }
  10331. return EventGenerator;
  10332. }());
  10333. /**
  10334. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  10335. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  10336. *
  10337. * Notes:
  10338. * - child_moved events will be synthesized at this time for any child_changed events that affect
  10339. * our index.
  10340. * - prevName will be calculated based on the index ordering.
  10341. */
  10342. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  10343. var events = [];
  10344. var moves = [];
  10345. changes.forEach(function (change) {
  10346. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  10347. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  10348. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  10349. }
  10350. });
  10351. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  10352. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  10353. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  10354. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  10355. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  10356. return events;
  10357. }
  10358. /**
  10359. * Given changes of a single change type, generate the corresponding events.
  10360. */
  10361. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  10362. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  10363. filteredChanges.sort(function (a, b) {
  10364. return eventGeneratorCompareChanges(eventGenerator, a, b);
  10365. });
  10366. filteredChanges.forEach(function (change) {
  10367. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  10368. registrations.forEach(function (registration) {
  10369. if (registration.respondsTo(change.type)) {
  10370. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  10371. }
  10372. });
  10373. });
  10374. }
  10375. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  10376. if (change.type === 'value' || change.type === 'child_removed') {
  10377. return change;
  10378. }
  10379. else {
  10380. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  10381. return change;
  10382. }
  10383. }
  10384. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  10385. if (a.childName == null || b.childName == null) {
  10386. throw util.assertionError('Should only compare child_ events.');
  10387. }
  10388. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  10389. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  10390. return eventGenerator.index_.compare(aWrapped, bWrapped);
  10391. }
  10392. /**
  10393. * @license
  10394. * Copyright 2017 Google LLC
  10395. *
  10396. * Licensed under the Apache License, Version 2.0 (the "License");
  10397. * you may not use this file except in compliance with the License.
  10398. * You may obtain a copy of the License at
  10399. *
  10400. * http://www.apache.org/licenses/LICENSE-2.0
  10401. *
  10402. * Unless required by applicable law or agreed to in writing, software
  10403. * distributed under the License is distributed on an "AS IS" BASIS,
  10404. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10405. * See the License for the specific language governing permissions and
  10406. * limitations under the License.
  10407. */
  10408. function newViewCache(eventCache, serverCache) {
  10409. return { eventCache: eventCache, serverCache: serverCache };
  10410. }
  10411. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  10412. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  10413. }
  10414. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  10415. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  10416. }
  10417. function viewCacheGetCompleteEventSnap(viewCache) {
  10418. return viewCache.eventCache.isFullyInitialized()
  10419. ? viewCache.eventCache.getNode()
  10420. : null;
  10421. }
  10422. function viewCacheGetCompleteServerSnap(viewCache) {
  10423. return viewCache.serverCache.isFullyInitialized()
  10424. ? viewCache.serverCache.getNode()
  10425. : null;
  10426. }
  10427. /**
  10428. * @license
  10429. * Copyright 2017 Google LLC
  10430. *
  10431. * Licensed under the Apache License, Version 2.0 (the "License");
  10432. * you may not use this file except in compliance with the License.
  10433. * You may obtain a copy of the License at
  10434. *
  10435. * http://www.apache.org/licenses/LICENSE-2.0
  10436. *
  10437. * Unless required by applicable law or agreed to in writing, software
  10438. * distributed under the License is distributed on an "AS IS" BASIS,
  10439. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10440. * See the License for the specific language governing permissions and
  10441. * limitations under the License.
  10442. */
  10443. var emptyChildrenSingleton;
  10444. /**
  10445. * Singleton empty children collection.
  10446. *
  10447. */
  10448. var EmptyChildren = function () {
  10449. if (!emptyChildrenSingleton) {
  10450. emptyChildrenSingleton = new SortedMap(stringCompare);
  10451. }
  10452. return emptyChildrenSingleton;
  10453. };
  10454. /**
  10455. * A tree with immutable elements.
  10456. */
  10457. var ImmutableTree = /** @class */ (function () {
  10458. function ImmutableTree(value, children) {
  10459. if (children === void 0) { children = EmptyChildren(); }
  10460. this.value = value;
  10461. this.children = children;
  10462. }
  10463. ImmutableTree.fromObject = function (obj) {
  10464. var tree = new ImmutableTree(null);
  10465. each(obj, function (childPath, childSnap) {
  10466. tree = tree.set(new Path(childPath), childSnap);
  10467. });
  10468. return tree;
  10469. };
  10470. /**
  10471. * True if the value is empty and there are no children
  10472. */
  10473. ImmutableTree.prototype.isEmpty = function () {
  10474. return this.value === null && this.children.isEmpty();
  10475. };
  10476. /**
  10477. * Given a path and predicate, return the first node and the path to that node
  10478. * where the predicate returns true.
  10479. *
  10480. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  10481. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  10482. *
  10483. * @param relativePath - The remainder of the path
  10484. * @param predicate - The predicate to satisfy to return a node
  10485. */
  10486. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  10487. if (this.value != null && predicate(this.value)) {
  10488. return { path: newEmptyPath(), value: this.value };
  10489. }
  10490. else {
  10491. if (pathIsEmpty(relativePath)) {
  10492. return null;
  10493. }
  10494. else {
  10495. var front = pathGetFront(relativePath);
  10496. var child = this.children.get(front);
  10497. if (child !== null) {
  10498. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  10499. if (childExistingPathAndValue != null) {
  10500. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  10501. return { path: fullPath, value: childExistingPathAndValue.value };
  10502. }
  10503. else {
  10504. return null;
  10505. }
  10506. }
  10507. else {
  10508. return null;
  10509. }
  10510. }
  10511. }
  10512. };
  10513. /**
  10514. * Find, if it exists, the shortest subpath of the given path that points a defined
  10515. * value in the tree
  10516. */
  10517. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  10518. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  10519. };
  10520. /**
  10521. * @returns The subtree at the given path
  10522. */
  10523. ImmutableTree.prototype.subtree = function (relativePath) {
  10524. if (pathIsEmpty(relativePath)) {
  10525. return this;
  10526. }
  10527. else {
  10528. var front = pathGetFront(relativePath);
  10529. var childTree = this.children.get(front);
  10530. if (childTree !== null) {
  10531. return childTree.subtree(pathPopFront(relativePath));
  10532. }
  10533. else {
  10534. return new ImmutableTree(null);
  10535. }
  10536. }
  10537. };
  10538. /**
  10539. * Sets a value at the specified path.
  10540. *
  10541. * @param relativePath - Path to set value at.
  10542. * @param toSet - Value to set.
  10543. * @returns Resulting tree.
  10544. */
  10545. ImmutableTree.prototype.set = function (relativePath, toSet) {
  10546. if (pathIsEmpty(relativePath)) {
  10547. return new ImmutableTree(toSet, this.children);
  10548. }
  10549. else {
  10550. var front = pathGetFront(relativePath);
  10551. var child = this.children.get(front) || new ImmutableTree(null);
  10552. var newChild = child.set(pathPopFront(relativePath), toSet);
  10553. var newChildren = this.children.insert(front, newChild);
  10554. return new ImmutableTree(this.value, newChildren);
  10555. }
  10556. };
  10557. /**
  10558. * Removes the value at the specified path.
  10559. *
  10560. * @param relativePath - Path to value to remove.
  10561. * @returns Resulting tree.
  10562. */
  10563. ImmutableTree.prototype.remove = function (relativePath) {
  10564. if (pathIsEmpty(relativePath)) {
  10565. if (this.children.isEmpty()) {
  10566. return new ImmutableTree(null);
  10567. }
  10568. else {
  10569. return new ImmutableTree(null, this.children);
  10570. }
  10571. }
  10572. else {
  10573. var front = pathGetFront(relativePath);
  10574. var child = this.children.get(front);
  10575. if (child) {
  10576. var newChild = child.remove(pathPopFront(relativePath));
  10577. var newChildren = void 0;
  10578. if (newChild.isEmpty()) {
  10579. newChildren = this.children.remove(front);
  10580. }
  10581. else {
  10582. newChildren = this.children.insert(front, newChild);
  10583. }
  10584. if (this.value === null && newChildren.isEmpty()) {
  10585. return new ImmutableTree(null);
  10586. }
  10587. else {
  10588. return new ImmutableTree(this.value, newChildren);
  10589. }
  10590. }
  10591. else {
  10592. return this;
  10593. }
  10594. }
  10595. };
  10596. /**
  10597. * Gets a value from the tree.
  10598. *
  10599. * @param relativePath - Path to get value for.
  10600. * @returns Value at path, or null.
  10601. */
  10602. ImmutableTree.prototype.get = function (relativePath) {
  10603. if (pathIsEmpty(relativePath)) {
  10604. return this.value;
  10605. }
  10606. else {
  10607. var front = pathGetFront(relativePath);
  10608. var child = this.children.get(front);
  10609. if (child) {
  10610. return child.get(pathPopFront(relativePath));
  10611. }
  10612. else {
  10613. return null;
  10614. }
  10615. }
  10616. };
  10617. /**
  10618. * Replace the subtree at the specified path with the given new tree.
  10619. *
  10620. * @param relativePath - Path to replace subtree for.
  10621. * @param newTree - New tree.
  10622. * @returns Resulting tree.
  10623. */
  10624. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  10625. if (pathIsEmpty(relativePath)) {
  10626. return newTree;
  10627. }
  10628. else {
  10629. var front = pathGetFront(relativePath);
  10630. var child = this.children.get(front) || new ImmutableTree(null);
  10631. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  10632. var newChildren = void 0;
  10633. if (newChild.isEmpty()) {
  10634. newChildren = this.children.remove(front);
  10635. }
  10636. else {
  10637. newChildren = this.children.insert(front, newChild);
  10638. }
  10639. return new ImmutableTree(this.value, newChildren);
  10640. }
  10641. };
  10642. /**
  10643. * Performs a depth first fold on this tree. Transforms a tree into a single
  10644. * value, given a function that operates on the path to a node, an optional
  10645. * current value, and a map of child names to folded subtrees
  10646. */
  10647. ImmutableTree.prototype.fold = function (fn) {
  10648. return this.fold_(newEmptyPath(), fn);
  10649. };
  10650. /**
  10651. * Recursive helper for public-facing fold() method
  10652. */
  10653. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  10654. var accum = {};
  10655. this.children.inorderTraversal(function (childKey, childTree) {
  10656. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  10657. });
  10658. return fn(pathSoFar, this.value, accum);
  10659. };
  10660. /**
  10661. * Find the first matching value on the given path. Return the result of applying f to it.
  10662. */
  10663. ImmutableTree.prototype.findOnPath = function (path, f) {
  10664. return this.findOnPath_(path, newEmptyPath(), f);
  10665. };
  10666. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  10667. var result = this.value ? f(pathSoFar, this.value) : false;
  10668. if (result) {
  10669. return result;
  10670. }
  10671. else {
  10672. if (pathIsEmpty(pathToFollow)) {
  10673. return null;
  10674. }
  10675. else {
  10676. var front = pathGetFront(pathToFollow);
  10677. var nextChild = this.children.get(front);
  10678. if (nextChild) {
  10679. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  10680. }
  10681. else {
  10682. return null;
  10683. }
  10684. }
  10685. }
  10686. };
  10687. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  10688. return this.foreachOnPath_(path, newEmptyPath(), f);
  10689. };
  10690. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  10691. if (pathIsEmpty(pathToFollow)) {
  10692. return this;
  10693. }
  10694. else {
  10695. if (this.value) {
  10696. f(currentRelativePath, this.value);
  10697. }
  10698. var front = pathGetFront(pathToFollow);
  10699. var nextChild = this.children.get(front);
  10700. if (nextChild) {
  10701. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  10702. }
  10703. else {
  10704. return new ImmutableTree(null);
  10705. }
  10706. }
  10707. };
  10708. /**
  10709. * Calls the given function for each node in the tree that has a value.
  10710. *
  10711. * @param f - A function to be called with the path from the root of the tree to
  10712. * a node, and the value at that node. Called in depth-first order.
  10713. */
  10714. ImmutableTree.prototype.foreach = function (f) {
  10715. this.foreach_(newEmptyPath(), f);
  10716. };
  10717. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  10718. this.children.inorderTraversal(function (childName, childTree) {
  10719. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  10720. });
  10721. if (this.value) {
  10722. f(currentRelativePath, this.value);
  10723. }
  10724. };
  10725. ImmutableTree.prototype.foreachChild = function (f) {
  10726. this.children.inorderTraversal(function (childName, childTree) {
  10727. if (childTree.value) {
  10728. f(childName, childTree.value);
  10729. }
  10730. });
  10731. };
  10732. return ImmutableTree;
  10733. }());
  10734. /**
  10735. * @license
  10736. * Copyright 2017 Google LLC
  10737. *
  10738. * Licensed under the Apache License, Version 2.0 (the "License");
  10739. * you may not use this file except in compliance with the License.
  10740. * You may obtain a copy of the License at
  10741. *
  10742. * http://www.apache.org/licenses/LICENSE-2.0
  10743. *
  10744. * Unless required by applicable law or agreed to in writing, software
  10745. * distributed under the License is distributed on an "AS IS" BASIS,
  10746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10747. * See the License for the specific language governing permissions and
  10748. * limitations under the License.
  10749. */
  10750. /**
  10751. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  10752. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  10753. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  10754. * to reflect the write added.
  10755. */
  10756. var CompoundWrite = /** @class */ (function () {
  10757. function CompoundWrite(writeTree_) {
  10758. this.writeTree_ = writeTree_;
  10759. }
  10760. CompoundWrite.empty = function () {
  10761. return new CompoundWrite(new ImmutableTree(null));
  10762. };
  10763. return CompoundWrite;
  10764. }());
  10765. function compoundWriteAddWrite(compoundWrite, path, node) {
  10766. if (pathIsEmpty(path)) {
  10767. return new CompoundWrite(new ImmutableTree(node));
  10768. }
  10769. else {
  10770. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  10771. if (rootmost != null) {
  10772. var rootMostPath = rootmost.path;
  10773. var value = rootmost.value;
  10774. var relativePath = newRelativePath(rootMostPath, path);
  10775. value = value.updateChild(relativePath, node);
  10776. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  10777. }
  10778. else {
  10779. var subtree = new ImmutableTree(node);
  10780. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  10781. return new CompoundWrite(newWriteTree);
  10782. }
  10783. }
  10784. }
  10785. function compoundWriteAddWrites(compoundWrite, path, updates) {
  10786. var newWrite = compoundWrite;
  10787. each(updates, function (childKey, node) {
  10788. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  10789. });
  10790. return newWrite;
  10791. }
  10792. /**
  10793. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  10794. * location, which must be removed by calling this method with that path.
  10795. *
  10796. * @param compoundWrite - The CompoundWrite to remove.
  10797. * @param path - The path at which a write and all deeper writes should be removed
  10798. * @returns The new CompoundWrite with the removed path
  10799. */
  10800. function compoundWriteRemoveWrite(compoundWrite, path) {
  10801. if (pathIsEmpty(path)) {
  10802. return CompoundWrite.empty();
  10803. }
  10804. else {
  10805. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  10806. return new CompoundWrite(newWriteTree);
  10807. }
  10808. }
  10809. /**
  10810. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  10811. * considered "complete".
  10812. *
  10813. * @param compoundWrite - The CompoundWrite to check.
  10814. * @param path - The path to check for
  10815. * @returns Whether there is a complete write at that path
  10816. */
  10817. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  10818. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  10819. }
  10820. /**
  10821. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  10822. * writes from deeper paths, but will return child nodes from a more shallow path.
  10823. *
  10824. * @param compoundWrite - The CompoundWrite to get the node from.
  10825. * @param path - The path to get a complete write
  10826. * @returns The node if complete at that path, or null otherwise.
  10827. */
  10828. function compoundWriteGetCompleteNode(compoundWrite, path) {
  10829. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  10830. if (rootmost != null) {
  10831. return compoundWrite.writeTree_
  10832. .get(rootmost.path)
  10833. .getChild(newRelativePath(rootmost.path, path));
  10834. }
  10835. else {
  10836. return null;
  10837. }
  10838. }
  10839. /**
  10840. * Returns all children that are guaranteed to be a complete overwrite.
  10841. *
  10842. * @param compoundWrite - The CompoundWrite to get children from.
  10843. * @returns A list of all complete children.
  10844. */
  10845. function compoundWriteGetCompleteChildren(compoundWrite) {
  10846. var children = [];
  10847. var node = compoundWrite.writeTree_.value;
  10848. if (node != null) {
  10849. // If it's a leaf node, it has no children; so nothing to do.
  10850. if (!node.isLeafNode()) {
  10851. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10852. children.push(new NamedNode(childName, childNode));
  10853. });
  10854. }
  10855. }
  10856. else {
  10857. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  10858. if (childTree.value != null) {
  10859. children.push(new NamedNode(childName, childTree.value));
  10860. }
  10861. });
  10862. }
  10863. return children;
  10864. }
  10865. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  10866. if (pathIsEmpty(path)) {
  10867. return compoundWrite;
  10868. }
  10869. else {
  10870. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  10871. if (shadowingNode != null) {
  10872. return new CompoundWrite(new ImmutableTree(shadowingNode));
  10873. }
  10874. else {
  10875. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  10876. }
  10877. }
  10878. }
  10879. /**
  10880. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  10881. * @returns Whether this CompoundWrite is empty
  10882. */
  10883. function compoundWriteIsEmpty(compoundWrite) {
  10884. return compoundWrite.writeTree_.isEmpty();
  10885. }
  10886. /**
  10887. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  10888. * node
  10889. * @param node - The node to apply this CompoundWrite to
  10890. * @returns The node with all writes applied
  10891. */
  10892. function compoundWriteApply(compoundWrite, node) {
  10893. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  10894. }
  10895. function applySubtreeWrite(relativePath, writeTree, node) {
  10896. if (writeTree.value != null) {
  10897. // Since there a write is always a leaf, we're done here
  10898. return node.updateChild(relativePath, writeTree.value);
  10899. }
  10900. else {
  10901. var priorityWrite_1 = null;
  10902. writeTree.children.inorderTraversal(function (childKey, childTree) {
  10903. if (childKey === '.priority') {
  10904. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  10905. // to apply priorities to empty nodes that are later filled
  10906. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  10907. priorityWrite_1 = childTree.value;
  10908. }
  10909. else {
  10910. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  10911. }
  10912. });
  10913. // If there was a priority write, we only apply it if the node is not empty
  10914. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  10915. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  10916. }
  10917. return node;
  10918. }
  10919. }
  10920. /**
  10921. * @license
  10922. * Copyright 2017 Google LLC
  10923. *
  10924. * Licensed under the Apache License, Version 2.0 (the "License");
  10925. * you may not use this file except in compliance with the License.
  10926. * You may obtain a copy of the License at
  10927. *
  10928. * http://www.apache.org/licenses/LICENSE-2.0
  10929. *
  10930. * Unless required by applicable law or agreed to in writing, software
  10931. * distributed under the License is distributed on an "AS IS" BASIS,
  10932. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10933. * See the License for the specific language governing permissions and
  10934. * limitations under the License.
  10935. */
  10936. /**
  10937. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  10938. *
  10939. */
  10940. function writeTreeChildWrites(writeTree, path) {
  10941. return newWriteTreeRef(path, writeTree);
  10942. }
  10943. /**
  10944. * Record a new overwrite from user code.
  10945. *
  10946. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  10947. */
  10948. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  10949. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  10950. if (visible === undefined) {
  10951. visible = true;
  10952. }
  10953. writeTree.allWrites.push({
  10954. path: path,
  10955. snap: snap,
  10956. writeId: writeId,
  10957. visible: visible
  10958. });
  10959. if (visible) {
  10960. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  10961. }
  10962. writeTree.lastWriteId = writeId;
  10963. }
  10964. /**
  10965. * Record a new merge from user code.
  10966. */
  10967. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  10968. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  10969. writeTree.allWrites.push({
  10970. path: path,
  10971. children: changedChildren,
  10972. writeId: writeId,
  10973. visible: true
  10974. });
  10975. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  10976. writeTree.lastWriteId = writeId;
  10977. }
  10978. function writeTreeGetWrite(writeTree, writeId) {
  10979. for (var i = 0; i < writeTree.allWrites.length; i++) {
  10980. var record = writeTree.allWrites[i];
  10981. if (record.writeId === writeId) {
  10982. return record;
  10983. }
  10984. }
  10985. return null;
  10986. }
  10987. /**
  10988. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  10989. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  10990. *
  10991. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  10992. * events as a result).
  10993. */
  10994. function writeTreeRemoveWrite(writeTree, writeId) {
  10995. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  10996. // out of order.
  10997. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  10998. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  10999. var idx = writeTree.allWrites.findIndex(function (s) {
  11000. return s.writeId === writeId;
  11001. });
  11002. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  11003. var writeToRemove = writeTree.allWrites[idx];
  11004. writeTree.allWrites.splice(idx, 1);
  11005. var removedWriteWasVisible = writeToRemove.visible;
  11006. var removedWriteOverlapsWithOtherWrites = false;
  11007. var i = writeTree.allWrites.length - 1;
  11008. while (removedWriteWasVisible && i >= 0) {
  11009. var currentWrite = writeTree.allWrites[i];
  11010. if (currentWrite.visible) {
  11011. if (i >= idx &&
  11012. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  11013. // The removed write was completely shadowed by a subsequent write.
  11014. removedWriteWasVisible = false;
  11015. }
  11016. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  11017. // Either we're covering some writes or they're covering part of us (depending on which came first).
  11018. removedWriteOverlapsWithOtherWrites = true;
  11019. }
  11020. }
  11021. i--;
  11022. }
  11023. if (!removedWriteWasVisible) {
  11024. return false;
  11025. }
  11026. else if (removedWriteOverlapsWithOtherWrites) {
  11027. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  11028. writeTreeResetTree_(writeTree);
  11029. return true;
  11030. }
  11031. else {
  11032. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  11033. if (writeToRemove.snap) {
  11034. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  11035. }
  11036. else {
  11037. var children = writeToRemove.children;
  11038. each(children, function (childName) {
  11039. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  11040. });
  11041. }
  11042. return true;
  11043. }
  11044. }
  11045. function writeTreeRecordContainsPath_(writeRecord, path) {
  11046. if (writeRecord.snap) {
  11047. return pathContains(writeRecord.path, path);
  11048. }
  11049. else {
  11050. for (var childName in writeRecord.children) {
  11051. if (writeRecord.children.hasOwnProperty(childName) &&
  11052. pathContains(pathChild(writeRecord.path, childName), path)) {
  11053. return true;
  11054. }
  11055. }
  11056. return false;
  11057. }
  11058. }
  11059. /**
  11060. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  11061. */
  11062. function writeTreeResetTree_(writeTree) {
  11063. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  11064. if (writeTree.allWrites.length > 0) {
  11065. writeTree.lastWriteId =
  11066. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  11067. }
  11068. else {
  11069. writeTree.lastWriteId = -1;
  11070. }
  11071. }
  11072. /**
  11073. * The default filter used when constructing the tree. Keep everything that's visible.
  11074. */
  11075. function writeTreeDefaultFilter_(write) {
  11076. return write.visible;
  11077. }
  11078. /**
  11079. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  11080. * event data at that path.
  11081. */
  11082. function writeTreeLayerTree_(writes, filter, treeRoot) {
  11083. var compoundWrite = CompoundWrite.empty();
  11084. for (var i = 0; i < writes.length; ++i) {
  11085. var write = writes[i];
  11086. // Theory, a later set will either:
  11087. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  11088. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  11089. if (filter(write)) {
  11090. var writePath = write.path;
  11091. var relativePath = void 0;
  11092. if (write.snap) {
  11093. if (pathContains(treeRoot, writePath)) {
  11094. relativePath = newRelativePath(treeRoot, writePath);
  11095. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  11096. }
  11097. else if (pathContains(writePath, treeRoot)) {
  11098. relativePath = newRelativePath(writePath, treeRoot);
  11099. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  11100. }
  11101. else ;
  11102. }
  11103. else if (write.children) {
  11104. if (pathContains(treeRoot, writePath)) {
  11105. relativePath = newRelativePath(treeRoot, writePath);
  11106. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  11107. }
  11108. else if (pathContains(writePath, treeRoot)) {
  11109. relativePath = newRelativePath(writePath, treeRoot);
  11110. if (pathIsEmpty(relativePath)) {
  11111. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  11112. }
  11113. else {
  11114. var child = util.safeGet(write.children, pathGetFront(relativePath));
  11115. if (child) {
  11116. // There exists a child in this node that matches the root path
  11117. var deepNode = child.getChild(pathPopFront(relativePath));
  11118. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  11119. }
  11120. }
  11121. }
  11122. else ;
  11123. }
  11124. else {
  11125. throw util.assertionError('WriteRecord should have .snap or .children');
  11126. }
  11127. }
  11128. }
  11129. return compoundWrite;
  11130. }
  11131. /**
  11132. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  11133. * writes), attempt to calculate a complete snapshot for the given path
  11134. *
  11135. * @param writeIdsToExclude - An optional set to be excluded
  11136. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  11137. */
  11138. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  11139. if (!writeIdsToExclude && !includeHiddenWrites) {
  11140. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  11141. if (shadowingNode != null) {
  11142. return shadowingNode;
  11143. }
  11144. else {
  11145. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11146. if (compoundWriteIsEmpty(subMerge)) {
  11147. return completeServerCache;
  11148. }
  11149. else if (completeServerCache == null &&
  11150. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  11151. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  11152. return null;
  11153. }
  11154. else {
  11155. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  11156. return compoundWriteApply(subMerge, layeredCache);
  11157. }
  11158. }
  11159. }
  11160. else {
  11161. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11162. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  11163. return completeServerCache;
  11164. }
  11165. else {
  11166. // If the server cache is null, and we don't have a complete cache, we need to return null
  11167. if (!includeHiddenWrites &&
  11168. completeServerCache == null &&
  11169. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  11170. return null;
  11171. }
  11172. else {
  11173. var filter = function (write) {
  11174. return ((write.visible || includeHiddenWrites) &&
  11175. (!writeIdsToExclude ||
  11176. !~writeIdsToExclude.indexOf(write.writeId)) &&
  11177. (pathContains(write.path, treePath) ||
  11178. pathContains(treePath, write.path)));
  11179. };
  11180. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  11181. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  11182. return compoundWriteApply(mergeAtPath, layeredCache);
  11183. }
  11184. }
  11185. }
  11186. }
  11187. /**
  11188. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  11189. * Used when creating new views, to pre-fill their complete event children snapshot.
  11190. */
  11191. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  11192. var completeChildren = ChildrenNode.EMPTY_NODE;
  11193. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  11194. if (topLevelSet) {
  11195. if (!topLevelSet.isLeafNode()) {
  11196. // we're shadowing everything. Return the children.
  11197. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  11198. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  11199. });
  11200. }
  11201. return completeChildren;
  11202. }
  11203. else if (completeServerChildren) {
  11204. // Layer any children we have on top of this
  11205. // We know we don't have a top-level set, so just enumerate existing children
  11206. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11207. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  11208. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  11209. completeChildren = completeChildren.updateImmediateChild(childName, node);
  11210. });
  11211. // Add any complete children we have from the set
  11212. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  11213. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  11214. });
  11215. return completeChildren;
  11216. }
  11217. else {
  11218. // We don't have anything to layer on top of. Layer on any children we have
  11219. // Note that we can return an empty snap if we have a defined delete
  11220. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11221. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  11222. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  11223. });
  11224. return completeChildren;
  11225. }
  11226. }
  11227. /**
  11228. * Given that the underlying server data has updated, determine what, if anything, needs to be
  11229. * applied to the event cache.
  11230. *
  11231. * Possibilities:
  11232. *
  11233. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  11234. *
  11235. * 2. Some write is completely shadowing. No events to be raised
  11236. *
  11237. * 3. Is partially shadowed. Events
  11238. *
  11239. * Either existingEventSnap or existingServerSnap must exist
  11240. */
  11241. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  11242. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  11243. var path = pathChild(treePath, childPath);
  11244. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  11245. // At this point we can probably guarantee that we're in case 2, meaning no events
  11246. // May need to check visibility while doing the findRootMostValueAndPath call
  11247. return null;
  11248. }
  11249. else {
  11250. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  11251. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  11252. if (compoundWriteIsEmpty(childMerge)) {
  11253. // We're not shadowing at all. Case 1
  11254. return existingServerSnap.getChild(childPath);
  11255. }
  11256. else {
  11257. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  11258. // However this is tricky to find out, since user updates don't necessary change the server
  11259. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  11260. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  11261. // only check if the updates change the serverNode.
  11262. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  11263. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  11264. }
  11265. }
  11266. }
  11267. /**
  11268. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  11269. * complete child for this ChildKey.
  11270. */
  11271. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  11272. var path = pathChild(treePath, childKey);
  11273. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  11274. if (shadowingNode != null) {
  11275. return shadowingNode;
  11276. }
  11277. else {
  11278. if (existingServerSnap.isCompleteForChild(childKey)) {
  11279. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  11280. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  11281. }
  11282. else {
  11283. return null;
  11284. }
  11285. }
  11286. }
  11287. /**
  11288. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  11289. * a higher path, this will return the child of that write relative to the write and this path.
  11290. * Returns null if there is no write at this path.
  11291. */
  11292. function writeTreeShadowingWrite(writeTree, path) {
  11293. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  11294. }
  11295. /**
  11296. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  11297. * the window, but may now be in the window.
  11298. */
  11299. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  11300. var toIterate;
  11301. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  11302. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  11303. if (shadowingNode != null) {
  11304. toIterate = shadowingNode;
  11305. }
  11306. else if (completeServerData != null) {
  11307. toIterate = compoundWriteApply(merge, completeServerData);
  11308. }
  11309. else {
  11310. // no children to iterate on
  11311. return [];
  11312. }
  11313. toIterate = toIterate.withIndex(index);
  11314. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  11315. var nodes = [];
  11316. var cmp = index.getCompare();
  11317. var iter = reverse
  11318. ? toIterate.getReverseIteratorFrom(startPost, index)
  11319. : toIterate.getIteratorFrom(startPost, index);
  11320. var next = iter.getNext();
  11321. while (next && nodes.length < count) {
  11322. if (cmp(next, startPost) !== 0) {
  11323. nodes.push(next);
  11324. }
  11325. next = iter.getNext();
  11326. }
  11327. return nodes;
  11328. }
  11329. else {
  11330. return [];
  11331. }
  11332. }
  11333. function newWriteTree() {
  11334. return {
  11335. visibleWrites: CompoundWrite.empty(),
  11336. allWrites: [],
  11337. lastWriteId: -1
  11338. };
  11339. }
  11340. /**
  11341. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  11342. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  11343. * can lead to a more expensive calculation.
  11344. *
  11345. * @param writeIdsToExclude - Optional writes to exclude.
  11346. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  11347. */
  11348. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  11349. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  11350. }
  11351. /**
  11352. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  11353. * mix of the given server data and write data.
  11354. *
  11355. */
  11356. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  11357. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  11358. }
  11359. /**
  11360. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  11361. * if anything, needs to be applied to the event cache.
  11362. *
  11363. * Possibilities:
  11364. *
  11365. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  11366. *
  11367. * 2. Some write is completely shadowing. No events to be raised
  11368. *
  11369. * 3. Is partially shadowed. Events should be raised
  11370. *
  11371. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  11372. *
  11373. *
  11374. */
  11375. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  11376. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  11377. }
  11378. /**
  11379. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  11380. * a higher path, this will return the child of that write relative to the write and this path.
  11381. * Returns null if there is no write at this path.
  11382. *
  11383. */
  11384. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  11385. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  11386. }
  11387. /**
  11388. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  11389. * the window, but may now be in the window
  11390. */
  11391. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  11392. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  11393. }
  11394. /**
  11395. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  11396. * complete child for this ChildKey.
  11397. */
  11398. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  11399. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  11400. }
  11401. /**
  11402. * Return a WriteTreeRef for a child.
  11403. */
  11404. function writeTreeRefChild(writeTreeRef, childName) {
  11405. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  11406. }
  11407. function newWriteTreeRef(path, writeTree) {
  11408. return {
  11409. treePath: path,
  11410. writeTree: writeTree
  11411. };
  11412. }
  11413. /**
  11414. * @license
  11415. * Copyright 2017 Google LLC
  11416. *
  11417. * Licensed under the Apache License, Version 2.0 (the "License");
  11418. * you may not use this file except in compliance with the License.
  11419. * You may obtain a copy of the License at
  11420. *
  11421. * http://www.apache.org/licenses/LICENSE-2.0
  11422. *
  11423. * Unless required by applicable law or agreed to in writing, software
  11424. * distributed under the License is distributed on an "AS IS" BASIS,
  11425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11426. * See the License for the specific language governing permissions and
  11427. * limitations under the License.
  11428. */
  11429. var ChildChangeAccumulator = /** @class */ (function () {
  11430. function ChildChangeAccumulator() {
  11431. this.changeMap = new Map();
  11432. }
  11433. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  11434. var type = change.type;
  11435. var childKey = change.childName;
  11436. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  11437. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  11438. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  11439. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  11440. var oldChange = this.changeMap.get(childKey);
  11441. if (oldChange) {
  11442. var oldType = oldChange.type;
  11443. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  11444. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  11445. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  11446. }
  11447. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  11448. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  11449. this.changeMap.delete(childKey);
  11450. }
  11451. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  11452. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  11453. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  11454. }
  11455. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  11456. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  11457. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  11458. }
  11459. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  11460. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  11461. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  11462. }
  11463. else {
  11464. throw util.assertionError('Illegal combination of changes: ' +
  11465. change +
  11466. ' occurred after ' +
  11467. oldChange);
  11468. }
  11469. }
  11470. else {
  11471. this.changeMap.set(childKey, change);
  11472. }
  11473. };
  11474. ChildChangeAccumulator.prototype.getChanges = function () {
  11475. return Array.from(this.changeMap.values());
  11476. };
  11477. return ChildChangeAccumulator;
  11478. }());
  11479. /**
  11480. * @license
  11481. * Copyright 2017 Google LLC
  11482. *
  11483. * Licensed under the Apache License, Version 2.0 (the "License");
  11484. * you may not use this file except in compliance with the License.
  11485. * You may obtain a copy of the License at
  11486. *
  11487. * http://www.apache.org/licenses/LICENSE-2.0
  11488. *
  11489. * Unless required by applicable law or agreed to in writing, software
  11490. * distributed under the License is distributed on an "AS IS" BASIS,
  11491. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11492. * See the License for the specific language governing permissions and
  11493. * limitations under the License.
  11494. */
  11495. /**
  11496. * An implementation of CompleteChildSource that never returns any additional children
  11497. */
  11498. // eslint-disable-next-line @typescript-eslint/naming-convention
  11499. var NoCompleteChildSource_ = /** @class */ (function () {
  11500. function NoCompleteChildSource_() {
  11501. }
  11502. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  11503. return null;
  11504. };
  11505. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  11506. return null;
  11507. };
  11508. return NoCompleteChildSource_;
  11509. }());
  11510. /**
  11511. * Singleton instance.
  11512. */
  11513. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  11514. /**
  11515. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  11516. * old event caches available to calculate complete children.
  11517. */
  11518. var WriteTreeCompleteChildSource = /** @class */ (function () {
  11519. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  11520. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  11521. this.writes_ = writes_;
  11522. this.viewCache_ = viewCache_;
  11523. this.optCompleteServerCache_ = optCompleteServerCache_;
  11524. }
  11525. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  11526. var node = this.viewCache_.eventCache;
  11527. if (node.isCompleteForChild(childKey)) {
  11528. return node.getNode().getImmediateChild(childKey);
  11529. }
  11530. else {
  11531. var serverNode = this.optCompleteServerCache_ != null
  11532. ? new CacheNode(this.optCompleteServerCache_, true, false)
  11533. : this.viewCache_.serverCache;
  11534. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  11535. }
  11536. };
  11537. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  11538. var completeServerData = this.optCompleteServerCache_ != null
  11539. ? this.optCompleteServerCache_
  11540. : viewCacheGetCompleteServerSnap(this.viewCache_);
  11541. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  11542. if (nodes.length === 0) {
  11543. return null;
  11544. }
  11545. else {
  11546. return nodes[0];
  11547. }
  11548. };
  11549. return WriteTreeCompleteChildSource;
  11550. }());
  11551. /**
  11552. * @license
  11553. * Copyright 2017 Google LLC
  11554. *
  11555. * Licensed under the Apache License, Version 2.0 (the "License");
  11556. * you may not use this file except in compliance with the License.
  11557. * You may obtain a copy of the License at
  11558. *
  11559. * http://www.apache.org/licenses/LICENSE-2.0
  11560. *
  11561. * Unless required by applicable law or agreed to in writing, software
  11562. * distributed under the License is distributed on an "AS IS" BASIS,
  11563. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11564. * See the License for the specific language governing permissions and
  11565. * limitations under the License.
  11566. */
  11567. function newViewProcessor(filter) {
  11568. return { filter: filter };
  11569. }
  11570. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  11571. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  11572. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  11573. }
  11574. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  11575. var accumulator = new ChildChangeAccumulator();
  11576. var newViewCache, filterServerNode;
  11577. if (operation.type === OperationType.OVERWRITE) {
  11578. var overwrite = operation;
  11579. if (overwrite.source.fromUser) {
  11580. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  11581. }
  11582. else {
  11583. util.assert(overwrite.source.fromServer, 'Unknown source.');
  11584. // We filter the node if it's a tagged update or the node has been previously filtered and the
  11585. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  11586. // again
  11587. filterServerNode =
  11588. overwrite.source.tagged ||
  11589. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  11590. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  11591. }
  11592. }
  11593. else if (operation.type === OperationType.MERGE) {
  11594. var merge = operation;
  11595. if (merge.source.fromUser) {
  11596. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  11597. }
  11598. else {
  11599. util.assert(merge.source.fromServer, 'Unknown source.');
  11600. // We filter the node if it's a tagged update or the node has been previously filtered
  11601. filterServerNode =
  11602. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  11603. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  11604. }
  11605. }
  11606. else if (operation.type === OperationType.ACK_USER_WRITE) {
  11607. var ackUserWrite = operation;
  11608. if (!ackUserWrite.revert) {
  11609. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  11610. }
  11611. else {
  11612. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  11613. }
  11614. }
  11615. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  11616. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  11617. }
  11618. else {
  11619. throw util.assertionError('Unknown operation type: ' + operation.type);
  11620. }
  11621. var changes = accumulator.getChanges();
  11622. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  11623. return { viewCache: newViewCache, changes: changes };
  11624. }
  11625. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  11626. var eventSnap = newViewCache.eventCache;
  11627. if (eventSnap.isFullyInitialized()) {
  11628. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  11629. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  11630. if (accumulator.length > 0 ||
  11631. !oldViewCache.eventCache.isFullyInitialized() ||
  11632. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  11633. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  11634. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  11635. }
  11636. }
  11637. }
  11638. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  11639. var oldEventSnap = viewCache.eventCache;
  11640. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  11641. // we have a shadowing write, ignore changes
  11642. return viewCache;
  11643. }
  11644. else {
  11645. var newEventCache = void 0, serverNode = void 0;
  11646. if (pathIsEmpty(changePath)) {
  11647. // TODO: figure out how this plays with "sliding ack windows"
  11648. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  11649. if (viewCache.serverCache.isFiltered()) {
  11650. // We need to special case this, because we need to only apply writes to complete children, or
  11651. // we might end up raising events for incomplete children. If the server data is filtered deep
  11652. // writes cannot be guaranteed to be complete
  11653. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  11654. var completeChildren = serverCache instanceof ChildrenNode
  11655. ? serverCache
  11656. : ChildrenNode.EMPTY_NODE;
  11657. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  11658. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  11659. }
  11660. else {
  11661. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11662. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  11663. }
  11664. }
  11665. else {
  11666. var childKey = pathGetFront(changePath);
  11667. if (childKey === '.priority') {
  11668. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  11669. var oldEventNode = oldEventSnap.getNode();
  11670. serverNode = viewCache.serverCache.getNode();
  11671. // we might have overwrites for this priority
  11672. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  11673. if (updatedPriority != null) {
  11674. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  11675. }
  11676. else {
  11677. // priority didn't change, keep old node
  11678. newEventCache = oldEventSnap.getNode();
  11679. }
  11680. }
  11681. else {
  11682. var childChangePath = pathPopFront(changePath);
  11683. // update child
  11684. var newEventChild = void 0;
  11685. if (oldEventSnap.isCompleteForChild(childKey)) {
  11686. serverNode = viewCache.serverCache.getNode();
  11687. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  11688. if (eventChildUpdate != null) {
  11689. newEventChild = oldEventSnap
  11690. .getNode()
  11691. .getImmediateChild(childKey)
  11692. .updateChild(childChangePath, eventChildUpdate);
  11693. }
  11694. else {
  11695. // Nothing changed, just keep the old child
  11696. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  11697. }
  11698. }
  11699. else {
  11700. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  11701. }
  11702. if (newEventChild != null) {
  11703. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  11704. }
  11705. else {
  11706. // no complete child available or no change
  11707. newEventCache = oldEventSnap.getNode();
  11708. }
  11709. }
  11710. }
  11711. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  11712. }
  11713. }
  11714. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  11715. var oldServerSnap = oldViewCache.serverCache;
  11716. var newServerCache;
  11717. var serverFilter = filterServerNode
  11718. ? viewProcessor.filter
  11719. : viewProcessor.filter.getIndexedFilter();
  11720. if (pathIsEmpty(changePath)) {
  11721. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  11722. }
  11723. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  11724. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  11725. var newServerNode = oldServerSnap
  11726. .getNode()
  11727. .updateChild(changePath, changedSnap);
  11728. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  11729. }
  11730. else {
  11731. var childKey = pathGetFront(changePath);
  11732. if (!oldServerSnap.isCompleteForPath(changePath) &&
  11733. pathGetLength(changePath) > 1) {
  11734. // We don't update incomplete nodes with updates intended for other listeners
  11735. return oldViewCache;
  11736. }
  11737. var childChangePath = pathPopFront(changePath);
  11738. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  11739. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  11740. if (childKey === '.priority') {
  11741. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  11742. }
  11743. else {
  11744. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  11745. }
  11746. }
  11747. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  11748. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  11749. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  11750. }
  11751. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  11752. var oldEventSnap = oldViewCache.eventCache;
  11753. var newViewCache, newEventCache;
  11754. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  11755. if (pathIsEmpty(changePath)) {
  11756. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  11757. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  11758. }
  11759. else {
  11760. var childKey = pathGetFront(changePath);
  11761. if (childKey === '.priority') {
  11762. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  11763. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  11764. }
  11765. else {
  11766. var childChangePath = pathPopFront(changePath);
  11767. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  11768. var newChild = void 0;
  11769. if (pathIsEmpty(childChangePath)) {
  11770. // Child overwrite, we can replace the child
  11771. newChild = changedSnap;
  11772. }
  11773. else {
  11774. var childNode = source.getCompleteChild(childKey);
  11775. if (childNode != null) {
  11776. if (pathGetBack(childChangePath) === '.priority' &&
  11777. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  11778. // This is a priority update on an empty node. If this node exists on the server, the
  11779. // server will send down the priority in the update, so ignore for now
  11780. newChild = childNode;
  11781. }
  11782. else {
  11783. newChild = childNode.updateChild(childChangePath, changedSnap);
  11784. }
  11785. }
  11786. else {
  11787. // There is no complete child node available
  11788. newChild = ChildrenNode.EMPTY_NODE;
  11789. }
  11790. }
  11791. if (!oldChild.equals(newChild)) {
  11792. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  11793. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  11794. }
  11795. else {
  11796. newViewCache = oldViewCache;
  11797. }
  11798. }
  11799. }
  11800. return newViewCache;
  11801. }
  11802. function viewProcessorCacheHasChild(viewCache, childKey) {
  11803. return viewCache.eventCache.isCompleteForChild(childKey);
  11804. }
  11805. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  11806. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  11807. // window leaving room for new items. It's important we process these changes first, so we
  11808. // iterate the changes twice, first processing any that affect items currently in view.
  11809. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  11810. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  11811. // not the other.
  11812. var curViewCache = viewCache;
  11813. changedChildren.foreach(function (relativePath, childNode) {
  11814. var writePath = pathChild(path, relativePath);
  11815. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  11816. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  11817. }
  11818. });
  11819. changedChildren.foreach(function (relativePath, childNode) {
  11820. var writePath = pathChild(path, relativePath);
  11821. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  11822. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  11823. }
  11824. });
  11825. return curViewCache;
  11826. }
  11827. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  11828. merge.foreach(function (relativePath, childNode) {
  11829. node = node.updateChild(relativePath, childNode);
  11830. });
  11831. return node;
  11832. }
  11833. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  11834. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  11835. // wait for the complete data update coming soon.
  11836. if (viewCache.serverCache.getNode().isEmpty() &&
  11837. !viewCache.serverCache.isFullyInitialized()) {
  11838. return viewCache;
  11839. }
  11840. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  11841. // window leaving room for new items. It's important we process these changes first, so we
  11842. // iterate the changes twice, first processing any that affect items currently in view.
  11843. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  11844. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  11845. // not the other.
  11846. var curViewCache = viewCache;
  11847. var viewMergeTree;
  11848. if (pathIsEmpty(path)) {
  11849. viewMergeTree = changedChildren;
  11850. }
  11851. else {
  11852. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  11853. }
  11854. var serverNode = viewCache.serverCache.getNode();
  11855. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  11856. if (serverNode.hasChild(childKey)) {
  11857. var serverChild = viewCache.serverCache
  11858. .getNode()
  11859. .getImmediateChild(childKey);
  11860. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  11861. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  11862. }
  11863. });
  11864. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  11865. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  11866. childMergeTree.value === null;
  11867. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  11868. var serverChild = viewCache.serverCache
  11869. .getNode()
  11870. .getImmediateChild(childKey);
  11871. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  11872. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  11873. }
  11874. });
  11875. return curViewCache;
  11876. }
  11877. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  11878. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  11879. return viewCache;
  11880. }
  11881. // Only filter server node if it is currently filtered
  11882. var filterServerNode = viewCache.serverCache.isFiltered();
  11883. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  11884. // now that it won't be shadowed.
  11885. var serverCache = viewCache.serverCache;
  11886. if (affectedTree.value != null) {
  11887. // This is an overwrite.
  11888. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  11889. serverCache.isCompleteForPath(ackPath)) {
  11890. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  11891. }
  11892. else if (pathIsEmpty(ackPath)) {
  11893. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  11894. // should just re-apply whatever we have in our cache as a merge.
  11895. var changedChildren_1 = new ImmutableTree(null);
  11896. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  11897. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  11898. });
  11899. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  11900. }
  11901. else {
  11902. return viewCache;
  11903. }
  11904. }
  11905. else {
  11906. // This is a merge.
  11907. var changedChildren_2 = new ImmutableTree(null);
  11908. affectedTree.foreach(function (mergePath, value) {
  11909. var serverCachePath = pathChild(ackPath, mergePath);
  11910. if (serverCache.isCompleteForPath(serverCachePath)) {
  11911. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  11912. }
  11913. });
  11914. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  11915. }
  11916. }
  11917. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  11918. var oldServerNode = viewCache.serverCache;
  11919. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  11920. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  11921. }
  11922. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  11923. var complete;
  11924. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  11925. return viewCache;
  11926. }
  11927. else {
  11928. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  11929. var oldEventCache = viewCache.eventCache.getNode();
  11930. var newEventCache = void 0;
  11931. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  11932. var newNode = void 0;
  11933. if (viewCache.serverCache.isFullyInitialized()) {
  11934. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11935. }
  11936. else {
  11937. var serverChildren = viewCache.serverCache.getNode();
  11938. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  11939. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  11940. }
  11941. newNode = newNode;
  11942. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  11943. }
  11944. else {
  11945. var childKey = pathGetFront(path);
  11946. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  11947. if (newChild == null &&
  11948. viewCache.serverCache.isCompleteForChild(childKey)) {
  11949. newChild = oldEventCache.getImmediateChild(childKey);
  11950. }
  11951. if (newChild != null) {
  11952. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  11953. }
  11954. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  11955. // No complete child available, delete the existing one, if any
  11956. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  11957. }
  11958. else {
  11959. newEventCache = oldEventCache;
  11960. }
  11961. if (newEventCache.isEmpty() &&
  11962. viewCache.serverCache.isFullyInitialized()) {
  11963. // We might have reverted all child writes. Maybe the old event was a leaf node
  11964. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  11965. if (complete.isLeafNode()) {
  11966. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  11967. }
  11968. }
  11969. }
  11970. complete =
  11971. viewCache.serverCache.isFullyInitialized() ||
  11972. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  11973. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  11974. }
  11975. }
  11976. /**
  11977. * @license
  11978. * Copyright 2017 Google LLC
  11979. *
  11980. * Licensed under the Apache License, Version 2.0 (the "License");
  11981. * you may not use this file except in compliance with the License.
  11982. * You may obtain a copy of the License at
  11983. *
  11984. * http://www.apache.org/licenses/LICENSE-2.0
  11985. *
  11986. * Unless required by applicable law or agreed to in writing, software
  11987. * distributed under the License is distributed on an "AS IS" BASIS,
  11988. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11989. * See the License for the specific language governing permissions and
  11990. * limitations under the License.
  11991. */
  11992. /**
  11993. * A view represents a specific location and query that has 1 or more event registrations.
  11994. *
  11995. * It does several things:
  11996. * - Maintains the list of event registrations for this location/query.
  11997. * - Maintains a cache of the data visible for this location/query.
  11998. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  11999. * registrations returns the set of events to be raised.
  12000. */
  12001. var View = /** @class */ (function () {
  12002. function View(query_, initialViewCache) {
  12003. this.query_ = query_;
  12004. this.eventRegistrations_ = [];
  12005. var params = this.query_._queryParams;
  12006. var indexFilter = new IndexedFilter(params.getIndex());
  12007. var filter = queryParamsGetNodeFilter(params);
  12008. this.processor_ = newViewProcessor(filter);
  12009. var initialServerCache = initialViewCache.serverCache;
  12010. var initialEventCache = initialViewCache.eventCache;
  12011. // Don't filter server node with other filter than index, wait for tagged listen
  12012. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  12013. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  12014. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  12015. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  12016. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  12017. this.eventGenerator_ = new EventGenerator(this.query_);
  12018. }
  12019. Object.defineProperty(View.prototype, "query", {
  12020. get: function () {
  12021. return this.query_;
  12022. },
  12023. enumerable: false,
  12024. configurable: true
  12025. });
  12026. return View;
  12027. }());
  12028. function viewGetServerCache(view) {
  12029. return view.viewCache_.serverCache.getNode();
  12030. }
  12031. function viewGetCompleteNode(view) {
  12032. return viewCacheGetCompleteEventSnap(view.viewCache_);
  12033. }
  12034. function viewGetCompleteServerCache(view, path) {
  12035. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  12036. if (cache) {
  12037. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  12038. // we need to see if it contains the child we're interested in.
  12039. if (view.query._queryParams.loadsAllData() ||
  12040. (!pathIsEmpty(path) &&
  12041. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  12042. return cache.getChild(path);
  12043. }
  12044. }
  12045. return null;
  12046. }
  12047. function viewIsEmpty(view) {
  12048. return view.eventRegistrations_.length === 0;
  12049. }
  12050. function viewAddEventRegistration(view, eventRegistration) {
  12051. view.eventRegistrations_.push(eventRegistration);
  12052. }
  12053. /**
  12054. * @param eventRegistration - If null, remove all callbacks.
  12055. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  12056. * @returns Cancel events, if cancelError was provided.
  12057. */
  12058. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  12059. var cancelEvents = [];
  12060. if (cancelError) {
  12061. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  12062. var path_1 = view.query._path;
  12063. view.eventRegistrations_.forEach(function (registration) {
  12064. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  12065. if (maybeEvent) {
  12066. cancelEvents.push(maybeEvent);
  12067. }
  12068. });
  12069. }
  12070. if (eventRegistration) {
  12071. var remaining = [];
  12072. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  12073. var existing = view.eventRegistrations_[i];
  12074. if (!existing.matches(eventRegistration)) {
  12075. remaining.push(existing);
  12076. }
  12077. else if (eventRegistration.hasAnyCallback()) {
  12078. // We're removing just this one
  12079. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  12080. break;
  12081. }
  12082. }
  12083. view.eventRegistrations_ = remaining;
  12084. }
  12085. else {
  12086. view.eventRegistrations_ = [];
  12087. }
  12088. return cancelEvents;
  12089. }
  12090. /**
  12091. * Applies the given Operation, updates our cache, and returns the appropriate events.
  12092. */
  12093. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  12094. if (operation.type === OperationType.MERGE &&
  12095. operation.source.queryId !== null) {
  12096. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  12097. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  12098. }
  12099. var oldViewCache = view.viewCache_;
  12100. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  12101. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  12102. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  12103. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  12104. view.viewCache_ = result.viewCache;
  12105. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  12106. }
  12107. function viewGetInitialEvents(view, registration) {
  12108. var eventSnap = view.viewCache_.eventCache;
  12109. var initialChanges = [];
  12110. if (!eventSnap.getNode().isLeafNode()) {
  12111. var eventNode = eventSnap.getNode();
  12112. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  12113. initialChanges.push(changeChildAdded(key, childNode));
  12114. });
  12115. }
  12116. if (eventSnap.isFullyInitialized()) {
  12117. initialChanges.push(changeValue(eventSnap.getNode()));
  12118. }
  12119. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  12120. }
  12121. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  12122. var registrations = eventRegistration
  12123. ? [eventRegistration]
  12124. : view.eventRegistrations_;
  12125. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  12126. }
  12127. /**
  12128. * @license
  12129. * Copyright 2017 Google LLC
  12130. *
  12131. * Licensed under the Apache License, Version 2.0 (the "License");
  12132. * you may not use this file except in compliance with the License.
  12133. * You may obtain a copy of the License at
  12134. *
  12135. * http://www.apache.org/licenses/LICENSE-2.0
  12136. *
  12137. * Unless required by applicable law or agreed to in writing, software
  12138. * distributed under the License is distributed on an "AS IS" BASIS,
  12139. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12140. * See the License for the specific language governing permissions and
  12141. * limitations under the License.
  12142. */
  12143. var referenceConstructor$1;
  12144. /**
  12145. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  12146. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  12147. * and user writes (set, transaction, update).
  12148. *
  12149. * It's responsible for:
  12150. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  12151. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  12152. * applyUserOverwrite, etc.)
  12153. */
  12154. var SyncPoint = /** @class */ (function () {
  12155. function SyncPoint() {
  12156. /**
  12157. * The Views being tracked at this location in the tree, stored as a map where the key is a
  12158. * queryId and the value is the View for that query.
  12159. *
  12160. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  12161. */
  12162. this.views = new Map();
  12163. }
  12164. return SyncPoint;
  12165. }());
  12166. function syncPointSetReferenceConstructor(val) {
  12167. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  12168. referenceConstructor$1 = val;
  12169. }
  12170. function syncPointGetReferenceConstructor() {
  12171. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  12172. return referenceConstructor$1;
  12173. }
  12174. function syncPointIsEmpty(syncPoint) {
  12175. return syncPoint.views.size === 0;
  12176. }
  12177. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  12178. var e_1, _a;
  12179. var queryId = operation.source.queryId;
  12180. if (queryId !== null) {
  12181. var view = syncPoint.views.get(queryId);
  12182. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  12183. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  12184. }
  12185. else {
  12186. var events = [];
  12187. try {
  12188. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  12189. var view = _c.value;
  12190. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  12191. }
  12192. }
  12193. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12194. finally {
  12195. try {
  12196. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12197. }
  12198. finally { if (e_1) throw e_1.error; }
  12199. }
  12200. return events;
  12201. }
  12202. }
  12203. /**
  12204. * Get a view for the specified query.
  12205. *
  12206. * @param query - The query to return a view for
  12207. * @param writesCache
  12208. * @param serverCache
  12209. * @param serverCacheComplete
  12210. * @returns Events to raise.
  12211. */
  12212. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  12213. var queryId = query._queryIdentifier;
  12214. var view = syncPoint.views.get(queryId);
  12215. if (!view) {
  12216. // TODO: make writesCache take flag for complete server node
  12217. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  12218. var eventCacheComplete = false;
  12219. if (eventCache) {
  12220. eventCacheComplete = true;
  12221. }
  12222. else if (serverCache instanceof ChildrenNode) {
  12223. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  12224. eventCacheComplete = false;
  12225. }
  12226. else {
  12227. eventCache = ChildrenNode.EMPTY_NODE;
  12228. eventCacheComplete = false;
  12229. }
  12230. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  12231. return new View(query, viewCache);
  12232. }
  12233. return view;
  12234. }
  12235. /**
  12236. * Add an event callback for the specified query.
  12237. *
  12238. * @param query
  12239. * @param eventRegistration
  12240. * @param writesCache
  12241. * @param serverCache - Complete server cache, if we have it.
  12242. * @param serverCacheComplete
  12243. * @returns Events to raise.
  12244. */
  12245. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  12246. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  12247. if (!syncPoint.views.has(query._queryIdentifier)) {
  12248. syncPoint.views.set(query._queryIdentifier, view);
  12249. }
  12250. // This is guaranteed to exist now, we just created anything that was missing
  12251. viewAddEventRegistration(view, eventRegistration);
  12252. return viewGetInitialEvents(view, eventRegistration);
  12253. }
  12254. /**
  12255. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  12256. *
  12257. * If query is the default query, we'll check all views for the specified eventRegistration.
  12258. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  12259. *
  12260. * @param eventRegistration - If null, remove all callbacks.
  12261. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  12262. * @returns removed queries and any cancel events
  12263. */
  12264. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  12265. var e_2, _a;
  12266. var queryId = query._queryIdentifier;
  12267. var removed = [];
  12268. var cancelEvents = [];
  12269. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  12270. if (queryId === 'default') {
  12271. try {
  12272. // When you do ref.off(...), we search all views for the registration to remove.
  12273. for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  12274. var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  12275. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  12276. if (viewIsEmpty(view)) {
  12277. syncPoint.views.delete(viewQueryId);
  12278. // We'll deal with complete views later.
  12279. if (!view.query._queryParams.loadsAllData()) {
  12280. removed.push(view.query);
  12281. }
  12282. }
  12283. }
  12284. }
  12285. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  12286. finally {
  12287. try {
  12288. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12289. }
  12290. finally { if (e_2) throw e_2.error; }
  12291. }
  12292. }
  12293. else {
  12294. // remove the callback from the specific view.
  12295. var view = syncPoint.views.get(queryId);
  12296. if (view) {
  12297. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  12298. if (viewIsEmpty(view)) {
  12299. syncPoint.views.delete(queryId);
  12300. // We'll deal with complete views later.
  12301. if (!view.query._queryParams.loadsAllData()) {
  12302. removed.push(view.query);
  12303. }
  12304. }
  12305. }
  12306. }
  12307. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  12308. // We removed our last complete view.
  12309. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  12310. }
  12311. return { removed: removed, events: cancelEvents };
  12312. }
  12313. function syncPointGetQueryViews(syncPoint) {
  12314. var e_3, _a;
  12315. var result = [];
  12316. try {
  12317. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  12318. var view = _c.value;
  12319. if (!view.query._queryParams.loadsAllData()) {
  12320. result.push(view);
  12321. }
  12322. }
  12323. }
  12324. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  12325. finally {
  12326. try {
  12327. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12328. }
  12329. finally { if (e_3) throw e_3.error; }
  12330. }
  12331. return result;
  12332. }
  12333. /**
  12334. * @param path - The path to the desired complete snapshot
  12335. * @returns A complete cache, if it exists
  12336. */
  12337. function syncPointGetCompleteServerCache(syncPoint, path) {
  12338. var e_4, _a;
  12339. var serverCache = null;
  12340. try {
  12341. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  12342. var view = _c.value;
  12343. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  12344. }
  12345. }
  12346. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  12347. finally {
  12348. try {
  12349. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12350. }
  12351. finally { if (e_4) throw e_4.error; }
  12352. }
  12353. return serverCache;
  12354. }
  12355. function syncPointViewForQuery(syncPoint, query) {
  12356. var params = query._queryParams;
  12357. if (params.loadsAllData()) {
  12358. return syncPointGetCompleteView(syncPoint);
  12359. }
  12360. else {
  12361. var queryId = query._queryIdentifier;
  12362. return syncPoint.views.get(queryId);
  12363. }
  12364. }
  12365. function syncPointViewExistsForQuery(syncPoint, query) {
  12366. return syncPointViewForQuery(syncPoint, query) != null;
  12367. }
  12368. function syncPointHasCompleteView(syncPoint) {
  12369. return syncPointGetCompleteView(syncPoint) != null;
  12370. }
  12371. function syncPointGetCompleteView(syncPoint) {
  12372. var e_5, _a;
  12373. try {
  12374. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  12375. var view = _c.value;
  12376. if (view.query._queryParams.loadsAllData()) {
  12377. return view;
  12378. }
  12379. }
  12380. }
  12381. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  12382. finally {
  12383. try {
  12384. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12385. }
  12386. finally { if (e_5) throw e_5.error; }
  12387. }
  12388. return null;
  12389. }
  12390. /**
  12391. * @license
  12392. * Copyright 2017 Google LLC
  12393. *
  12394. * Licensed under the Apache License, Version 2.0 (the "License");
  12395. * you may not use this file except in compliance with the License.
  12396. * You may obtain a copy of the License at
  12397. *
  12398. * http://www.apache.org/licenses/LICENSE-2.0
  12399. *
  12400. * Unless required by applicable law or agreed to in writing, software
  12401. * distributed under the License is distributed on an "AS IS" BASIS,
  12402. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12403. * See the License for the specific language governing permissions and
  12404. * limitations under the License.
  12405. */
  12406. var referenceConstructor;
  12407. function syncTreeSetReferenceConstructor(val) {
  12408. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  12409. referenceConstructor = val;
  12410. }
  12411. function syncTreeGetReferenceConstructor() {
  12412. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  12413. return referenceConstructor;
  12414. }
  12415. /**
  12416. * Static tracker for next query tag.
  12417. */
  12418. var syncTreeNextQueryTag_ = 1;
  12419. /**
  12420. * SyncTree is the central class for managing event callback registration, data caching, views
  12421. * (query processing), and event generation. There are typically two SyncTree instances for
  12422. * each Repo, one for the normal Firebase data, and one for the .info data.
  12423. *
  12424. * It has a number of responsibilities, including:
  12425. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  12426. * - Applying and caching data changes for user set(), transaction(), and update() calls
  12427. * (applyUserOverwrite(), applyUserMerge()).
  12428. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  12429. * applyServerMerge()).
  12430. * - Generating user-facing events for server and user changes (all of the apply* methods
  12431. * return the set of events that need to be raised as a result).
  12432. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  12433. * to the correct set of paths and queries to satisfy the current set of user event
  12434. * callbacks (listens are started/stopped using the provided listenProvider).
  12435. *
  12436. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  12437. * events are returned to the caller rather than raised synchronously.
  12438. *
  12439. */
  12440. var SyncTree = /** @class */ (function () {
  12441. /**
  12442. * @param listenProvider_ - Used by SyncTree to start / stop listening
  12443. * to server data.
  12444. */
  12445. function SyncTree(listenProvider_) {
  12446. this.listenProvider_ = listenProvider_;
  12447. /**
  12448. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  12449. */
  12450. this.syncPointTree_ = new ImmutableTree(null);
  12451. /**
  12452. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  12453. */
  12454. this.pendingWriteTree_ = newWriteTree();
  12455. this.tagToQueryMap = new Map();
  12456. this.queryToTagMap = new Map();
  12457. }
  12458. return SyncTree;
  12459. }());
  12460. /**
  12461. * Apply the data changes for a user-generated set() or transaction() call.
  12462. *
  12463. * @returns Events to raise.
  12464. */
  12465. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  12466. // Record pending write.
  12467. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  12468. if (!visible) {
  12469. return [];
  12470. }
  12471. else {
  12472. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  12473. }
  12474. }
  12475. /**
  12476. * Apply the data from a user-generated update() call
  12477. *
  12478. * @returns Events to raise.
  12479. */
  12480. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  12481. // Record pending merge.
  12482. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  12483. var changeTree = ImmutableTree.fromObject(changedChildren);
  12484. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  12485. }
  12486. /**
  12487. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  12488. *
  12489. * @param revert - True if the given write failed and needs to be reverted
  12490. * @returns Events to raise.
  12491. */
  12492. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  12493. if (revert === void 0) { revert = false; }
  12494. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  12495. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  12496. if (!needToReevaluate) {
  12497. return [];
  12498. }
  12499. else {
  12500. var affectedTree_1 = new ImmutableTree(null);
  12501. if (write.snap != null) {
  12502. // overwrite
  12503. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  12504. }
  12505. else {
  12506. each(write.children, function (pathString) {
  12507. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  12508. });
  12509. }
  12510. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  12511. }
  12512. }
  12513. /**
  12514. * Apply new server data for the specified path..
  12515. *
  12516. * @returns Events to raise.
  12517. */
  12518. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  12519. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  12520. }
  12521. /**
  12522. * Apply new server data to be merged in at the specified path.
  12523. *
  12524. * @returns Events to raise.
  12525. */
  12526. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  12527. var changeTree = ImmutableTree.fromObject(changedChildren);
  12528. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  12529. }
  12530. /**
  12531. * Apply a listen complete for a query
  12532. *
  12533. * @returns Events to raise.
  12534. */
  12535. function syncTreeApplyListenComplete(syncTree, path) {
  12536. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  12537. }
  12538. /**
  12539. * Apply a listen complete for a tagged query
  12540. *
  12541. * @returns Events to raise.
  12542. */
  12543. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  12544. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12545. if (queryKey) {
  12546. var r = syncTreeParseQueryKey_(queryKey);
  12547. var queryPath = r.path, queryId = r.queryId;
  12548. var relativePath = newRelativePath(queryPath, path);
  12549. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  12550. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12551. }
  12552. else {
  12553. // We've already removed the query. No big deal, ignore the update
  12554. return [];
  12555. }
  12556. }
  12557. /**
  12558. * Remove event callback(s).
  12559. *
  12560. * If query is the default query, we'll check all queries for the specified eventRegistration.
  12561. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  12562. *
  12563. * @param eventRegistration - If null, all callbacks are removed.
  12564. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  12565. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  12566. * deduping needs to take place. This flag allows toggling of that behavior
  12567. * @returns Cancel events, if cancelError was provided.
  12568. */
  12569. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  12570. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  12571. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  12572. var path = query._path;
  12573. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  12574. var cancelEvents = [];
  12575. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  12576. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  12577. // not loadsAllData().
  12578. if (maybeSyncPoint &&
  12579. (query._queryIdentifier === 'default' ||
  12580. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  12581. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  12582. if (syncPointIsEmpty(maybeSyncPoint)) {
  12583. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  12584. }
  12585. var removed = removedAndEvents.removed;
  12586. cancelEvents = removedAndEvents.events;
  12587. if (!skipListenerDedup) {
  12588. /**
  12589. * We may have just removed one of many listeners and can short-circuit this whole process
  12590. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  12591. * properly set up.
  12592. */
  12593. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  12594. // queryId === 'default'
  12595. var removingDefault = -1 !==
  12596. removed.findIndex(function (query) {
  12597. return query._queryParams.loadsAllData();
  12598. });
  12599. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  12600. return syncPointHasCompleteView(parentSyncPoint);
  12601. });
  12602. if (removingDefault && !covered) {
  12603. var subtree = syncTree.syncPointTree_.subtree(path);
  12604. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  12605. // removal
  12606. if (!subtree.isEmpty()) {
  12607. // We need to fold over our subtree and collect the listeners to send
  12608. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  12609. // Ok, we've collected all the listens we need. Set them up.
  12610. for (var i = 0; i < newViews.length; ++i) {
  12611. var view = newViews[i], newQuery = view.query;
  12612. var listener = syncTreeCreateListenerForView_(syncTree, view);
  12613. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  12614. }
  12615. }
  12616. // Otherwise there's nothing below us, so nothing we need to start listening on
  12617. }
  12618. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  12619. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  12620. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  12621. if (!covered && removed.length > 0 && !cancelError) {
  12622. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  12623. // default. Otherwise, we need to iterate through and cancel each individual query
  12624. if (removingDefault) {
  12625. // We don't tag default listeners
  12626. var defaultTag = null;
  12627. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  12628. }
  12629. else {
  12630. removed.forEach(function (queryToRemove) {
  12631. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  12632. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  12633. });
  12634. }
  12635. }
  12636. }
  12637. // Now, clear all of the tags we're tracking for the removed listens
  12638. syncTreeRemoveTags_(syncTree, removed);
  12639. }
  12640. return cancelEvents;
  12641. }
  12642. /**
  12643. * Apply new server data for the specified tagged query.
  12644. *
  12645. * @returns Events to raise.
  12646. */
  12647. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  12648. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12649. if (queryKey != null) {
  12650. var r = syncTreeParseQueryKey_(queryKey);
  12651. var queryPath = r.path, queryId = r.queryId;
  12652. var relativePath = newRelativePath(queryPath, path);
  12653. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  12654. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12655. }
  12656. else {
  12657. // Query must have been removed already
  12658. return [];
  12659. }
  12660. }
  12661. /**
  12662. * Apply server data to be merged in for the specified tagged query.
  12663. *
  12664. * @returns Events to raise.
  12665. */
  12666. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  12667. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  12668. if (queryKey) {
  12669. var r = syncTreeParseQueryKey_(queryKey);
  12670. var queryPath = r.path, queryId = r.queryId;
  12671. var relativePath = newRelativePath(queryPath, path);
  12672. var changeTree = ImmutableTree.fromObject(changedChildren);
  12673. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  12674. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  12675. }
  12676. else {
  12677. // We've already removed the query. No big deal, ignore the update
  12678. return [];
  12679. }
  12680. }
  12681. /**
  12682. * Add an event callback for the specified query.
  12683. *
  12684. * @returns Events to raise.
  12685. */
  12686. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  12687. if (skipSetupListener === void 0) { skipSetupListener = false; }
  12688. var path = query._path;
  12689. var serverCache = null;
  12690. var foundAncestorDefaultView = false;
  12691. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  12692. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  12693. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  12694. var relativePath = newRelativePath(pathToSyncPoint, path);
  12695. serverCache =
  12696. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  12697. foundAncestorDefaultView =
  12698. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  12699. });
  12700. var syncPoint = syncTree.syncPointTree_.get(path);
  12701. if (!syncPoint) {
  12702. syncPoint = new SyncPoint();
  12703. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  12704. }
  12705. else {
  12706. foundAncestorDefaultView =
  12707. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  12708. serverCache =
  12709. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12710. }
  12711. var serverCacheComplete;
  12712. if (serverCache != null) {
  12713. serverCacheComplete = true;
  12714. }
  12715. else {
  12716. serverCacheComplete = false;
  12717. serverCache = ChildrenNode.EMPTY_NODE;
  12718. var subtree = syncTree.syncPointTree_.subtree(path);
  12719. subtree.foreachChild(function (childName, childSyncPoint) {
  12720. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  12721. if (completeCache) {
  12722. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  12723. }
  12724. });
  12725. }
  12726. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  12727. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  12728. // We need to track a tag for this query
  12729. var queryKey = syncTreeMakeQueryKey_(query);
  12730. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  12731. var tag = syncTreeGetNextQueryTag_();
  12732. syncTree.queryToTagMap.set(queryKey, tag);
  12733. syncTree.tagToQueryMap.set(tag, queryKey);
  12734. }
  12735. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  12736. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  12737. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  12738. var view = syncPointViewForQuery(syncPoint, query);
  12739. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  12740. }
  12741. return events;
  12742. }
  12743. /**
  12744. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  12745. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  12746. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  12747. * <incremented total> as the write is applied locally and then acknowledged at the server.
  12748. *
  12749. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  12750. *
  12751. * @param path - The path to the data we want
  12752. * @param writeIdsToExclude - A specific set to be excluded
  12753. */
  12754. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  12755. var includeHiddenSets = true;
  12756. var writeTree = syncTree.pendingWriteTree_;
  12757. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  12758. var relativePath = newRelativePath(pathSoFar, path);
  12759. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  12760. if (serverCache) {
  12761. return serverCache;
  12762. }
  12763. });
  12764. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  12765. }
  12766. function syncTreeGetServerValue(syncTree, query) {
  12767. var path = query._path;
  12768. var serverCache = null;
  12769. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  12770. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  12771. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  12772. var relativePath = newRelativePath(pathToSyncPoint, path);
  12773. serverCache =
  12774. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  12775. });
  12776. var syncPoint = syncTree.syncPointTree_.get(path);
  12777. if (!syncPoint) {
  12778. syncPoint = new SyncPoint();
  12779. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  12780. }
  12781. else {
  12782. serverCache =
  12783. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12784. }
  12785. var serverCacheComplete = serverCache != null;
  12786. var serverCacheNode = serverCacheComplete
  12787. ? new CacheNode(serverCache, true, false)
  12788. : null;
  12789. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  12790. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  12791. return viewGetCompleteNode(view);
  12792. }
  12793. /**
  12794. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  12795. *
  12796. * NOTES:
  12797. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  12798. *
  12799. * - We call applyOperation() on each SyncPoint passing three things:
  12800. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  12801. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  12802. * 3. A snapshot Node with cached server data, if we have it.
  12803. *
  12804. * - We concatenate all of the events returned by each SyncPoint and return the result.
  12805. */
  12806. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  12807. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  12808. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  12809. }
  12810. /**
  12811. * Recursive helper for applyOperationToSyncPoints_
  12812. */
  12813. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  12814. if (pathIsEmpty(operation.path)) {
  12815. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  12816. }
  12817. else {
  12818. var syncPoint = syncPointTree.get(newEmptyPath());
  12819. // If we don't have cached server data, see if we can get it from this SyncPoint.
  12820. if (serverCache == null && syncPoint != null) {
  12821. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12822. }
  12823. var events = [];
  12824. var childName = pathGetFront(operation.path);
  12825. var childOperation = operation.operationForChild(childName);
  12826. var childTree = syncPointTree.children.get(childName);
  12827. if (childTree && childOperation) {
  12828. var childServerCache = serverCache
  12829. ? serverCache.getImmediateChild(childName)
  12830. : null;
  12831. var childWritesCache = writeTreeRefChild(writesCache, childName);
  12832. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  12833. }
  12834. if (syncPoint) {
  12835. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  12836. }
  12837. return events;
  12838. }
  12839. }
  12840. /**
  12841. * Recursive helper for applyOperationToSyncPoints_
  12842. */
  12843. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  12844. var syncPoint = syncPointTree.get(newEmptyPath());
  12845. // If we don't have cached server data, see if we can get it from this SyncPoint.
  12846. if (serverCache == null && syncPoint != null) {
  12847. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  12848. }
  12849. var events = [];
  12850. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  12851. var childServerCache = serverCache
  12852. ? serverCache.getImmediateChild(childName)
  12853. : null;
  12854. var childWritesCache = writeTreeRefChild(writesCache, childName);
  12855. var childOperation = operation.operationForChild(childName);
  12856. if (childOperation) {
  12857. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  12858. }
  12859. });
  12860. if (syncPoint) {
  12861. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  12862. }
  12863. return events;
  12864. }
  12865. function syncTreeCreateListenerForView_(syncTree, view) {
  12866. var query = view.query;
  12867. var tag = syncTreeTagForQuery(syncTree, query);
  12868. return {
  12869. hashFn: function () {
  12870. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  12871. return cache.hash();
  12872. },
  12873. onComplete: function (status) {
  12874. if (status === 'ok') {
  12875. if (tag) {
  12876. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  12877. }
  12878. else {
  12879. return syncTreeApplyListenComplete(syncTree, query._path);
  12880. }
  12881. }
  12882. else {
  12883. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  12884. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  12885. var error = errorForServerCode(status, query);
  12886. return syncTreeRemoveEventRegistration(syncTree, query,
  12887. /*eventRegistration*/ null, error);
  12888. }
  12889. }
  12890. };
  12891. }
  12892. /**
  12893. * Return the tag associated with the given query.
  12894. */
  12895. function syncTreeTagForQuery(syncTree, query) {
  12896. var queryKey = syncTreeMakeQueryKey_(query);
  12897. return syncTree.queryToTagMap.get(queryKey);
  12898. }
  12899. /**
  12900. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  12901. */
  12902. function syncTreeMakeQueryKey_(query) {
  12903. return query._path.toString() + '$' + query._queryIdentifier;
  12904. }
  12905. /**
  12906. * Return the query associated with the given tag, if we have one
  12907. */
  12908. function syncTreeQueryKeyForTag_(syncTree, tag) {
  12909. return syncTree.tagToQueryMap.get(tag);
  12910. }
  12911. /**
  12912. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  12913. */
  12914. function syncTreeParseQueryKey_(queryKey) {
  12915. var splitIndex = queryKey.indexOf('$');
  12916. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  12917. return {
  12918. queryId: queryKey.substr(splitIndex + 1),
  12919. path: new Path(queryKey.substr(0, splitIndex))
  12920. };
  12921. }
  12922. /**
  12923. * A helper method to apply tagged operations
  12924. */
  12925. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  12926. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  12927. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  12928. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  12929. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  12930. }
  12931. /**
  12932. * This collapses multiple unfiltered views into a single view, since we only need a single
  12933. * listener for them.
  12934. */
  12935. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  12936. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  12937. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  12938. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  12939. return [completeView];
  12940. }
  12941. else {
  12942. // No complete view here, flatten any deeper listens into an array
  12943. var views_1 = [];
  12944. if (maybeChildSyncPoint) {
  12945. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  12946. }
  12947. each(childMap, function (_key, childViews) {
  12948. views_1 = views_1.concat(childViews);
  12949. });
  12950. return views_1;
  12951. }
  12952. });
  12953. }
  12954. /**
  12955. * Normalizes a query to a query we send the server for listening
  12956. *
  12957. * @returns The normalized query
  12958. */
  12959. function syncTreeQueryForListening_(query) {
  12960. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  12961. // We treat queries that load all data as default queries
  12962. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  12963. // from Query
  12964. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  12965. }
  12966. else {
  12967. return query;
  12968. }
  12969. }
  12970. function syncTreeRemoveTags_(syncTree, queries) {
  12971. for (var j = 0; j < queries.length; ++j) {
  12972. var removedQuery = queries[j];
  12973. if (!removedQuery._queryParams.loadsAllData()) {
  12974. // We should have a tag for this
  12975. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  12976. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  12977. syncTree.queryToTagMap.delete(removedQueryKey);
  12978. syncTree.tagToQueryMap.delete(removedQueryTag);
  12979. }
  12980. }
  12981. }
  12982. /**
  12983. * Static accessor for query tags.
  12984. */
  12985. function syncTreeGetNextQueryTag_() {
  12986. return syncTreeNextQueryTag_++;
  12987. }
  12988. /**
  12989. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  12990. *
  12991. * @returns This method can return events to support synchronous data sources
  12992. */
  12993. function syncTreeSetupListener_(syncTree, query, view) {
  12994. var path = query._path;
  12995. var tag = syncTreeTagForQuery(syncTree, query);
  12996. var listener = syncTreeCreateListenerForView_(syncTree, view);
  12997. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  12998. var subtree = syncTree.syncPointTree_.subtree(path);
  12999. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  13000. // may need to shadow other listens as well.
  13001. if (tag) {
  13002. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  13003. }
  13004. else {
  13005. // Shadow everything at or below this location, this is a default listener.
  13006. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  13007. if (!pathIsEmpty(relativePath) &&
  13008. maybeChildSyncPoint &&
  13009. syncPointHasCompleteView(maybeChildSyncPoint)) {
  13010. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  13011. }
  13012. else {
  13013. // No default listener here, flatten any deeper queries into an array
  13014. var queries_1 = [];
  13015. if (maybeChildSyncPoint) {
  13016. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  13017. }
  13018. each(childMap, function (_key, childQueries) {
  13019. queries_1 = queries_1.concat(childQueries);
  13020. });
  13021. return queries_1;
  13022. }
  13023. });
  13024. for (var i = 0; i < queriesToStop.length; ++i) {
  13025. var queryToStop = queriesToStop[i];
  13026. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  13027. }
  13028. }
  13029. return events;
  13030. }
  13031. /**
  13032. * @license
  13033. * Copyright 2017 Google LLC
  13034. *
  13035. * Licensed under the Apache License, Version 2.0 (the "License");
  13036. * you may not use this file except in compliance with the License.
  13037. * You may obtain a copy of the License at
  13038. *
  13039. * http://www.apache.org/licenses/LICENSE-2.0
  13040. *
  13041. * Unless required by applicable law or agreed to in writing, software
  13042. * distributed under the License is distributed on an "AS IS" BASIS,
  13043. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13044. * See the License for the specific language governing permissions and
  13045. * limitations under the License.
  13046. */
  13047. var ExistingValueProvider = /** @class */ (function () {
  13048. function ExistingValueProvider(node_) {
  13049. this.node_ = node_;
  13050. }
  13051. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  13052. var child = this.node_.getImmediateChild(childName);
  13053. return new ExistingValueProvider(child);
  13054. };
  13055. ExistingValueProvider.prototype.node = function () {
  13056. return this.node_;
  13057. };
  13058. return ExistingValueProvider;
  13059. }());
  13060. var DeferredValueProvider = /** @class */ (function () {
  13061. function DeferredValueProvider(syncTree, path) {
  13062. this.syncTree_ = syncTree;
  13063. this.path_ = path;
  13064. }
  13065. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  13066. var childPath = pathChild(this.path_, childName);
  13067. return new DeferredValueProvider(this.syncTree_, childPath);
  13068. };
  13069. DeferredValueProvider.prototype.node = function () {
  13070. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  13071. };
  13072. return DeferredValueProvider;
  13073. }());
  13074. /**
  13075. * Generate placeholders for deferred values.
  13076. */
  13077. var generateWithValues = function (values) {
  13078. values = values || {};
  13079. values['timestamp'] = values['timestamp'] || new Date().getTime();
  13080. return values;
  13081. };
  13082. /**
  13083. * Value to use when firing local events. When writing server values, fire
  13084. * local events with an approximate value, otherwise return value as-is.
  13085. */
  13086. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  13087. if (!value || typeof value !== 'object') {
  13088. return value;
  13089. }
  13090. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  13091. if (typeof value['.sv'] === 'string') {
  13092. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  13093. }
  13094. else if (typeof value['.sv'] === 'object') {
  13095. return resolveComplexDeferredValue(value['.sv'], existingVal);
  13096. }
  13097. else {
  13098. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  13099. }
  13100. };
  13101. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  13102. switch (op) {
  13103. case 'timestamp':
  13104. return serverValues['timestamp'];
  13105. default:
  13106. util.assert(false, 'Unexpected server value: ' + op);
  13107. }
  13108. };
  13109. var resolveComplexDeferredValue = function (op, existing, unused) {
  13110. if (!op.hasOwnProperty('increment')) {
  13111. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  13112. }
  13113. var delta = op['increment'];
  13114. if (typeof delta !== 'number') {
  13115. util.assert(false, 'Unexpected increment value: ' + delta);
  13116. }
  13117. var existingNode = existing.node();
  13118. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  13119. // Incrementing a non-number sets the value to the incremented amount
  13120. if (!existingNode.isLeafNode()) {
  13121. return delta;
  13122. }
  13123. var leaf = existingNode;
  13124. var existingVal = leaf.getValue();
  13125. if (typeof existingVal !== 'number') {
  13126. return delta;
  13127. }
  13128. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  13129. return existingVal + delta;
  13130. };
  13131. /**
  13132. * Recursively replace all deferred values and priorities in the tree with the
  13133. * specified generated replacement values.
  13134. * @param path - path to which write is relative
  13135. * @param node - new data written at path
  13136. * @param syncTree - current data
  13137. */
  13138. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  13139. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  13140. };
  13141. /**
  13142. * Recursively replace all deferred values and priorities in the node with the
  13143. * specified generated replacement values. If there are no server values in the node,
  13144. * it'll be returned as-is.
  13145. */
  13146. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  13147. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  13148. };
  13149. function resolveDeferredValue(node, existingVal, serverValues) {
  13150. var rawPri = node.getPriority().val();
  13151. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  13152. var newNode;
  13153. if (node.isLeafNode()) {
  13154. var leafNode = node;
  13155. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  13156. if (value !== leafNode.getValue() ||
  13157. priority !== leafNode.getPriority().val()) {
  13158. return new LeafNode(value, nodeFromJSON(priority));
  13159. }
  13160. else {
  13161. return node;
  13162. }
  13163. }
  13164. else {
  13165. var childrenNode = node;
  13166. newNode = childrenNode;
  13167. if (priority !== childrenNode.getPriority().val()) {
  13168. newNode = newNode.updatePriority(new LeafNode(priority));
  13169. }
  13170. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  13171. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  13172. if (newChildNode !== childNode) {
  13173. newNode = newNode.updateImmediateChild(childName, newChildNode);
  13174. }
  13175. });
  13176. return newNode;
  13177. }
  13178. }
  13179. /**
  13180. * @license
  13181. * Copyright 2017 Google LLC
  13182. *
  13183. * Licensed under the Apache License, Version 2.0 (the "License");
  13184. * you may not use this file except in compliance with the License.
  13185. * You may obtain a copy of the License at
  13186. *
  13187. * http://www.apache.org/licenses/LICENSE-2.0
  13188. *
  13189. * Unless required by applicable law or agreed to in writing, software
  13190. * distributed under the License is distributed on an "AS IS" BASIS,
  13191. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13192. * See the License for the specific language governing permissions and
  13193. * limitations under the License.
  13194. */
  13195. /**
  13196. * A light-weight tree, traversable by path. Nodes can have both values and children.
  13197. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  13198. * children.
  13199. */
  13200. var Tree = /** @class */ (function () {
  13201. /**
  13202. * @param name - Optional name of the node.
  13203. * @param parent - Optional parent node.
  13204. * @param node - Optional node to wrap.
  13205. */
  13206. function Tree(name, parent, node) {
  13207. if (name === void 0) { name = ''; }
  13208. if (parent === void 0) { parent = null; }
  13209. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  13210. this.name = name;
  13211. this.parent = parent;
  13212. this.node = node;
  13213. }
  13214. return Tree;
  13215. }());
  13216. /**
  13217. * Returns a sub-Tree for the given path.
  13218. *
  13219. * @param pathObj - Path to look up.
  13220. * @returns Tree for path.
  13221. */
  13222. function treeSubTree(tree, pathObj) {
  13223. // TODO: Require pathObj to be Path?
  13224. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  13225. var child = tree, next = pathGetFront(path);
  13226. while (next !== null) {
  13227. var childNode = util.safeGet(child.node.children, next) || {
  13228. children: {},
  13229. childCount: 0
  13230. };
  13231. child = new Tree(next, child, childNode);
  13232. path = pathPopFront(path);
  13233. next = pathGetFront(path);
  13234. }
  13235. return child;
  13236. }
  13237. /**
  13238. * Returns the data associated with this tree node.
  13239. *
  13240. * @returns The data or null if no data exists.
  13241. */
  13242. function treeGetValue(tree) {
  13243. return tree.node.value;
  13244. }
  13245. /**
  13246. * Sets data to this tree node.
  13247. *
  13248. * @param value - Value to set.
  13249. */
  13250. function treeSetValue(tree, value) {
  13251. tree.node.value = value;
  13252. treeUpdateParents(tree);
  13253. }
  13254. /**
  13255. * @returns Whether the tree has any children.
  13256. */
  13257. function treeHasChildren(tree) {
  13258. return tree.node.childCount > 0;
  13259. }
  13260. /**
  13261. * @returns Whethe rthe tree is empty (no value or children).
  13262. */
  13263. function treeIsEmpty(tree) {
  13264. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  13265. }
  13266. /**
  13267. * Calls action for each child of this tree node.
  13268. *
  13269. * @param action - Action to be called for each child.
  13270. */
  13271. function treeForEachChild(tree, action) {
  13272. each(tree.node.children, function (child, childTree) {
  13273. action(new Tree(child, tree, childTree));
  13274. });
  13275. }
  13276. /**
  13277. * Does a depth-first traversal of this node's descendants, calling action for each one.
  13278. *
  13279. * @param action - Action to be called for each child.
  13280. * @param includeSelf - Whether to call action on this node as well. Defaults to
  13281. * false.
  13282. * @param childrenFirst - Whether to call action on children before calling it on
  13283. * parent.
  13284. */
  13285. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  13286. if (includeSelf && !childrenFirst) {
  13287. action(tree);
  13288. }
  13289. treeForEachChild(tree, function (child) {
  13290. treeForEachDescendant(child, action, true, childrenFirst);
  13291. });
  13292. if (includeSelf && childrenFirst) {
  13293. action(tree);
  13294. }
  13295. }
  13296. /**
  13297. * Calls action on each ancestor node.
  13298. *
  13299. * @param action - Action to be called on each parent; return
  13300. * true to abort.
  13301. * @param includeSelf - Whether to call action on this node as well.
  13302. * @returns true if the action callback returned true.
  13303. */
  13304. function treeForEachAncestor(tree, action, includeSelf) {
  13305. var node = includeSelf ? tree : tree.parent;
  13306. while (node !== null) {
  13307. if (action(node)) {
  13308. return true;
  13309. }
  13310. node = node.parent;
  13311. }
  13312. return false;
  13313. }
  13314. /**
  13315. * @returns The path of this tree node, as a Path.
  13316. */
  13317. function treeGetPath(tree) {
  13318. return new Path(tree.parent === null
  13319. ? tree.name
  13320. : treeGetPath(tree.parent) + '/' + tree.name);
  13321. }
  13322. /**
  13323. * Adds or removes this child from its parent based on whether it's empty or not.
  13324. */
  13325. function treeUpdateParents(tree) {
  13326. if (tree.parent !== null) {
  13327. treeUpdateChild(tree.parent, tree.name, tree);
  13328. }
  13329. }
  13330. /**
  13331. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  13332. *
  13333. * @param childName - The name of the child to update.
  13334. * @param child - The child to update.
  13335. */
  13336. function treeUpdateChild(tree, childName, child) {
  13337. var childEmpty = treeIsEmpty(child);
  13338. var childExists = util.contains(tree.node.children, childName);
  13339. if (childEmpty && childExists) {
  13340. delete tree.node.children[childName];
  13341. tree.node.childCount--;
  13342. treeUpdateParents(tree);
  13343. }
  13344. else if (!childEmpty && !childExists) {
  13345. tree.node.children[childName] = child.node;
  13346. tree.node.childCount++;
  13347. treeUpdateParents(tree);
  13348. }
  13349. }
  13350. /**
  13351. * @license
  13352. * Copyright 2017 Google LLC
  13353. *
  13354. * Licensed under the Apache License, Version 2.0 (the "License");
  13355. * you may not use this file except in compliance with the License.
  13356. * You may obtain a copy of the License at
  13357. *
  13358. * http://www.apache.org/licenses/LICENSE-2.0
  13359. *
  13360. * Unless required by applicable law or agreed to in writing, software
  13361. * distributed under the License is distributed on an "AS IS" BASIS,
  13362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13363. * See the License for the specific language governing permissions and
  13364. * limitations under the License.
  13365. */
  13366. /**
  13367. * True for invalid Firebase keys
  13368. */
  13369. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  13370. /**
  13371. * True for invalid Firebase paths.
  13372. * Allows '/' in paths.
  13373. */
  13374. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  13375. /**
  13376. * Maximum number of characters to allow in leaf value
  13377. */
  13378. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  13379. var isValidKey = function (key) {
  13380. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  13381. };
  13382. var isValidPathString = function (pathString) {
  13383. return (typeof pathString === 'string' &&
  13384. pathString.length !== 0 &&
  13385. !INVALID_PATH_REGEX_.test(pathString));
  13386. };
  13387. var isValidRootPathString = function (pathString) {
  13388. if (pathString) {
  13389. // Allow '/.info/' at the beginning.
  13390. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  13391. }
  13392. return isValidPathString(pathString);
  13393. };
  13394. var isValidPriority = function (priority) {
  13395. return (priority === null ||
  13396. typeof priority === 'string' ||
  13397. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  13398. (priority &&
  13399. typeof priority === 'object' &&
  13400. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13401. util.contains(priority, '.sv')));
  13402. };
  13403. /**
  13404. * Pre-validate a datum passed as an argument to Firebase function.
  13405. */
  13406. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  13407. if (optional && value === undefined) {
  13408. return;
  13409. }
  13410. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  13411. };
  13412. /**
  13413. * Validate a data object client-side before sending to server.
  13414. */
  13415. var validateFirebaseData = function (errorPrefix, data, path_) {
  13416. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  13417. if (data === undefined) {
  13418. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  13419. }
  13420. if (typeof data === 'function') {
  13421. throw new Error(errorPrefix +
  13422. 'contains a function ' +
  13423. validationPathToErrorString(path) +
  13424. ' with contents = ' +
  13425. data.toString());
  13426. }
  13427. if (isInvalidJSONNumber(data)) {
  13428. throw new Error(errorPrefix +
  13429. 'contains ' +
  13430. data.toString() +
  13431. ' ' +
  13432. validationPathToErrorString(path));
  13433. }
  13434. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  13435. if (typeof data === 'string' &&
  13436. data.length > MAX_LEAF_SIZE_ / 3 &&
  13437. util.stringLength(data) > MAX_LEAF_SIZE_) {
  13438. throw new Error(errorPrefix +
  13439. 'contains a string greater than ' +
  13440. MAX_LEAF_SIZE_ +
  13441. ' utf8 bytes ' +
  13442. validationPathToErrorString(path) +
  13443. " ('" +
  13444. data.substring(0, 50) +
  13445. "...')");
  13446. }
  13447. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  13448. // to save extra walking of large objects.
  13449. if (data && typeof data === 'object') {
  13450. var hasDotValue_1 = false;
  13451. var hasActualChild_1 = false;
  13452. each(data, function (key, value) {
  13453. if (key === '.value') {
  13454. hasDotValue_1 = true;
  13455. }
  13456. else if (key !== '.priority' && key !== '.sv') {
  13457. hasActualChild_1 = true;
  13458. if (!isValidKey(key)) {
  13459. throw new Error(errorPrefix +
  13460. ' contains an invalid key (' +
  13461. key +
  13462. ') ' +
  13463. validationPathToErrorString(path) +
  13464. '. Keys must be non-empty strings ' +
  13465. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  13466. }
  13467. }
  13468. validationPathPush(path, key);
  13469. validateFirebaseData(errorPrefix, value, path);
  13470. validationPathPop(path);
  13471. });
  13472. if (hasDotValue_1 && hasActualChild_1) {
  13473. throw new Error(errorPrefix +
  13474. ' contains ".value" child ' +
  13475. validationPathToErrorString(path) +
  13476. ' in addition to actual children.');
  13477. }
  13478. }
  13479. };
  13480. /**
  13481. * Pre-validate paths passed in the firebase function.
  13482. */
  13483. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  13484. var i, curPath;
  13485. for (i = 0; i < mergePaths.length; i++) {
  13486. curPath = mergePaths[i];
  13487. var keys = pathSlice(curPath);
  13488. for (var j = 0; j < keys.length; j++) {
  13489. if (keys[j] === '.priority' && j === keys.length - 1) ;
  13490. else if (!isValidKey(keys[j])) {
  13491. throw new Error(errorPrefix +
  13492. 'contains an invalid key (' +
  13493. keys[j] +
  13494. ') in path ' +
  13495. curPath.toString() +
  13496. '. Keys must be non-empty strings ' +
  13497. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  13498. }
  13499. }
  13500. }
  13501. // Check that update keys are not descendants of each other.
  13502. // We rely on the property that sorting guarantees that ancestors come
  13503. // right before descendants.
  13504. mergePaths.sort(pathCompare);
  13505. var prevPath = null;
  13506. for (i = 0; i < mergePaths.length; i++) {
  13507. curPath = mergePaths[i];
  13508. if (prevPath !== null && pathContains(prevPath, curPath)) {
  13509. throw new Error(errorPrefix +
  13510. 'contains a path ' +
  13511. prevPath.toString() +
  13512. ' that is ancestor of another path ' +
  13513. curPath.toString());
  13514. }
  13515. prevPath = curPath;
  13516. }
  13517. };
  13518. /**
  13519. * pre-validate an object passed as an argument to firebase function (
  13520. * must be an object - e.g. for firebase.update()).
  13521. */
  13522. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  13523. if (optional && data === undefined) {
  13524. return;
  13525. }
  13526. var errorPrefix = util.errorPrefix(fnName, 'values');
  13527. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  13528. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  13529. }
  13530. var mergePaths = [];
  13531. each(data, function (key, value) {
  13532. var curPath = new Path(key);
  13533. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  13534. if (pathGetBack(curPath) === '.priority') {
  13535. if (!isValidPriority(value)) {
  13536. throw new Error(errorPrefix +
  13537. "contains an invalid value for '" +
  13538. curPath.toString() +
  13539. "', which must be a valid " +
  13540. 'Firebase priority (a string, finite number, server value, or null).');
  13541. }
  13542. }
  13543. mergePaths.push(curPath);
  13544. });
  13545. validateFirebaseMergePaths(errorPrefix, mergePaths);
  13546. };
  13547. var validatePriority = function (fnName, priority, optional) {
  13548. if (optional && priority === undefined) {
  13549. return;
  13550. }
  13551. if (isInvalidJSONNumber(priority)) {
  13552. throw new Error(util.errorPrefix(fnName, 'priority') +
  13553. 'is ' +
  13554. priority.toString() +
  13555. ', but must be a valid Firebase priority (a string, finite number, ' +
  13556. 'server value, or null).');
  13557. }
  13558. // Special case to allow importing data with a .sv.
  13559. if (!isValidPriority(priority)) {
  13560. throw new Error(util.errorPrefix(fnName, 'priority') +
  13561. 'must be a valid Firebase priority ' +
  13562. '(a string, finite number, server value, or null).');
  13563. }
  13564. };
  13565. var validateKey = function (fnName, argumentName, key, optional) {
  13566. if (optional && key === undefined) {
  13567. return;
  13568. }
  13569. if (!isValidKey(key)) {
  13570. throw new Error(util.errorPrefix(fnName, argumentName) +
  13571. 'was an invalid key = "' +
  13572. key +
  13573. '". Firebase keys must be non-empty strings and ' +
  13574. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  13575. }
  13576. };
  13577. /**
  13578. * @internal
  13579. */
  13580. var validatePathString = function (fnName, argumentName, pathString, optional) {
  13581. if (optional && pathString === undefined) {
  13582. return;
  13583. }
  13584. if (!isValidPathString(pathString)) {
  13585. throw new Error(util.errorPrefix(fnName, argumentName) +
  13586. 'was an invalid path = "' +
  13587. pathString +
  13588. '". Paths must be non-empty strings and ' +
  13589. 'can\'t contain ".", "#", "$", "[", or "]"');
  13590. }
  13591. };
  13592. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  13593. if (pathString) {
  13594. // Allow '/.info/' at the beginning.
  13595. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  13596. }
  13597. validatePathString(fnName, argumentName, pathString, optional);
  13598. };
  13599. /**
  13600. * @internal
  13601. */
  13602. var validateWritablePath = function (fnName, path) {
  13603. if (pathGetFront(path) === '.info') {
  13604. throw new Error(fnName + " failed = Can't modify data under /.info/");
  13605. }
  13606. };
  13607. var validateUrl = function (fnName, parsedUrl) {
  13608. // TODO = Validate server better.
  13609. var pathString = parsedUrl.path.toString();
  13610. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  13611. parsedUrl.repoInfo.host.length === 0 ||
  13612. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  13613. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  13614. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  13615. throw new Error(util.errorPrefix(fnName, 'url') +
  13616. 'must be a valid firebase URL and ' +
  13617. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  13618. }
  13619. };
  13620. /**
  13621. * @license
  13622. * Copyright 2017 Google LLC
  13623. *
  13624. * Licensed under the Apache License, Version 2.0 (the "License");
  13625. * you may not use this file except in compliance with the License.
  13626. * You may obtain a copy of the License at
  13627. *
  13628. * http://www.apache.org/licenses/LICENSE-2.0
  13629. *
  13630. * Unless required by applicable law or agreed to in writing, software
  13631. * distributed under the License is distributed on an "AS IS" BASIS,
  13632. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13633. * See the License for the specific language governing permissions and
  13634. * limitations under the License.
  13635. */
  13636. /**
  13637. * The event queue serves a few purposes:
  13638. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  13639. * events being queued.
  13640. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  13641. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  13642. * left off, ensuring that the events are still raised synchronously and in order.
  13643. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  13644. * events are raised synchronously.
  13645. *
  13646. * NOTE: This can all go away if/when we move to async events.
  13647. *
  13648. */
  13649. var EventQueue = /** @class */ (function () {
  13650. function EventQueue() {
  13651. this.eventLists_ = [];
  13652. /**
  13653. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  13654. */
  13655. this.recursionDepth_ = 0;
  13656. }
  13657. return EventQueue;
  13658. }());
  13659. /**
  13660. * @param eventDataList - The new events to queue.
  13661. */
  13662. function eventQueueQueueEvents(eventQueue, eventDataList) {
  13663. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  13664. var currList = null;
  13665. for (var i = 0; i < eventDataList.length; i++) {
  13666. var data = eventDataList[i];
  13667. var path = data.getPath();
  13668. if (currList !== null && !pathEquals(path, currList.path)) {
  13669. eventQueue.eventLists_.push(currList);
  13670. currList = null;
  13671. }
  13672. if (currList === null) {
  13673. currList = { events: [], path: path };
  13674. }
  13675. currList.events.push(data);
  13676. }
  13677. if (currList) {
  13678. eventQueue.eventLists_.push(currList);
  13679. }
  13680. }
  13681. /**
  13682. * Queues the specified events and synchronously raises all events (including previously queued ones)
  13683. * for the specified path.
  13684. *
  13685. * It is assumed that the new events are all for the specified path.
  13686. *
  13687. * @param path - The path to raise events for.
  13688. * @param eventDataList - The new events to raise.
  13689. */
  13690. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  13691. eventQueueQueueEvents(eventQueue, eventDataList);
  13692. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  13693. return pathEquals(eventPath, path);
  13694. });
  13695. }
  13696. /**
  13697. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  13698. * locations related to the specified change path (i.e. all ancestors and descendants).
  13699. *
  13700. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  13701. *
  13702. * @param changedPath - The path to raise events for.
  13703. * @param eventDataList - The events to raise
  13704. */
  13705. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  13706. eventQueueQueueEvents(eventQueue, eventDataList);
  13707. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  13708. return pathContains(eventPath, changedPath) ||
  13709. pathContains(changedPath, eventPath);
  13710. });
  13711. }
  13712. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  13713. eventQueue.recursionDepth_++;
  13714. var sentAll = true;
  13715. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  13716. var eventList = eventQueue.eventLists_[i];
  13717. if (eventList) {
  13718. var eventPath = eventList.path;
  13719. if (predicate(eventPath)) {
  13720. eventListRaise(eventQueue.eventLists_[i]);
  13721. eventQueue.eventLists_[i] = null;
  13722. }
  13723. else {
  13724. sentAll = false;
  13725. }
  13726. }
  13727. }
  13728. if (sentAll) {
  13729. eventQueue.eventLists_ = [];
  13730. }
  13731. eventQueue.recursionDepth_--;
  13732. }
  13733. /**
  13734. * Iterates through the list and raises each event
  13735. */
  13736. function eventListRaise(eventList) {
  13737. for (var i = 0; i < eventList.events.length; i++) {
  13738. var eventData = eventList.events[i];
  13739. if (eventData !== null) {
  13740. eventList.events[i] = null;
  13741. var eventFn = eventData.getEventRunner();
  13742. if (logger) {
  13743. log('event: ' + eventData.toString());
  13744. }
  13745. exceptionGuard(eventFn);
  13746. }
  13747. }
  13748. }
  13749. /**
  13750. * @license
  13751. * Copyright 2017 Google LLC
  13752. *
  13753. * Licensed under the Apache License, Version 2.0 (the "License");
  13754. * you may not use this file except in compliance with the License.
  13755. * You may obtain a copy of the License at
  13756. *
  13757. * http://www.apache.org/licenses/LICENSE-2.0
  13758. *
  13759. * Unless required by applicable law or agreed to in writing, software
  13760. * distributed under the License is distributed on an "AS IS" BASIS,
  13761. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13762. * See the License for the specific language governing permissions and
  13763. * limitations under the License.
  13764. */
  13765. var INTERRUPT_REASON = 'repo_interrupt';
  13766. /**
  13767. * If a transaction does not succeed after 25 retries, we abort it. Among other
  13768. * things this ensure that if there's ever a bug causing a mismatch between
  13769. * client / server hashes for some data, we won't retry indefinitely.
  13770. */
  13771. var MAX_TRANSACTION_RETRIES = 25;
  13772. /**
  13773. * A connection to a single data repository.
  13774. */
  13775. var Repo = /** @class */ (function () {
  13776. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  13777. this.repoInfo_ = repoInfo_;
  13778. this.forceRestClient_ = forceRestClient_;
  13779. this.authTokenProvider_ = authTokenProvider_;
  13780. this.appCheckProvider_ = appCheckProvider_;
  13781. this.dataUpdateCount = 0;
  13782. this.statsListener_ = null;
  13783. this.eventQueue_ = new EventQueue();
  13784. this.nextWriteId_ = 1;
  13785. this.interceptServerDataCallback_ = null;
  13786. /** A list of data pieces and paths to be set when this client disconnects. */
  13787. this.onDisconnect_ = newSparseSnapshotTree();
  13788. /** Stores queues of outstanding transactions for Firebase locations. */
  13789. this.transactionQueueTree_ = new Tree();
  13790. // TODO: This should be @private but it's used by test_access.js and internal.js
  13791. this.persistentConnection_ = null;
  13792. // This key is intentionally not updated if RepoInfo is later changed or replaced
  13793. this.key = this.repoInfo_.toURLString();
  13794. }
  13795. /**
  13796. * @returns The URL corresponding to the root of this Firebase.
  13797. */
  13798. Repo.prototype.toString = function () {
  13799. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  13800. };
  13801. return Repo;
  13802. }());
  13803. function repoStart(repo, appId, authOverride) {
  13804. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  13805. if (repo.forceRestClient_ || beingCrawled()) {
  13806. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  13807. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  13808. }, repo.authTokenProvider_, repo.appCheckProvider_);
  13809. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  13810. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  13811. }
  13812. else {
  13813. // Validate authOverride
  13814. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  13815. if (typeof authOverride !== 'object') {
  13816. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  13817. }
  13818. try {
  13819. util.stringify(authOverride);
  13820. }
  13821. catch (e) {
  13822. throw new Error('Invalid authOverride provided: ' + e);
  13823. }
  13824. }
  13825. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  13826. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  13827. }, function (connectStatus) {
  13828. repoOnConnectStatus(repo, connectStatus);
  13829. }, function (updates) {
  13830. repoOnServerInfoUpdate(repo, updates);
  13831. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  13832. repo.server_ = repo.persistentConnection_;
  13833. }
  13834. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  13835. repo.server_.refreshAuthToken(token);
  13836. });
  13837. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  13838. repo.server_.refreshAppCheckToken(result.token);
  13839. });
  13840. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  13841. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  13842. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  13843. // Used for .info.
  13844. repo.infoData_ = new SnapshotHolder();
  13845. repo.infoSyncTree_ = new SyncTree({
  13846. startListening: function (query, tag, currentHashFn, onComplete) {
  13847. var infoEvents = [];
  13848. var node = repo.infoData_.getNode(query._path);
  13849. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  13850. // on initial data...
  13851. if (!node.isEmpty()) {
  13852. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  13853. setTimeout(function () {
  13854. onComplete('ok');
  13855. }, 0);
  13856. }
  13857. return infoEvents;
  13858. },
  13859. stopListening: function () { }
  13860. });
  13861. repoUpdateInfo(repo, 'connected', false);
  13862. repo.serverSyncTree_ = new SyncTree({
  13863. startListening: function (query, tag, currentHashFn, onComplete) {
  13864. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  13865. var events = onComplete(status, data);
  13866. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  13867. });
  13868. // No synchronous events for network-backed sync trees
  13869. return [];
  13870. },
  13871. stopListening: function (query, tag) {
  13872. repo.server_.unlisten(query, tag);
  13873. }
  13874. });
  13875. }
  13876. /**
  13877. * @returns The time in milliseconds, taking the server offset into account if we have one.
  13878. */
  13879. function repoServerTime(repo) {
  13880. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  13881. var offset = offsetNode.val() || 0;
  13882. return new Date().getTime() + offset;
  13883. }
  13884. /**
  13885. * Generate ServerValues using some variables from the repo object.
  13886. */
  13887. function repoGenerateServerValues(repo) {
  13888. return generateWithValues({
  13889. timestamp: repoServerTime(repo)
  13890. });
  13891. }
  13892. /**
  13893. * Called by realtime when we get new messages from the server.
  13894. */
  13895. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  13896. // For testing.
  13897. repo.dataUpdateCount++;
  13898. var path = new Path(pathString);
  13899. data = repo.interceptServerDataCallback_
  13900. ? repo.interceptServerDataCallback_(pathString, data)
  13901. : data;
  13902. var events = [];
  13903. if (tag) {
  13904. if (isMerge) {
  13905. var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  13906. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  13907. }
  13908. else {
  13909. var taggedSnap = nodeFromJSON(data);
  13910. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  13911. }
  13912. }
  13913. else if (isMerge) {
  13914. var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  13915. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  13916. }
  13917. else {
  13918. var snap = nodeFromJSON(data);
  13919. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  13920. }
  13921. var affectedPath = path;
  13922. if (events.length > 0) {
  13923. // Since we have a listener outstanding for each transaction, receiving any events
  13924. // is a proxy for some change having occurred.
  13925. affectedPath = repoRerunTransactions(repo, path);
  13926. }
  13927. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  13928. }
  13929. function repoOnConnectStatus(repo, connectStatus) {
  13930. repoUpdateInfo(repo, 'connected', connectStatus);
  13931. if (connectStatus === false) {
  13932. repoRunOnDisconnectEvents(repo);
  13933. }
  13934. }
  13935. function repoOnServerInfoUpdate(repo, updates) {
  13936. each(updates, function (key, value) {
  13937. repoUpdateInfo(repo, key, value);
  13938. });
  13939. }
  13940. function repoUpdateInfo(repo, pathString, value) {
  13941. var path = new Path('/.info/' + pathString);
  13942. var newNode = nodeFromJSON(value);
  13943. repo.infoData_.updateSnapshot(path, newNode);
  13944. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  13945. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  13946. }
  13947. function repoGetNextWriteId(repo) {
  13948. return repo.nextWriteId_++;
  13949. }
  13950. /**
  13951. * The purpose of `getValue` is to return the latest known value
  13952. * satisfying `query`.
  13953. *
  13954. * This method will first check for in-memory cached values
  13955. * belonging to active listeners. If they are found, such values
  13956. * are considered to be the most up-to-date.
  13957. *
  13958. * If the client is not connected, this method will wait until the
  13959. * repo has established a connection and then request the value for `query`.
  13960. * If the client is not able to retrieve the query result for another reason,
  13961. * it reports an error.
  13962. *
  13963. * @param query - The query to surface a value for.
  13964. */
  13965. function repoGetValue(repo, query, eventRegistration) {
  13966. // Only active queries are cached. There is no persisted cache.
  13967. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  13968. if (cached != null) {
  13969. return Promise.resolve(cached);
  13970. }
  13971. return repo.server_.get(query).then(function (payload) {
  13972. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  13973. /**
  13974. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  13975. * Add an event registration,
  13976. * Update data at the path,
  13977. * Raise any events,
  13978. * Cleanup the SyncTree
  13979. */
  13980. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  13981. var events;
  13982. if (query._queryParams.loadsAllData()) {
  13983. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  13984. }
  13985. else {
  13986. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  13987. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  13988. }
  13989. /*
  13990. * We need to raise events in the scenario where `get()` is called at a parent path, and
  13991. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  13992. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  13993. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  13994. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  13995. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  13996. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  13997. * ensure the corresponding child events will get fired.
  13998. */
  13999. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  14000. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  14001. return node;
  14002. }, function (err) {
  14003. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  14004. return Promise.reject(new Error(err));
  14005. });
  14006. }
  14007. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  14008. repoLog(repo, 'set', {
  14009. path: path.toString(),
  14010. value: newVal,
  14011. priority: newPriority
  14012. });
  14013. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  14014. // (b) store unresolved paths on JSON parse
  14015. var serverValues = repoGenerateServerValues(repo);
  14016. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  14017. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  14018. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  14019. var writeId = repoGetNextWriteId(repo);
  14020. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  14021. eventQueueQueueEvents(repo.eventQueue_, events);
  14022. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  14023. var success = status === 'ok';
  14024. if (!success) {
  14025. warn$1('set at ' + path + ' failed: ' + status);
  14026. }
  14027. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  14028. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  14029. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14030. });
  14031. var affectedPath = repoAbortTransactions(repo, path);
  14032. repoRerunTransactions(repo, affectedPath);
  14033. // We queued the events above, so just flush the queue here
  14034. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  14035. }
  14036. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  14037. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  14038. // Start with our existing data and merge each child into it.
  14039. var empty = true;
  14040. var serverValues = repoGenerateServerValues(repo);
  14041. var changedChildren = {};
  14042. each(childrenToMerge, function (changedKey, changedValue) {
  14043. empty = false;
  14044. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  14045. });
  14046. if (!empty) {
  14047. var writeId_1 = repoGetNextWriteId(repo);
  14048. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  14049. eventQueueQueueEvents(repo.eventQueue_, events);
  14050. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  14051. var success = status === 'ok';
  14052. if (!success) {
  14053. warn$1('update at ' + path + ' failed: ' + status);
  14054. }
  14055. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  14056. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  14057. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  14058. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14059. });
  14060. each(childrenToMerge, function (changedPath) {
  14061. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  14062. repoRerunTransactions(repo, affectedPath);
  14063. });
  14064. // We queued the events above, so just flush the queue here
  14065. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  14066. }
  14067. else {
  14068. log("update() called with empty data. Don't do anything.");
  14069. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  14070. }
  14071. }
  14072. /**
  14073. * Applies all of the changes stored up in the onDisconnect_ tree.
  14074. */
  14075. function repoRunOnDisconnectEvents(repo) {
  14076. repoLog(repo, 'onDisconnectEvents');
  14077. var serverValues = repoGenerateServerValues(repo);
  14078. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  14079. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  14080. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  14081. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  14082. });
  14083. var events = [];
  14084. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  14085. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  14086. var affectedPath = repoAbortTransactions(repo, path);
  14087. repoRerunTransactions(repo, affectedPath);
  14088. });
  14089. repo.onDisconnect_ = newSparseSnapshotTree();
  14090. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  14091. }
  14092. function repoOnDisconnectCancel(repo, path, onComplete) {
  14093. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  14094. if (status === 'ok') {
  14095. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  14096. }
  14097. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14098. });
  14099. }
  14100. function repoOnDisconnectSet(repo, path, value, onComplete) {
  14101. var newNode = nodeFromJSON(value);
  14102. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  14103. if (status === 'ok') {
  14104. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  14105. }
  14106. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14107. });
  14108. }
  14109. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  14110. var newNode = nodeFromJSON(value, priority);
  14111. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  14112. if (status === 'ok') {
  14113. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  14114. }
  14115. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14116. });
  14117. }
  14118. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  14119. if (util.isEmpty(childrenToMerge)) {
  14120. log("onDisconnect().update() called with empty data. Don't do anything.");
  14121. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  14122. return;
  14123. }
  14124. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  14125. if (status === 'ok') {
  14126. each(childrenToMerge, function (childName, childNode) {
  14127. var newChildNode = nodeFromJSON(childNode);
  14128. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  14129. });
  14130. }
  14131. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  14132. });
  14133. }
  14134. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  14135. var events;
  14136. if (pathGetFront(query._path) === '.info') {
  14137. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  14138. }
  14139. else {
  14140. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  14141. }
  14142. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  14143. }
  14144. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  14145. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  14146. // a little bit by handling the return values anyways.
  14147. var events;
  14148. if (pathGetFront(query._path) === '.info') {
  14149. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  14150. }
  14151. else {
  14152. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  14153. }
  14154. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  14155. }
  14156. function repoInterrupt(repo) {
  14157. if (repo.persistentConnection_) {
  14158. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  14159. }
  14160. }
  14161. function repoResume(repo) {
  14162. if (repo.persistentConnection_) {
  14163. repo.persistentConnection_.resume(INTERRUPT_REASON);
  14164. }
  14165. }
  14166. function repoLog(repo) {
  14167. var varArgs = [];
  14168. for (var _i = 1; _i < arguments.length; _i++) {
  14169. varArgs[_i - 1] = arguments[_i];
  14170. }
  14171. var prefix = '';
  14172. if (repo.persistentConnection_) {
  14173. prefix = repo.persistentConnection_.id + ':';
  14174. }
  14175. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  14176. }
  14177. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  14178. if (callback) {
  14179. exceptionGuard(function () {
  14180. if (status === 'ok') {
  14181. callback(null);
  14182. }
  14183. else {
  14184. var code = (status || 'error').toUpperCase();
  14185. var message = code;
  14186. if (errorReason) {
  14187. message += ': ' + errorReason;
  14188. }
  14189. var error = new Error(message);
  14190. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14191. error.code = code;
  14192. callback(error);
  14193. }
  14194. });
  14195. }
  14196. }
  14197. /**
  14198. * Creates a new transaction, adds it to the transactions we're tracking, and
  14199. * sends it to the server if possible.
  14200. *
  14201. * @param path - Path at which to do transaction.
  14202. * @param transactionUpdate - Update callback.
  14203. * @param onComplete - Completion callback.
  14204. * @param unwatcher - Function that will be called when the transaction no longer
  14205. * need data updates for `path`.
  14206. * @param applyLocally - Whether or not to make intermediate results visible
  14207. */
  14208. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  14209. repoLog(repo, 'transaction on ' + path);
  14210. // Initialize transaction.
  14211. var transaction = {
  14212. path: path,
  14213. update: transactionUpdate,
  14214. onComplete: onComplete,
  14215. // One of TransactionStatus enums.
  14216. status: null,
  14217. // Used when combining transactions at different locations to figure out
  14218. // which one goes first.
  14219. order: LUIDGenerator(),
  14220. // Whether to raise local events for this transaction.
  14221. applyLocally: applyLocally,
  14222. // Count of how many times we've retried the transaction.
  14223. retryCount: 0,
  14224. // Function to call to clean up our .on() listener.
  14225. unwatcher: unwatcher,
  14226. // Stores why a transaction was aborted.
  14227. abortReason: null,
  14228. currentWriteId: null,
  14229. currentInputSnapshot: null,
  14230. currentOutputSnapshotRaw: null,
  14231. currentOutputSnapshotResolved: null
  14232. };
  14233. // Run transaction initially.
  14234. var currentState = repoGetLatestState(repo, path, undefined);
  14235. transaction.currentInputSnapshot = currentState;
  14236. var newVal = transaction.update(currentState.val());
  14237. if (newVal === undefined) {
  14238. // Abort transaction.
  14239. transaction.unwatcher();
  14240. transaction.currentOutputSnapshotRaw = null;
  14241. transaction.currentOutputSnapshotResolved = null;
  14242. if (transaction.onComplete) {
  14243. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  14244. }
  14245. }
  14246. else {
  14247. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  14248. // Mark as run and add to our queue.
  14249. transaction.status = 0 /* TransactionStatus.RUN */;
  14250. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  14251. var nodeQueue = treeGetValue(queueNode) || [];
  14252. nodeQueue.push(transaction);
  14253. treeSetValue(queueNode, nodeQueue);
  14254. // Update visibleData and raise events
  14255. // Note: We intentionally raise events after updating all of our
  14256. // transaction state, since the user could start new transactions from the
  14257. // event callbacks.
  14258. var priorityForNode = void 0;
  14259. if (typeof newVal === 'object' &&
  14260. newVal !== null &&
  14261. util.contains(newVal, '.priority')) {
  14262. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14263. priorityForNode = util.safeGet(newVal, '.priority');
  14264. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  14265. 'Priority must be a valid string, finite number, server value, or null.');
  14266. }
  14267. else {
  14268. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  14269. ChildrenNode.EMPTY_NODE;
  14270. priorityForNode = currentNode.getPriority().val();
  14271. }
  14272. var serverValues = repoGenerateServerValues(repo);
  14273. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  14274. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  14275. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  14276. transaction.currentOutputSnapshotResolved = newNode;
  14277. transaction.currentWriteId = repoGetNextWriteId(repo);
  14278. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  14279. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  14280. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  14281. }
  14282. }
  14283. /**
  14284. * @param excludeSets - A specific set to exclude
  14285. */
  14286. function repoGetLatestState(repo, path, excludeSets) {
  14287. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  14288. ChildrenNode.EMPTY_NODE);
  14289. }
  14290. /**
  14291. * Sends any already-run transactions that aren't waiting for outstanding
  14292. * transactions to complete.
  14293. *
  14294. * Externally it's called with no arguments, but it calls itself recursively
  14295. * with a particular transactionQueueTree node to recurse through the tree.
  14296. *
  14297. * @param node - transactionQueueTree node to start at.
  14298. */
  14299. function repoSendReadyTransactions(repo, node) {
  14300. if (node === void 0) { node = repo.transactionQueueTree_; }
  14301. // Before recursing, make sure any completed transactions are removed.
  14302. if (!node) {
  14303. repoPruneCompletedTransactionsBelowNode(repo, node);
  14304. }
  14305. if (treeGetValue(node)) {
  14306. var queue = repoBuildTransactionQueue(repo, node);
  14307. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  14308. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  14309. // If they're all run (and not sent), we can send them. Else, we must wait.
  14310. if (allRun) {
  14311. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  14312. }
  14313. }
  14314. else if (treeHasChildren(node)) {
  14315. treeForEachChild(node, function (childNode) {
  14316. repoSendReadyTransactions(repo, childNode);
  14317. });
  14318. }
  14319. }
  14320. /**
  14321. * Given a list of run transactions, send them to the server and then handle
  14322. * the result (success or failure).
  14323. *
  14324. * @param path - The location of the queue.
  14325. * @param queue - Queue of transactions under the specified location.
  14326. */
  14327. function repoSendTransactionQueue(repo, path, queue) {
  14328. // Mark transactions as sent and increment retry count!
  14329. var setsToIgnore = queue.map(function (txn) {
  14330. return txn.currentWriteId;
  14331. });
  14332. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  14333. var snapToSend = latestState;
  14334. var latestHash = latestState.hash();
  14335. for (var i = 0; i < queue.length; i++) {
  14336. var txn = queue[i];
  14337. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  14338. txn.status = 1 /* TransactionStatus.SENT */;
  14339. txn.retryCount++;
  14340. var relativePath = newRelativePath(path, txn.path);
  14341. // If we've gotten to this point, the output snapshot must be defined.
  14342. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  14343. }
  14344. var dataToSend = snapToSend.val(true);
  14345. var pathToSend = path;
  14346. // Send the put.
  14347. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  14348. repoLog(repo, 'transaction put response', {
  14349. path: pathToSend.toString(),
  14350. status: status
  14351. });
  14352. var events = [];
  14353. if (status === 'ok') {
  14354. // Queue up the callbacks and fire them after cleaning up all of our
  14355. // transaction state, since the callback could trigger more
  14356. // transactions or sets.
  14357. var callbacks = [];
  14358. var _loop_1 = function (i) {
  14359. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  14360. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  14361. if (queue[i].onComplete) {
  14362. // We never unset the output snapshot, and given that this
  14363. // transaction is complete, it should be set
  14364. callbacks.push(function () {
  14365. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  14366. });
  14367. }
  14368. queue[i].unwatcher();
  14369. };
  14370. for (var i = 0; i < queue.length; i++) {
  14371. _loop_1(i);
  14372. }
  14373. // Now remove the completed transactions.
  14374. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  14375. // There may be pending transactions that we can now send.
  14376. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  14377. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  14378. // Finally, trigger onComplete callbacks.
  14379. for (var i = 0; i < callbacks.length; i++) {
  14380. exceptionGuard(callbacks[i]);
  14381. }
  14382. }
  14383. else {
  14384. // transactions are no longer sent. Update their status appropriately.
  14385. if (status === 'datastale') {
  14386. for (var i = 0; i < queue.length; i++) {
  14387. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  14388. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  14389. }
  14390. else {
  14391. queue[i].status = 0 /* TransactionStatus.RUN */;
  14392. }
  14393. }
  14394. }
  14395. else {
  14396. warn$1('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  14397. for (var i = 0; i < queue.length; i++) {
  14398. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  14399. queue[i].abortReason = status;
  14400. }
  14401. }
  14402. repoRerunTransactions(repo, path);
  14403. }
  14404. }, latestHash);
  14405. }
  14406. /**
  14407. * Finds all transactions dependent on the data at changedPath and reruns them.
  14408. *
  14409. * Should be called any time cached data changes.
  14410. *
  14411. * Return the highest path that was affected by rerunning transactions. This
  14412. * is the path at which events need to be raised for.
  14413. *
  14414. * @param changedPath - The path in mergedData that changed.
  14415. * @returns The rootmost path that was affected by rerunning transactions.
  14416. */
  14417. function repoRerunTransactions(repo, changedPath) {
  14418. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  14419. var path = treeGetPath(rootMostTransactionNode);
  14420. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  14421. repoRerunTransactionQueue(repo, queue, path);
  14422. return path;
  14423. }
  14424. /**
  14425. * Does all the work of rerunning transactions (as well as cleans up aborted
  14426. * transactions and whatnot).
  14427. *
  14428. * @param queue - The queue of transactions to run.
  14429. * @param path - The path the queue is for.
  14430. */
  14431. function repoRerunTransactionQueue(repo, queue, path) {
  14432. if (queue.length === 0) {
  14433. return; // Nothing to do!
  14434. }
  14435. // Queue up the callbacks and fire them after cleaning up all of our
  14436. // transaction state, since the callback could trigger more transactions or
  14437. // sets.
  14438. var callbacks = [];
  14439. var events = [];
  14440. // Ignore all of the sets we're going to re-run.
  14441. var txnsToRerun = queue.filter(function (q) {
  14442. return q.status === 0 /* TransactionStatus.RUN */;
  14443. });
  14444. var setsToIgnore = txnsToRerun.map(function (q) {
  14445. return q.currentWriteId;
  14446. });
  14447. var _loop_2 = function (i) {
  14448. var transaction = queue[i];
  14449. var relativePath = newRelativePath(path, transaction.path);
  14450. var abortTransaction = false, abortReason;
  14451. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  14452. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  14453. abortTransaction = true;
  14454. abortReason = transaction.abortReason;
  14455. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14456. }
  14457. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  14458. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  14459. abortTransaction = true;
  14460. abortReason = 'maxretry';
  14461. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14462. }
  14463. else {
  14464. // This code reruns a transaction
  14465. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  14466. transaction.currentInputSnapshot = currentNode;
  14467. var newData = queue[i].update(currentNode.val());
  14468. if (newData !== undefined) {
  14469. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  14470. var newDataNode = nodeFromJSON(newData);
  14471. var hasExplicitPriority = typeof newData === 'object' &&
  14472. newData != null &&
  14473. util.contains(newData, '.priority');
  14474. if (!hasExplicitPriority) {
  14475. // Keep the old priority if there wasn't a priority explicitly specified.
  14476. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  14477. }
  14478. var oldWriteId = transaction.currentWriteId;
  14479. var serverValues = repoGenerateServerValues(repo);
  14480. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  14481. transaction.currentOutputSnapshotRaw = newDataNode;
  14482. transaction.currentOutputSnapshotResolved = newNodeResolved;
  14483. transaction.currentWriteId = repoGetNextWriteId(repo);
  14484. // Mutates setsToIgnore in place
  14485. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  14486. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  14487. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  14488. }
  14489. else {
  14490. abortTransaction = true;
  14491. abortReason = 'nodata';
  14492. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  14493. }
  14494. }
  14495. }
  14496. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  14497. events = [];
  14498. if (abortTransaction) {
  14499. // Abort.
  14500. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  14501. // Removing a listener can trigger pruning which can muck with
  14502. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  14503. // until we're done.
  14504. (function (unwatcher) {
  14505. setTimeout(unwatcher, Math.floor(0));
  14506. })(queue[i].unwatcher);
  14507. if (queue[i].onComplete) {
  14508. if (abortReason === 'nodata') {
  14509. callbacks.push(function () {
  14510. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  14511. });
  14512. }
  14513. else {
  14514. callbacks.push(function () {
  14515. return queue[i].onComplete(new Error(abortReason), false, null);
  14516. });
  14517. }
  14518. }
  14519. }
  14520. };
  14521. for (var i = 0; i < queue.length; i++) {
  14522. _loop_2(i);
  14523. }
  14524. // Clean up completed transactions.
  14525. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  14526. // Now fire callbacks, now that we're in a good, known state.
  14527. for (var i = 0; i < callbacks.length; i++) {
  14528. exceptionGuard(callbacks[i]);
  14529. }
  14530. // Try to send the transaction result to the server.
  14531. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  14532. }
  14533. /**
  14534. * Returns the rootmost ancestor node of the specified path that has a pending
  14535. * transaction on it, or just returns the node for the given path if there are
  14536. * no pending transactions on any ancestor.
  14537. *
  14538. * @param path - The location to start at.
  14539. * @returns The rootmost node with a transaction.
  14540. */
  14541. function repoGetAncestorTransactionNode(repo, path) {
  14542. var front;
  14543. // Start at the root and walk deeper into the tree towards path until we
  14544. // find a node with pending transactions.
  14545. var transactionNode = repo.transactionQueueTree_;
  14546. front = pathGetFront(path);
  14547. while (front !== null && treeGetValue(transactionNode) === undefined) {
  14548. transactionNode = treeSubTree(transactionNode, front);
  14549. path = pathPopFront(path);
  14550. front = pathGetFront(path);
  14551. }
  14552. return transactionNode;
  14553. }
  14554. /**
  14555. * Builds the queue of all transactions at or below the specified
  14556. * transactionNode.
  14557. *
  14558. * @param transactionNode
  14559. * @returns The generated queue.
  14560. */
  14561. function repoBuildTransactionQueue(repo, transactionNode) {
  14562. // Walk any child transaction queues and aggregate them into a single queue.
  14563. var transactionQueue = [];
  14564. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  14565. // Sort them by the order the transactions were created.
  14566. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  14567. return transactionQueue;
  14568. }
  14569. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  14570. var nodeQueue = treeGetValue(node);
  14571. if (nodeQueue) {
  14572. for (var i = 0; i < nodeQueue.length; i++) {
  14573. queue.push(nodeQueue[i]);
  14574. }
  14575. }
  14576. treeForEachChild(node, function (child) {
  14577. repoAggregateTransactionQueuesForNode(repo, child, queue);
  14578. });
  14579. }
  14580. /**
  14581. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  14582. */
  14583. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  14584. var queue = treeGetValue(node);
  14585. if (queue) {
  14586. var to = 0;
  14587. for (var from = 0; from < queue.length; from++) {
  14588. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  14589. queue[to] = queue[from];
  14590. to++;
  14591. }
  14592. }
  14593. queue.length = to;
  14594. treeSetValue(node, queue.length > 0 ? queue : undefined);
  14595. }
  14596. treeForEachChild(node, function (childNode) {
  14597. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  14598. });
  14599. }
  14600. /**
  14601. * Aborts all transactions on ancestors or descendants of the specified path.
  14602. * Called when doing a set() or update() since we consider them incompatible
  14603. * with transactions.
  14604. *
  14605. * @param path - Path for which we want to abort related transactions.
  14606. */
  14607. function repoAbortTransactions(repo, path) {
  14608. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  14609. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  14610. treeForEachAncestor(transactionNode, function (node) {
  14611. repoAbortTransactionsOnNode(repo, node);
  14612. });
  14613. repoAbortTransactionsOnNode(repo, transactionNode);
  14614. treeForEachDescendant(transactionNode, function (node) {
  14615. repoAbortTransactionsOnNode(repo, node);
  14616. });
  14617. return affectedPath;
  14618. }
  14619. /**
  14620. * Abort transactions stored in this transaction queue node.
  14621. *
  14622. * @param node - Node to abort transactions for.
  14623. */
  14624. function repoAbortTransactionsOnNode(repo, node) {
  14625. var queue = treeGetValue(node);
  14626. if (queue) {
  14627. // Queue up the callbacks and fire them after cleaning up all of our
  14628. // transaction state, since the callback could trigger more transactions
  14629. // or sets.
  14630. var callbacks = [];
  14631. // Go through queue. Any already-sent transactions must be marked for
  14632. // abort, while the unsent ones can be immediately aborted and removed.
  14633. var events = [];
  14634. var lastSent = -1;
  14635. for (var i = 0; i < queue.length; i++) {
  14636. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  14637. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  14638. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  14639. lastSent = i;
  14640. // Mark transaction for abort when it comes back.
  14641. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  14642. queue[i].abortReason = 'set';
  14643. }
  14644. else {
  14645. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  14646. // We can abort it immediately.
  14647. queue[i].unwatcher();
  14648. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  14649. if (queue[i].onComplete) {
  14650. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  14651. }
  14652. }
  14653. }
  14654. if (lastSent === -1) {
  14655. // We're not waiting for any sent transactions. We can clear the queue.
  14656. treeSetValue(node, undefined);
  14657. }
  14658. else {
  14659. // Remove the transactions we aborted.
  14660. queue.length = lastSent + 1;
  14661. }
  14662. // Now fire the callbacks.
  14663. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  14664. for (var i = 0; i < callbacks.length; i++) {
  14665. exceptionGuard(callbacks[i]);
  14666. }
  14667. }
  14668. }
  14669. /**
  14670. * @license
  14671. * Copyright 2017 Google LLC
  14672. *
  14673. * Licensed under the Apache License, Version 2.0 (the "License");
  14674. * you may not use this file except in compliance with the License.
  14675. * You may obtain a copy of the License at
  14676. *
  14677. * http://www.apache.org/licenses/LICENSE-2.0
  14678. *
  14679. * Unless required by applicable law or agreed to in writing, software
  14680. * distributed under the License is distributed on an "AS IS" BASIS,
  14681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14682. * See the License for the specific language governing permissions and
  14683. * limitations under the License.
  14684. */
  14685. function decodePath(pathString) {
  14686. var pathStringDecoded = '';
  14687. var pieces = pathString.split('/');
  14688. for (var i = 0; i < pieces.length; i++) {
  14689. if (pieces[i].length > 0) {
  14690. var piece = pieces[i];
  14691. try {
  14692. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  14693. }
  14694. catch (e) { }
  14695. pathStringDecoded += '/' + piece;
  14696. }
  14697. }
  14698. return pathStringDecoded;
  14699. }
  14700. /**
  14701. * @returns key value hash
  14702. */
  14703. function decodeQuery(queryString) {
  14704. var e_1, _a;
  14705. var results = {};
  14706. if (queryString.charAt(0) === '?') {
  14707. queryString = queryString.substring(1);
  14708. }
  14709. try {
  14710. for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  14711. var segment = _c.value;
  14712. if (segment.length === 0) {
  14713. continue;
  14714. }
  14715. var kv = segment.split('=');
  14716. if (kv.length === 2) {
  14717. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  14718. }
  14719. else {
  14720. warn$1("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  14721. }
  14722. }
  14723. }
  14724. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  14725. finally {
  14726. try {
  14727. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  14728. }
  14729. finally { if (e_1) throw e_1.error; }
  14730. }
  14731. return results;
  14732. }
  14733. var parseRepoInfo = function (dataURL, nodeAdmin) {
  14734. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  14735. if (parsedUrl.domain === 'firebase.com') {
  14736. fatal(parsedUrl.host +
  14737. ' is no longer supported. ' +
  14738. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  14739. }
  14740. // Catch common error of uninitialized namespace value.
  14741. if ((!namespace || namespace === 'undefined') &&
  14742. parsedUrl.domain !== 'localhost') {
  14743. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  14744. }
  14745. if (!parsedUrl.secure) {
  14746. warnIfPageIsSecure();
  14747. }
  14748. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  14749. return {
  14750. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  14751. /*persistenceKey=*/ '',
  14752. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  14753. path: new Path(parsedUrl.pathString)
  14754. };
  14755. };
  14756. var parseDatabaseURL = function (dataURL) {
  14757. // Default to empty strings in the event of a malformed string.
  14758. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  14759. // Always default to SSL, unless otherwise specified.
  14760. var secure = true, scheme = 'https', port = 443;
  14761. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  14762. if (typeof dataURL === 'string') {
  14763. // Parse scheme.
  14764. var colonInd = dataURL.indexOf('//');
  14765. if (colonInd >= 0) {
  14766. scheme = dataURL.substring(0, colonInd - 1);
  14767. dataURL = dataURL.substring(colonInd + 2);
  14768. }
  14769. // Parse host, path, and query string.
  14770. var slashInd = dataURL.indexOf('/');
  14771. if (slashInd === -1) {
  14772. slashInd = dataURL.length;
  14773. }
  14774. var questionMarkInd = dataURL.indexOf('?');
  14775. if (questionMarkInd === -1) {
  14776. questionMarkInd = dataURL.length;
  14777. }
  14778. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  14779. if (slashInd < questionMarkInd) {
  14780. // For pathString, questionMarkInd will always come after slashInd
  14781. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  14782. }
  14783. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  14784. // If we have a port, use scheme for determining if it's secure.
  14785. colonInd = host.indexOf(':');
  14786. if (colonInd >= 0) {
  14787. secure = scheme === 'https' || scheme === 'wss';
  14788. port = parseInt(host.substring(colonInd + 1), 10);
  14789. }
  14790. else {
  14791. colonInd = host.length;
  14792. }
  14793. var hostWithoutPort = host.slice(0, colonInd);
  14794. if (hostWithoutPort.toLowerCase() === 'localhost') {
  14795. domain = 'localhost';
  14796. }
  14797. else if (hostWithoutPort.split('.').length <= 2) {
  14798. domain = hostWithoutPort;
  14799. }
  14800. else {
  14801. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  14802. var dotInd = host.indexOf('.');
  14803. subdomain = host.substring(0, dotInd).toLowerCase();
  14804. domain = host.substring(dotInd + 1);
  14805. // Normalize namespaces to lowercase to share storage / connection.
  14806. namespace = subdomain;
  14807. }
  14808. // Always treat the value of the `ns` as the namespace name if it is present.
  14809. if ('ns' in queryParams) {
  14810. namespace = queryParams['ns'];
  14811. }
  14812. }
  14813. return {
  14814. host: host,
  14815. port: port,
  14816. domain: domain,
  14817. subdomain: subdomain,
  14818. secure: secure,
  14819. scheme: scheme,
  14820. pathString: pathString,
  14821. namespace: namespace
  14822. };
  14823. };
  14824. /**
  14825. * @license
  14826. * Copyright 2017 Google LLC
  14827. *
  14828. * Licensed under the Apache License, Version 2.0 (the "License");
  14829. * you may not use this file except in compliance with the License.
  14830. * You may obtain a copy of the License at
  14831. *
  14832. * http://www.apache.org/licenses/LICENSE-2.0
  14833. *
  14834. * Unless required by applicable law or agreed to in writing, software
  14835. * distributed under the License is distributed on an "AS IS" BASIS,
  14836. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14837. * See the License for the specific language governing permissions and
  14838. * limitations under the License.
  14839. */
  14840. // Modeled after base64 web-safe chars, but ordered by ASCII.
  14841. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  14842. /**
  14843. * Fancy ID generator that creates 20-character string identifiers with the
  14844. * following properties:
  14845. *
  14846. * 1. They're based on timestamp so that they sort *after* any existing ids.
  14847. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  14848. * collide with other clients' IDs.
  14849. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  14850. * that will sort properly).
  14851. * 4. They're monotonically increasing. Even if you generate more than one in
  14852. * the same timestamp, the latter ones will sort after the former ones. We do
  14853. * this by using the previous random bits but "incrementing" them by 1 (only
  14854. * in the case of a timestamp collision).
  14855. */
  14856. var nextPushId = (function () {
  14857. // Timestamp of last push, used to prevent local collisions if you push twice
  14858. // in one ms.
  14859. var lastPushTime = 0;
  14860. // We generate 72-bits of randomness which get turned into 12 characters and
  14861. // appended to the timestamp to prevent collisions with other clients. We
  14862. // store the last characters we generated because in the event of a collision,
  14863. // we'll use those same characters except "incremented" by one.
  14864. var lastRandChars = [];
  14865. return function (now) {
  14866. var duplicateTime = now === lastPushTime;
  14867. lastPushTime = now;
  14868. var i;
  14869. var timeStampChars = new Array(8);
  14870. for (i = 7; i >= 0; i--) {
  14871. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  14872. // NOTE: Can't use << here because javascript will convert to int and lose
  14873. // the upper bits.
  14874. now = Math.floor(now / 64);
  14875. }
  14876. util.assert(now === 0, 'Cannot push at time == 0');
  14877. var id = timeStampChars.join('');
  14878. if (!duplicateTime) {
  14879. for (i = 0; i < 12; i++) {
  14880. lastRandChars[i] = Math.floor(Math.random() * 64);
  14881. }
  14882. }
  14883. else {
  14884. // If the timestamp hasn't changed since last push, use the same random
  14885. // number, except incremented by 1.
  14886. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  14887. lastRandChars[i] = 0;
  14888. }
  14889. lastRandChars[i]++;
  14890. }
  14891. for (i = 0; i < 12; i++) {
  14892. id += PUSH_CHARS.charAt(lastRandChars[i]);
  14893. }
  14894. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  14895. return id;
  14896. };
  14897. })();
  14898. /**
  14899. * @license
  14900. * Copyright 2017 Google LLC
  14901. *
  14902. * Licensed under the Apache License, Version 2.0 (the "License");
  14903. * you may not use this file except in compliance with the License.
  14904. * You may obtain a copy of the License at
  14905. *
  14906. * http://www.apache.org/licenses/LICENSE-2.0
  14907. *
  14908. * Unless required by applicable law or agreed to in writing, software
  14909. * distributed under the License is distributed on an "AS IS" BASIS,
  14910. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14911. * See the License for the specific language governing permissions and
  14912. * limitations under the License.
  14913. */
  14914. /**
  14915. * Encapsulates the data needed to raise an event
  14916. */
  14917. var DataEvent = /** @class */ (function () {
  14918. /**
  14919. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  14920. * @param eventRegistration - The function to call to with the event data. User provided
  14921. * @param snapshot - The data backing the event
  14922. * @param prevName - Optional, the name of the previous child for child_* events.
  14923. */
  14924. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  14925. this.eventType = eventType;
  14926. this.eventRegistration = eventRegistration;
  14927. this.snapshot = snapshot;
  14928. this.prevName = prevName;
  14929. }
  14930. DataEvent.prototype.getPath = function () {
  14931. var ref = this.snapshot.ref;
  14932. if (this.eventType === 'value') {
  14933. return ref._path;
  14934. }
  14935. else {
  14936. return ref.parent._path;
  14937. }
  14938. };
  14939. DataEvent.prototype.getEventType = function () {
  14940. return this.eventType;
  14941. };
  14942. DataEvent.prototype.getEventRunner = function () {
  14943. return this.eventRegistration.getEventRunner(this);
  14944. };
  14945. DataEvent.prototype.toString = function () {
  14946. return (this.getPath().toString() +
  14947. ':' +
  14948. this.eventType +
  14949. ':' +
  14950. util.stringify(this.snapshot.exportVal()));
  14951. };
  14952. return DataEvent;
  14953. }());
  14954. var CancelEvent = /** @class */ (function () {
  14955. function CancelEvent(eventRegistration, error, path) {
  14956. this.eventRegistration = eventRegistration;
  14957. this.error = error;
  14958. this.path = path;
  14959. }
  14960. CancelEvent.prototype.getPath = function () {
  14961. return this.path;
  14962. };
  14963. CancelEvent.prototype.getEventType = function () {
  14964. return 'cancel';
  14965. };
  14966. CancelEvent.prototype.getEventRunner = function () {
  14967. return this.eventRegistration.getEventRunner(this);
  14968. };
  14969. CancelEvent.prototype.toString = function () {
  14970. return this.path.toString() + ':cancel';
  14971. };
  14972. return CancelEvent;
  14973. }());
  14974. /**
  14975. * @license
  14976. * Copyright 2017 Google LLC
  14977. *
  14978. * Licensed under the Apache License, Version 2.0 (the "License");
  14979. * you may not use this file except in compliance with the License.
  14980. * You may obtain a copy of the License at
  14981. *
  14982. * http://www.apache.org/licenses/LICENSE-2.0
  14983. *
  14984. * Unless required by applicable law or agreed to in writing, software
  14985. * distributed under the License is distributed on an "AS IS" BASIS,
  14986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14987. * See the License for the specific language governing permissions and
  14988. * limitations under the License.
  14989. */
  14990. /**
  14991. * A wrapper class that converts events from the database@exp SDK to the legacy
  14992. * Database SDK. Events are not converted directly as event registration relies
  14993. * on reference comparison of the original user callback (see `matches()`) and
  14994. * relies on equality of the legacy SDK's `context` object.
  14995. */
  14996. var CallbackContext = /** @class */ (function () {
  14997. function CallbackContext(snapshotCallback, cancelCallback) {
  14998. this.snapshotCallback = snapshotCallback;
  14999. this.cancelCallback = cancelCallback;
  15000. }
  15001. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  15002. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  15003. };
  15004. CallbackContext.prototype.onCancel = function (error) {
  15005. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  15006. return this.cancelCallback.call(null, error);
  15007. };
  15008. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  15009. get: function () {
  15010. return !!this.cancelCallback;
  15011. },
  15012. enumerable: false,
  15013. configurable: true
  15014. });
  15015. CallbackContext.prototype.matches = function (other) {
  15016. return (this.snapshotCallback === other.snapshotCallback ||
  15017. (this.snapshotCallback.userCallback !== undefined &&
  15018. this.snapshotCallback.userCallback ===
  15019. other.snapshotCallback.userCallback &&
  15020. this.snapshotCallback.context === other.snapshotCallback.context));
  15021. };
  15022. return CallbackContext;
  15023. }());
  15024. /**
  15025. * @license
  15026. * Copyright 2021 Google LLC
  15027. *
  15028. * Licensed under the Apache License, Version 2.0 (the "License");
  15029. * you may not use this file except in compliance with the License.
  15030. * You may obtain a copy of the License at
  15031. *
  15032. * http://www.apache.org/licenses/LICENSE-2.0
  15033. *
  15034. * Unless required by applicable law or agreed to in writing, software
  15035. * distributed under the License is distributed on an "AS IS" BASIS,
  15036. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15037. * See the License for the specific language governing permissions and
  15038. * limitations under the License.
  15039. */
  15040. /**
  15041. * The `onDisconnect` class allows you to write or clear data when your client
  15042. * disconnects from the Database server. These updates occur whether your
  15043. * client disconnects cleanly or not, so you can rely on them to clean up data
  15044. * even if a connection is dropped or a client crashes.
  15045. *
  15046. * The `onDisconnect` class is most commonly used to manage presence in
  15047. * applications where it is useful to detect how many clients are connected and
  15048. * when other clients disconnect. See
  15049. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  15050. * for more information.
  15051. *
  15052. * To avoid problems when a connection is dropped before the requests can be
  15053. * transferred to the Database server, these functions should be called before
  15054. * writing any data.
  15055. *
  15056. * Note that `onDisconnect` operations are only triggered once. If you want an
  15057. * operation to occur each time a disconnect occurs, you'll need to re-establish
  15058. * the `onDisconnect` operations each time you reconnect.
  15059. */
  15060. var OnDisconnect$1 = /** @class */ (function () {
  15061. /** @hideconstructor */
  15062. function OnDisconnect(_repo, _path) {
  15063. this._repo = _repo;
  15064. this._path = _path;
  15065. }
  15066. /**
  15067. * Cancels all previously queued `onDisconnect()` set or update events for this
  15068. * location and all children.
  15069. *
  15070. * If a write has been queued for this location via a `set()` or `update()` at a
  15071. * parent location, the write at this location will be canceled, though writes
  15072. * to sibling locations will still occur.
  15073. *
  15074. * @returns Resolves when synchronization to the server is complete.
  15075. */
  15076. OnDisconnect.prototype.cancel = function () {
  15077. var deferred = new util.Deferred();
  15078. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  15079. return deferred.promise;
  15080. };
  15081. /**
  15082. * Ensures the data at this location is deleted when the client is disconnected
  15083. * (due to closing the browser, navigating to a new page, or network issues).
  15084. *
  15085. * @returns Resolves when synchronization to the server is complete.
  15086. */
  15087. OnDisconnect.prototype.remove = function () {
  15088. validateWritablePath('OnDisconnect.remove', this._path);
  15089. var deferred = new util.Deferred();
  15090. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  15091. return deferred.promise;
  15092. };
  15093. /**
  15094. * Ensures the data at this location is set to the specified value when the
  15095. * client is disconnected (due to closing the browser, navigating to a new page,
  15096. * or network issues).
  15097. *
  15098. * `set()` is especially useful for implementing "presence" systems, where a
  15099. * value should be changed or cleared when a user disconnects so that they
  15100. * appear "offline" to other users. See
  15101. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  15102. * for more information.
  15103. *
  15104. * Note that `onDisconnect` operations are only triggered once. If you want an
  15105. * operation to occur each time a disconnect occurs, you'll need to re-establish
  15106. * the `onDisconnect` operations each time.
  15107. *
  15108. * @param value - The value to be written to this location on disconnect (can
  15109. * be an object, array, string, number, boolean, or null).
  15110. * @returns Resolves when synchronization to the Database is complete.
  15111. */
  15112. OnDisconnect.prototype.set = function (value) {
  15113. validateWritablePath('OnDisconnect.set', this._path);
  15114. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  15115. var deferred = new util.Deferred();
  15116. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  15117. return deferred.promise;
  15118. };
  15119. /**
  15120. * Ensures the data at this location is set to the specified value and priority
  15121. * when the client is disconnected (due to closing the browser, navigating to a
  15122. * new page, or network issues).
  15123. *
  15124. * @param value - The value to be written to this location on disconnect (can
  15125. * be an object, array, string, number, boolean, or null).
  15126. * @param priority - The priority to be written (string, number, or null).
  15127. * @returns Resolves when synchronization to the Database is complete.
  15128. */
  15129. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  15130. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  15131. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  15132. validatePriority('OnDisconnect.setWithPriority', priority, false);
  15133. var deferred = new util.Deferred();
  15134. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  15135. return deferred.promise;
  15136. };
  15137. /**
  15138. * Writes multiple values at this location when the client is disconnected (due
  15139. * to closing the browser, navigating to a new page, or network issues).
  15140. *
  15141. * The `values` argument contains multiple property-value pairs that will be
  15142. * written to the Database together. Each child property can either be a simple
  15143. * property (for example, "name") or a relative path (for example, "name/first")
  15144. * from the current location to the data to update.
  15145. *
  15146. * As opposed to the `set()` method, `update()` can be use to selectively update
  15147. * only the referenced properties at the current location (instead of replacing
  15148. * all the child properties at the current location).
  15149. *
  15150. * @param values - Object containing multiple values.
  15151. * @returns Resolves when synchronization to the Database is complete.
  15152. */
  15153. OnDisconnect.prototype.update = function (values) {
  15154. validateWritablePath('OnDisconnect.update', this._path);
  15155. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  15156. var deferred = new util.Deferred();
  15157. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  15158. return deferred.promise;
  15159. };
  15160. return OnDisconnect;
  15161. }());
  15162. /**
  15163. * @license
  15164. * Copyright 2020 Google LLC
  15165. *
  15166. * Licensed under the Apache License, Version 2.0 (the "License");
  15167. * you may not use this file except in compliance with the License.
  15168. * You may obtain a copy of the License at
  15169. *
  15170. * http://www.apache.org/licenses/LICENSE-2.0
  15171. *
  15172. * Unless required by applicable law or agreed to in writing, software
  15173. * distributed under the License is distributed on an "AS IS" BASIS,
  15174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15175. * See the License for the specific language governing permissions and
  15176. * limitations under the License.
  15177. */
  15178. /**
  15179. * @internal
  15180. */
  15181. var QueryImpl = /** @class */ (function () {
  15182. /**
  15183. * @hideconstructor
  15184. */
  15185. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  15186. this._repo = _repo;
  15187. this._path = _path;
  15188. this._queryParams = _queryParams;
  15189. this._orderByCalled = _orderByCalled;
  15190. }
  15191. Object.defineProperty(QueryImpl.prototype, "key", {
  15192. get: function () {
  15193. if (pathIsEmpty(this._path)) {
  15194. return null;
  15195. }
  15196. else {
  15197. return pathGetBack(this._path);
  15198. }
  15199. },
  15200. enumerable: false,
  15201. configurable: true
  15202. });
  15203. Object.defineProperty(QueryImpl.prototype, "ref", {
  15204. get: function () {
  15205. return new ReferenceImpl(this._repo, this._path);
  15206. },
  15207. enumerable: false,
  15208. configurable: true
  15209. });
  15210. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  15211. get: function () {
  15212. var obj = queryParamsGetQueryObject(this._queryParams);
  15213. var id = ObjectToUniqueKey(obj);
  15214. return id === '{}' ? 'default' : id;
  15215. },
  15216. enumerable: false,
  15217. configurable: true
  15218. });
  15219. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  15220. /**
  15221. * An object representation of the query parameters used by this Query.
  15222. */
  15223. get: function () {
  15224. return queryParamsGetQueryObject(this._queryParams);
  15225. },
  15226. enumerable: false,
  15227. configurable: true
  15228. });
  15229. QueryImpl.prototype.isEqual = function (other) {
  15230. other = util.getModularInstance(other);
  15231. if (!(other instanceof QueryImpl)) {
  15232. return false;
  15233. }
  15234. var sameRepo = this._repo === other._repo;
  15235. var samePath = pathEquals(this._path, other._path);
  15236. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  15237. return sameRepo && samePath && sameQueryIdentifier;
  15238. };
  15239. QueryImpl.prototype.toJSON = function () {
  15240. return this.toString();
  15241. };
  15242. QueryImpl.prototype.toString = function () {
  15243. return this._repo.toString() + pathToUrlEncodedString(this._path);
  15244. };
  15245. return QueryImpl;
  15246. }());
  15247. /**
  15248. * Validates that no other order by call has been made
  15249. */
  15250. function validateNoPreviousOrderByCall(query, fnName) {
  15251. if (query._orderByCalled === true) {
  15252. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  15253. }
  15254. }
  15255. /**
  15256. * Validates start/end values for queries.
  15257. */
  15258. function validateQueryEndpoints(params) {
  15259. var startNode = null;
  15260. var endNode = null;
  15261. if (params.hasStart()) {
  15262. startNode = params.getIndexStartValue();
  15263. }
  15264. if (params.hasEnd()) {
  15265. endNode = params.getIndexEndValue();
  15266. }
  15267. if (params.getIndex() === KEY_INDEX) {
  15268. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  15269. 'startAt(), endAt(), or equalTo().';
  15270. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  15271. 'endAt(), endBefore(), or equalTo() must be a string.';
  15272. if (params.hasStart()) {
  15273. var startName = params.getIndexStartName();
  15274. if (startName !== MIN_NAME) {
  15275. throw new Error(tooManyArgsError);
  15276. }
  15277. else if (typeof startNode !== 'string') {
  15278. throw new Error(wrongArgTypeError);
  15279. }
  15280. }
  15281. if (params.hasEnd()) {
  15282. var endName = params.getIndexEndName();
  15283. if (endName !== MAX_NAME) {
  15284. throw new Error(tooManyArgsError);
  15285. }
  15286. else if (typeof endNode !== 'string') {
  15287. throw new Error(wrongArgTypeError);
  15288. }
  15289. }
  15290. }
  15291. else if (params.getIndex() === PRIORITY_INDEX) {
  15292. if ((startNode != null && !isValidPriority(startNode)) ||
  15293. (endNode != null && !isValidPriority(endNode))) {
  15294. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  15295. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  15296. '(null, a number, or a string).');
  15297. }
  15298. }
  15299. else {
  15300. util.assert(params.getIndex() instanceof PathIndex ||
  15301. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  15302. if ((startNode != null && typeof startNode === 'object') ||
  15303. (endNode != null && typeof endNode === 'object')) {
  15304. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  15305. 'equalTo() cannot be an object.');
  15306. }
  15307. }
  15308. }
  15309. /**
  15310. * Validates that limit* has been called with the correct combination of parameters
  15311. */
  15312. function validateLimit(params) {
  15313. if (params.hasStart() &&
  15314. params.hasEnd() &&
  15315. params.hasLimit() &&
  15316. !params.hasAnchoredLimit()) {
  15317. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  15318. 'limitToFirst() or limitToLast() instead.');
  15319. }
  15320. }
  15321. /**
  15322. * @internal
  15323. */
  15324. var ReferenceImpl = /** @class */ (function (_super) {
  15325. tslib.__extends(ReferenceImpl, _super);
  15326. /** @hideconstructor */
  15327. function ReferenceImpl(repo, path) {
  15328. return _super.call(this, repo, path, new QueryParams(), false) || this;
  15329. }
  15330. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  15331. get: function () {
  15332. var parentPath = pathParent(this._path);
  15333. return parentPath === null
  15334. ? null
  15335. : new ReferenceImpl(this._repo, parentPath);
  15336. },
  15337. enumerable: false,
  15338. configurable: true
  15339. });
  15340. Object.defineProperty(ReferenceImpl.prototype, "root", {
  15341. get: function () {
  15342. var ref = this;
  15343. while (ref.parent !== null) {
  15344. ref = ref.parent;
  15345. }
  15346. return ref;
  15347. },
  15348. enumerable: false,
  15349. configurable: true
  15350. });
  15351. return ReferenceImpl;
  15352. }(QueryImpl));
  15353. /**
  15354. * A `DataSnapshot` contains data from a Database location.
  15355. *
  15356. * Any time you read data from the Database, you receive the data as a
  15357. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  15358. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  15359. * JavaScript object by calling the `val()` method. Alternatively, you can
  15360. * traverse into the snapshot by calling `child()` to return child snapshots
  15361. * (which you could then call `val()` on).
  15362. *
  15363. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  15364. * a Database location. It cannot be modified and will never change (to modify
  15365. * data, you always call the `set()` method on a `Reference` directly).
  15366. */
  15367. var DataSnapshot$1 = /** @class */ (function () {
  15368. /**
  15369. * @param _node - A SnapshotNode to wrap.
  15370. * @param ref - The location this snapshot came from.
  15371. * @param _index - The iteration order for this snapshot
  15372. * @hideconstructor
  15373. */
  15374. function DataSnapshot(_node,
  15375. /**
  15376. * The location of this DataSnapshot.
  15377. */
  15378. ref, _index) {
  15379. this._node = _node;
  15380. this.ref = ref;
  15381. this._index = _index;
  15382. }
  15383. Object.defineProperty(DataSnapshot.prototype, "priority", {
  15384. /**
  15385. * Gets the priority value of the data in this `DataSnapshot`.
  15386. *
  15387. * Applications need not use priority but can order collections by
  15388. * ordinary properties (see
  15389. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  15390. * ).
  15391. */
  15392. get: function () {
  15393. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  15394. return this._node.getPriority().val();
  15395. },
  15396. enumerable: false,
  15397. configurable: true
  15398. });
  15399. Object.defineProperty(DataSnapshot.prototype, "key", {
  15400. /**
  15401. * The key (last part of the path) of the location of this `DataSnapshot`.
  15402. *
  15403. * The last token in a Database location is considered its key. For example,
  15404. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  15405. * `DataSnapshot` will return the key for the location that generated it.
  15406. * However, accessing the key on the root URL of a Database will return
  15407. * `null`.
  15408. */
  15409. get: function () {
  15410. return this.ref.key;
  15411. },
  15412. enumerable: false,
  15413. configurable: true
  15414. });
  15415. Object.defineProperty(DataSnapshot.prototype, "size", {
  15416. /** Returns the number of child properties of this `DataSnapshot`. */
  15417. get: function () {
  15418. return this._node.numChildren();
  15419. },
  15420. enumerable: false,
  15421. configurable: true
  15422. });
  15423. /**
  15424. * Gets another `DataSnapshot` for the location at the specified relative path.
  15425. *
  15426. * Passing a relative path to the `child()` method of a DataSnapshot returns
  15427. * another `DataSnapshot` for the location at the specified relative path. The
  15428. * relative path can either be a simple child name (for example, "ada") or a
  15429. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  15430. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  15431. * whose value is `null`) is returned.
  15432. *
  15433. * @param path - A relative path to the location of child data.
  15434. */
  15435. DataSnapshot.prototype.child = function (path) {
  15436. var childPath = new Path(path);
  15437. var childRef = child(this.ref, path);
  15438. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  15439. };
  15440. /**
  15441. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  15442. * efficient than using `snapshot.val() !== null`.
  15443. */
  15444. DataSnapshot.prototype.exists = function () {
  15445. return !this._node.isEmpty();
  15446. };
  15447. /**
  15448. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  15449. *
  15450. * The `exportVal()` method is similar to `val()`, except priority information
  15451. * is included (if available), making it suitable for backing up your data.
  15452. *
  15453. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  15454. * Array, string, number, boolean, or `null`).
  15455. */
  15456. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15457. DataSnapshot.prototype.exportVal = function () {
  15458. return this._node.val(true);
  15459. };
  15460. /**
  15461. * Enumerates the top-level children in the `DataSnapshot`.
  15462. *
  15463. * Because of the way JavaScript objects work, the ordering of data in the
  15464. * JavaScript object returned by `val()` is not guaranteed to match the
  15465. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  15466. * where `forEach()` comes in handy. It guarantees the children of a
  15467. * `DataSnapshot` will be iterated in their query order.
  15468. *
  15469. * If no explicit `orderBy*()` method is used, results are returned
  15470. * ordered by key (unless priorities are used, in which case, results are
  15471. * returned by priority).
  15472. *
  15473. * @param action - A function that will be called for each child DataSnapshot.
  15474. * The callback can return true to cancel further enumeration.
  15475. * @returns true if enumeration was canceled due to your callback returning
  15476. * true.
  15477. */
  15478. DataSnapshot.prototype.forEach = function (action) {
  15479. var _this = this;
  15480. if (this._node.isLeafNode()) {
  15481. return false;
  15482. }
  15483. var childrenNode = this._node;
  15484. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  15485. return !!childrenNode.forEachChild(this._index, function (key, node) {
  15486. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  15487. });
  15488. };
  15489. /**
  15490. * Returns true if the specified child path has (non-null) data.
  15491. *
  15492. * @param path - A relative path to the location of a potential child.
  15493. * @returns `true` if data exists at the specified child path; else
  15494. * `false`.
  15495. */
  15496. DataSnapshot.prototype.hasChild = function (path) {
  15497. var childPath = new Path(path);
  15498. return !this._node.getChild(childPath).isEmpty();
  15499. };
  15500. /**
  15501. * Returns whether or not the `DataSnapshot` has any non-`null` child
  15502. * properties.
  15503. *
  15504. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  15505. * children. If it does, you can enumerate them using `forEach()`. If it
  15506. * doesn't, then either this snapshot contains a primitive value (which can be
  15507. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  15508. * `null`).
  15509. *
  15510. * @returns true if this snapshot has any children; else false.
  15511. */
  15512. DataSnapshot.prototype.hasChildren = function () {
  15513. if (this._node.isLeafNode()) {
  15514. return false;
  15515. }
  15516. else {
  15517. return !this._node.isEmpty();
  15518. }
  15519. };
  15520. /**
  15521. * Returns a JSON-serializable representation of this object.
  15522. */
  15523. DataSnapshot.prototype.toJSON = function () {
  15524. return this.exportVal();
  15525. };
  15526. /**
  15527. * Extracts a JavaScript value from a `DataSnapshot`.
  15528. *
  15529. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  15530. * scalar type (string, number, or boolean), an array, or an object. It may
  15531. * also return null, indicating that the `DataSnapshot` is empty (contains no
  15532. * data).
  15533. *
  15534. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  15535. * Array, string, number, boolean, or `null`).
  15536. */
  15537. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15538. DataSnapshot.prototype.val = function () {
  15539. return this._node.val();
  15540. };
  15541. return DataSnapshot;
  15542. }());
  15543. /**
  15544. *
  15545. * Returns a `Reference` representing the location in the Database
  15546. * corresponding to the provided path. If no path is provided, the `Reference`
  15547. * will point to the root of the Database.
  15548. *
  15549. * @param db - The database instance to obtain a reference for.
  15550. * @param path - Optional path representing the location the returned
  15551. * `Reference` will point. If not provided, the returned `Reference` will
  15552. * point to the root of the Database.
  15553. * @returns If a path is provided, a `Reference`
  15554. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  15555. * root of the Database.
  15556. */
  15557. function ref(db, path) {
  15558. db = util.getModularInstance(db);
  15559. db._checkNotDeleted('ref');
  15560. return path !== undefined ? child(db._root, path) : db._root;
  15561. }
  15562. /**
  15563. * Returns a `Reference` representing the location in the Database
  15564. * corresponding to the provided Firebase URL.
  15565. *
  15566. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  15567. * has a different domain than the current `Database` instance.
  15568. *
  15569. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  15570. * and are not applied to the returned `Reference`.
  15571. *
  15572. * @param db - The database instance to obtain a reference for.
  15573. * @param url - The Firebase URL at which the returned `Reference` will
  15574. * point.
  15575. * @returns A `Reference` pointing to the provided
  15576. * Firebase URL.
  15577. */
  15578. function refFromURL(db, url) {
  15579. db = util.getModularInstance(db);
  15580. db._checkNotDeleted('refFromURL');
  15581. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  15582. validateUrl('refFromURL', parsedURL);
  15583. var repoInfo = parsedURL.repoInfo;
  15584. if (!db._repo.repoInfo_.isCustomHost() &&
  15585. repoInfo.host !== db._repo.repoInfo_.host) {
  15586. fatal('refFromURL' +
  15587. ': Host name does not match the current database: ' +
  15588. '(found ' +
  15589. repoInfo.host +
  15590. ' but expected ' +
  15591. db._repo.repoInfo_.host +
  15592. ')');
  15593. }
  15594. return ref(db, parsedURL.path.toString());
  15595. }
  15596. /**
  15597. * Gets a `Reference` for the location at the specified relative path.
  15598. *
  15599. * The relative path can either be a simple child name (for example, "ada") or
  15600. * a deeper slash-separated path (for example, "ada/name/first").
  15601. *
  15602. * @param parent - The parent location.
  15603. * @param path - A relative path from this location to the desired child
  15604. * location.
  15605. * @returns The specified child location.
  15606. */
  15607. function child(parent, path) {
  15608. parent = util.getModularInstance(parent);
  15609. if (pathGetFront(parent._path) === null) {
  15610. validateRootPathString('child', 'path', path, false);
  15611. }
  15612. else {
  15613. validatePathString('child', 'path', path, false);
  15614. }
  15615. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  15616. }
  15617. /**
  15618. * Returns an `OnDisconnect` object - see
  15619. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  15620. * for more information on how to use it.
  15621. *
  15622. * @param ref - The reference to add OnDisconnect triggers for.
  15623. */
  15624. function onDisconnect(ref) {
  15625. ref = util.getModularInstance(ref);
  15626. return new OnDisconnect$1(ref._repo, ref._path);
  15627. }
  15628. /**
  15629. * Generates a new child location using a unique key and returns its
  15630. * `Reference`.
  15631. *
  15632. * This is the most common pattern for adding data to a collection of items.
  15633. *
  15634. * If you provide a value to `push()`, the value is written to the
  15635. * generated location. If you don't pass a value, nothing is written to the
  15636. * database and the child remains empty (but you can use the `Reference`
  15637. * elsewhere).
  15638. *
  15639. * The unique keys generated by `push()` are ordered by the current time, so the
  15640. * resulting list of items is chronologically sorted. The keys are also
  15641. * designed to be unguessable (they contain 72 random bits of entropy).
  15642. *
  15643. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  15644. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  15645. *
  15646. * @param parent - The parent location.
  15647. * @param value - Optional value to be written at the generated location.
  15648. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  15649. * but can be used immediately as the `Reference` to the child location.
  15650. */
  15651. function push(parent, value) {
  15652. parent = util.getModularInstance(parent);
  15653. validateWritablePath('push', parent._path);
  15654. validateFirebaseDataArg('push', value, parent._path, true);
  15655. var now = repoServerTime(parent._repo);
  15656. var name = nextPushId(now);
  15657. // push() returns a ThennableReference whose promise is fulfilled with a
  15658. // regular Reference. We use child() to create handles to two different
  15659. // references. The first is turned into a ThennableReference below by adding
  15660. // then() and catch() methods and is used as the return value of push(). The
  15661. // second remains a regular Reference and is used as the fulfilled value of
  15662. // the first ThennableReference.
  15663. var thennablePushRef = child(parent, name);
  15664. var pushRef = child(parent, name);
  15665. var promise;
  15666. if (value != null) {
  15667. promise = set(pushRef, value).then(function () { return pushRef; });
  15668. }
  15669. else {
  15670. promise = Promise.resolve(pushRef);
  15671. }
  15672. thennablePushRef.then = promise.then.bind(promise);
  15673. thennablePushRef.catch = promise.then.bind(promise, undefined);
  15674. return thennablePushRef;
  15675. }
  15676. /**
  15677. * Removes the data at this Database location.
  15678. *
  15679. * Any data at child locations will also be deleted.
  15680. *
  15681. * The effect of the remove will be visible immediately and the corresponding
  15682. * event 'value' will be triggered. Synchronization of the remove to the
  15683. * Firebase servers will also be started, and the returned Promise will resolve
  15684. * when complete. If provided, the onComplete callback will be called
  15685. * asynchronously after synchronization has finished.
  15686. *
  15687. * @param ref - The location to remove.
  15688. * @returns Resolves when remove on server is complete.
  15689. */
  15690. function remove(ref) {
  15691. validateWritablePath('remove', ref._path);
  15692. return set(ref, null);
  15693. }
  15694. /**
  15695. * Writes data to this Database location.
  15696. *
  15697. * This will overwrite any data at this location and all child locations.
  15698. *
  15699. * The effect of the write will be visible immediately, and the corresponding
  15700. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  15701. * the data to the Firebase servers will also be started, and the returned
  15702. * Promise will resolve when complete. If provided, the `onComplete` callback
  15703. * will be called asynchronously after synchronization has finished.
  15704. *
  15705. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  15706. * all data at this location and all child locations will be deleted.
  15707. *
  15708. * `set()` will remove any priority stored at this location, so if priority is
  15709. * meant to be preserved, you need to use `setWithPriority()` instead.
  15710. *
  15711. * Note that modifying data with `set()` will cancel any pending transactions
  15712. * at that location, so extreme care should be taken if mixing `set()` and
  15713. * `transaction()` to modify the same data.
  15714. *
  15715. * A single `set()` will generate a single "value" event at the location where
  15716. * the `set()` was performed.
  15717. *
  15718. * @param ref - The location to write to.
  15719. * @param value - The value to be written (string, number, boolean, object,
  15720. * array, or null).
  15721. * @returns Resolves when write to server is complete.
  15722. */
  15723. function set(ref, value) {
  15724. ref = util.getModularInstance(ref);
  15725. validateWritablePath('set', ref._path);
  15726. validateFirebaseDataArg('set', value, ref._path, false);
  15727. var deferred = new util.Deferred();
  15728. repoSetWithPriority(ref._repo, ref._path, value,
  15729. /*priority=*/ null, deferred.wrapCallback(function () { }));
  15730. return deferred.promise;
  15731. }
  15732. /**
  15733. * Sets a priority for the data at this Database location.
  15734. *
  15735. * Applications need not use priority but can order collections by
  15736. * ordinary properties (see
  15737. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  15738. * ).
  15739. *
  15740. * @param ref - The location to write to.
  15741. * @param priority - The priority to be written (string, number, or null).
  15742. * @returns Resolves when write to server is complete.
  15743. */
  15744. function setPriority(ref, priority) {
  15745. ref = util.getModularInstance(ref);
  15746. validateWritablePath('setPriority', ref._path);
  15747. validatePriority('setPriority', priority, false);
  15748. var deferred = new util.Deferred();
  15749. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  15750. return deferred.promise;
  15751. }
  15752. /**
  15753. * Writes data the Database location. Like `set()` but also specifies the
  15754. * priority for that data.
  15755. *
  15756. * Applications need not use priority but can order collections by
  15757. * ordinary properties (see
  15758. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  15759. * ).
  15760. *
  15761. * @param ref - The location to write to.
  15762. * @param value - The value to be written (string, number, boolean, object,
  15763. * array, or null).
  15764. * @param priority - The priority to be written (string, number, or null).
  15765. * @returns Resolves when write to server is complete.
  15766. */
  15767. function setWithPriority(ref, value, priority) {
  15768. validateWritablePath('setWithPriority', ref._path);
  15769. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  15770. validatePriority('setWithPriority', priority, false);
  15771. if (ref.key === '.length' || ref.key === '.keys') {
  15772. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  15773. }
  15774. var deferred = new util.Deferred();
  15775. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  15776. return deferred.promise;
  15777. }
  15778. /**
  15779. * Writes multiple values to the Database at once.
  15780. *
  15781. * The `values` argument contains multiple property-value pairs that will be
  15782. * written to the Database together. Each child property can either be a simple
  15783. * property (for example, "name") or a relative path (for example,
  15784. * "name/first") from the current location to the data to update.
  15785. *
  15786. * As opposed to the `set()` method, `update()` can be use to selectively update
  15787. * only the referenced properties at the current location (instead of replacing
  15788. * all the child properties at the current location).
  15789. *
  15790. * The effect of the write will be visible immediately, and the corresponding
  15791. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  15792. * the data to the Firebase servers will also be started, and the returned
  15793. * Promise will resolve when complete. If provided, the `onComplete` callback
  15794. * will be called asynchronously after synchronization has finished.
  15795. *
  15796. * A single `update()` will generate a single "value" event at the location
  15797. * where the `update()` was performed, regardless of how many children were
  15798. * modified.
  15799. *
  15800. * Note that modifying data with `update()` will cancel any pending
  15801. * transactions at that location, so extreme care should be taken if mixing
  15802. * `update()` and `transaction()` to modify the same data.
  15803. *
  15804. * Passing `null` to `update()` will remove the data at this location.
  15805. *
  15806. * See
  15807. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  15808. *
  15809. * @param ref - The location to write to.
  15810. * @param values - Object containing multiple values.
  15811. * @returns Resolves when update on server is complete.
  15812. */
  15813. function update(ref, values) {
  15814. validateFirebaseMergeDataArg('update', values, ref._path, false);
  15815. var deferred = new util.Deferred();
  15816. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  15817. return deferred.promise;
  15818. }
  15819. /**
  15820. * Gets the most up-to-date result for this query.
  15821. *
  15822. * @param query - The query to run.
  15823. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  15824. * available, or rejects if the client is unable to return a value (e.g., if the
  15825. * server is unreachable and there is nothing cached).
  15826. */
  15827. function get(query) {
  15828. query = util.getModularInstance(query);
  15829. var callbackContext = new CallbackContext(function () { });
  15830. var container = new ValueEventRegistration(callbackContext);
  15831. return repoGetValue(query._repo, query, container).then(function (node) {
  15832. return new DataSnapshot$1(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  15833. });
  15834. }
  15835. /**
  15836. * Represents registration for 'value' events.
  15837. */
  15838. var ValueEventRegistration = /** @class */ (function () {
  15839. function ValueEventRegistration(callbackContext) {
  15840. this.callbackContext = callbackContext;
  15841. }
  15842. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  15843. return eventType === 'value';
  15844. };
  15845. ValueEventRegistration.prototype.createEvent = function (change, query) {
  15846. var index = query._queryParams.getIndex();
  15847. return new DataEvent('value', this, new DataSnapshot$1(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  15848. };
  15849. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  15850. var _this = this;
  15851. if (eventData.getEventType() === 'cancel') {
  15852. return function () {
  15853. return _this.callbackContext.onCancel(eventData.error);
  15854. };
  15855. }
  15856. else {
  15857. return function () {
  15858. return _this.callbackContext.onValue(eventData.snapshot, null);
  15859. };
  15860. }
  15861. };
  15862. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  15863. if (this.callbackContext.hasCancelCallback) {
  15864. return new CancelEvent(this, error, path);
  15865. }
  15866. else {
  15867. return null;
  15868. }
  15869. };
  15870. ValueEventRegistration.prototype.matches = function (other) {
  15871. if (!(other instanceof ValueEventRegistration)) {
  15872. return false;
  15873. }
  15874. else if (!other.callbackContext || !this.callbackContext) {
  15875. // If no callback specified, we consider it to match any callback.
  15876. return true;
  15877. }
  15878. else {
  15879. return other.callbackContext.matches(this.callbackContext);
  15880. }
  15881. };
  15882. ValueEventRegistration.prototype.hasAnyCallback = function () {
  15883. return this.callbackContext !== null;
  15884. };
  15885. return ValueEventRegistration;
  15886. }());
  15887. /**
  15888. * Represents the registration of a child_x event.
  15889. */
  15890. var ChildEventRegistration = /** @class */ (function () {
  15891. function ChildEventRegistration(eventType, callbackContext) {
  15892. this.eventType = eventType;
  15893. this.callbackContext = callbackContext;
  15894. }
  15895. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  15896. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  15897. eventToCheck =
  15898. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  15899. return this.eventType === eventToCheck;
  15900. };
  15901. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  15902. if (this.callbackContext.hasCancelCallback) {
  15903. return new CancelEvent(this, error, path);
  15904. }
  15905. else {
  15906. return null;
  15907. }
  15908. };
  15909. ChildEventRegistration.prototype.createEvent = function (change, query) {
  15910. util.assert(change.childName != null, 'Child events should have a childName.');
  15911. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  15912. var index = query._queryParams.getIndex();
  15913. return new DataEvent(change.type, this, new DataSnapshot$1(change.snapshotNode, childRef, index), change.prevName);
  15914. };
  15915. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  15916. var _this = this;
  15917. if (eventData.getEventType() === 'cancel') {
  15918. return function () {
  15919. return _this.callbackContext.onCancel(eventData.error);
  15920. };
  15921. }
  15922. else {
  15923. return function () {
  15924. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  15925. };
  15926. }
  15927. };
  15928. ChildEventRegistration.prototype.matches = function (other) {
  15929. if (other instanceof ChildEventRegistration) {
  15930. return (this.eventType === other.eventType &&
  15931. (!this.callbackContext ||
  15932. !other.callbackContext ||
  15933. this.callbackContext.matches(other.callbackContext)));
  15934. }
  15935. return false;
  15936. };
  15937. ChildEventRegistration.prototype.hasAnyCallback = function () {
  15938. return !!this.callbackContext;
  15939. };
  15940. return ChildEventRegistration;
  15941. }());
  15942. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  15943. var cancelCallback;
  15944. if (typeof cancelCallbackOrListenOptions === 'object') {
  15945. cancelCallback = undefined;
  15946. options = cancelCallbackOrListenOptions;
  15947. }
  15948. if (typeof cancelCallbackOrListenOptions === 'function') {
  15949. cancelCallback = cancelCallbackOrListenOptions;
  15950. }
  15951. if (options && options.onlyOnce) {
  15952. var userCallback_1 = callback;
  15953. var onceCallback = function (dataSnapshot, previousChildName) {
  15954. repoRemoveEventCallbackForQuery(query._repo, query, container);
  15955. userCallback_1(dataSnapshot, previousChildName);
  15956. };
  15957. onceCallback.userCallback = callback.userCallback;
  15958. onceCallback.context = callback.context;
  15959. callback = onceCallback;
  15960. }
  15961. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  15962. var container = eventType === 'value'
  15963. ? new ValueEventRegistration(callbackContext)
  15964. : new ChildEventRegistration(eventType, callbackContext);
  15965. repoAddEventCallbackForQuery(query._repo, query, container);
  15966. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  15967. }
  15968. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  15969. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  15970. }
  15971. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  15972. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  15973. }
  15974. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  15975. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  15976. }
  15977. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  15978. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  15979. }
  15980. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  15981. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  15982. }
  15983. /**
  15984. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  15985. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  15986. * the respective `on*` callbacks.
  15987. *
  15988. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  15989. * will not automatically remove listeners registered on child nodes, `off()`
  15990. * must also be called on any child listeners to remove the callback.
  15991. *
  15992. * If a callback is not specified, all callbacks for the specified eventType
  15993. * will be removed. Similarly, if no eventType is specified, all callbacks
  15994. * for the `Reference` will be removed.
  15995. *
  15996. * Individual listeners can also be removed by invoking their unsubscribe
  15997. * callbacks.
  15998. *
  15999. * @param query - The query that the listener was registered with.
  16000. * @param eventType - One of the following strings: "value", "child_added",
  16001. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  16002. * for the `Reference` will be removed.
  16003. * @param callback - The callback function that was passed to `on()` or
  16004. * `undefined` to remove all callbacks.
  16005. */
  16006. function off(query, eventType, callback) {
  16007. var container = null;
  16008. var expCallback = callback ? new CallbackContext(callback) : null;
  16009. if (eventType === 'value') {
  16010. container = new ValueEventRegistration(expCallback);
  16011. }
  16012. else if (eventType) {
  16013. container = new ChildEventRegistration(eventType, expCallback);
  16014. }
  16015. repoRemoveEventCallbackForQuery(query._repo, query, container);
  16016. }
  16017. /**
  16018. * A `QueryConstraint` is used to narrow the set of documents returned by a
  16019. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  16020. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  16021. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  16022. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  16023. * {@link orderByValue} or {@link equalTo} and
  16024. * can then be passed to {@link query} to create a new query instance that
  16025. * also contains this `QueryConstraint`.
  16026. */
  16027. var QueryConstraint = /** @class */ (function () {
  16028. function QueryConstraint() {
  16029. }
  16030. return QueryConstraint;
  16031. }());
  16032. var QueryEndAtConstraint = /** @class */ (function (_super) {
  16033. tslib.__extends(QueryEndAtConstraint, _super);
  16034. function QueryEndAtConstraint(_value, _key) {
  16035. var _this = _super.call(this) || this;
  16036. _this._value = _value;
  16037. _this._key = _key;
  16038. return _this;
  16039. }
  16040. QueryEndAtConstraint.prototype._apply = function (query) {
  16041. validateFirebaseDataArg('endAt', this._value, query._path, true);
  16042. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  16043. validateLimit(newParams);
  16044. validateQueryEndpoints(newParams);
  16045. if (query._queryParams.hasEnd()) {
  16046. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  16047. 'endBefore or equalTo).');
  16048. }
  16049. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  16050. };
  16051. return QueryEndAtConstraint;
  16052. }(QueryConstraint));
  16053. /**
  16054. * Creates a `QueryConstraint` with the specified ending point.
  16055. *
  16056. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16057. * allows you to choose arbitrary starting and ending points for your queries.
  16058. *
  16059. * The ending point is inclusive, so children with exactly the specified value
  16060. * will be included in the query. The optional key argument can be used to
  16061. * further limit the range of the query. If it is specified, then children that
  16062. * have exactly the specified value must also have a key name less than or equal
  16063. * to the specified key.
  16064. *
  16065. * You can read more about `endAt()` in
  16066. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16067. *
  16068. * @param value - The value to end at. The argument type depends on which
  16069. * `orderBy*()` function was used in this query. Specify a value that matches
  16070. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16071. * value must be a string.
  16072. * @param key - The child key to end at, among the children with the previously
  16073. * specified priority. This argument is only allowed if ordering by child,
  16074. * value, or priority.
  16075. */
  16076. function endAt(value, key) {
  16077. validateKey('endAt', 'key', key, true);
  16078. return new QueryEndAtConstraint(value, key);
  16079. }
  16080. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  16081. tslib.__extends(QueryEndBeforeConstraint, _super);
  16082. function QueryEndBeforeConstraint(_value, _key) {
  16083. var _this = _super.call(this) || this;
  16084. _this._value = _value;
  16085. _this._key = _key;
  16086. return _this;
  16087. }
  16088. QueryEndBeforeConstraint.prototype._apply = function (query) {
  16089. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  16090. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  16091. validateLimit(newParams);
  16092. validateQueryEndpoints(newParams);
  16093. if (query._queryParams.hasEnd()) {
  16094. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  16095. 'endBefore or equalTo).');
  16096. }
  16097. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  16098. };
  16099. return QueryEndBeforeConstraint;
  16100. }(QueryConstraint));
  16101. /**
  16102. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  16103. *
  16104. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16105. * allows you to choose arbitrary starting and ending points for your queries.
  16106. *
  16107. * The ending point is exclusive. If only a value is provided, children
  16108. * with a value less than the specified value will be included in the query.
  16109. * If a key is specified, then children must have a value less than or equal
  16110. * to the specified value and a key name less than the specified key.
  16111. *
  16112. * @param value - The value to end before. The argument type depends on which
  16113. * `orderBy*()` function was used in this query. Specify a value that matches
  16114. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16115. * value must be a string.
  16116. * @param key - The child key to end before, among the children with the
  16117. * previously specified priority. This argument is only allowed if ordering by
  16118. * child, value, or priority.
  16119. */
  16120. function endBefore(value, key) {
  16121. validateKey('endBefore', 'key', key, true);
  16122. return new QueryEndBeforeConstraint(value, key);
  16123. }
  16124. var QueryStartAtConstraint = /** @class */ (function (_super) {
  16125. tslib.__extends(QueryStartAtConstraint, _super);
  16126. function QueryStartAtConstraint(_value, _key) {
  16127. var _this = _super.call(this) || this;
  16128. _this._value = _value;
  16129. _this._key = _key;
  16130. return _this;
  16131. }
  16132. QueryStartAtConstraint.prototype._apply = function (query) {
  16133. validateFirebaseDataArg('startAt', this._value, query._path, true);
  16134. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  16135. validateLimit(newParams);
  16136. validateQueryEndpoints(newParams);
  16137. if (query._queryParams.hasStart()) {
  16138. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  16139. 'startBefore or equalTo).');
  16140. }
  16141. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  16142. };
  16143. return QueryStartAtConstraint;
  16144. }(QueryConstraint));
  16145. /**
  16146. * Creates a `QueryConstraint` with the specified starting point.
  16147. *
  16148. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16149. * allows you to choose arbitrary starting and ending points for your queries.
  16150. *
  16151. * The starting point is inclusive, so children with exactly the specified value
  16152. * will be included in the query. The optional key argument can be used to
  16153. * further limit the range of the query. If it is specified, then children that
  16154. * have exactly the specified value must also have a key name greater than or
  16155. * equal to the specified key.
  16156. *
  16157. * You can read more about `startAt()` in
  16158. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16159. *
  16160. * @param value - The value to start at. The argument type depends on which
  16161. * `orderBy*()` function was used in this query. Specify a value that matches
  16162. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16163. * value must be a string.
  16164. * @param key - The child key to start at. This argument is only allowed if
  16165. * ordering by child, value, or priority.
  16166. */
  16167. function startAt(value, key) {
  16168. if (value === void 0) { value = null; }
  16169. validateKey('startAt', 'key', key, true);
  16170. return new QueryStartAtConstraint(value, key);
  16171. }
  16172. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  16173. tslib.__extends(QueryStartAfterConstraint, _super);
  16174. function QueryStartAfterConstraint(_value, _key) {
  16175. var _this = _super.call(this) || this;
  16176. _this._value = _value;
  16177. _this._key = _key;
  16178. return _this;
  16179. }
  16180. QueryStartAfterConstraint.prototype._apply = function (query) {
  16181. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  16182. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  16183. validateLimit(newParams);
  16184. validateQueryEndpoints(newParams);
  16185. if (query._queryParams.hasStart()) {
  16186. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  16187. 'startAfter, or equalTo).');
  16188. }
  16189. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  16190. };
  16191. return QueryStartAfterConstraint;
  16192. }(QueryConstraint));
  16193. /**
  16194. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  16195. *
  16196. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16197. * allows you to choose arbitrary starting and ending points for your queries.
  16198. *
  16199. * The starting point is exclusive. If only a value is provided, children
  16200. * with a value greater than the specified value will be included in the query.
  16201. * If a key is specified, then children must have a value greater than or equal
  16202. * to the specified value and a a key name greater than the specified key.
  16203. *
  16204. * @param value - The value to start after. The argument type depends on which
  16205. * `orderBy*()` function was used in this query. Specify a value that matches
  16206. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16207. * value must be a string.
  16208. * @param key - The child key to start after. This argument is only allowed if
  16209. * ordering by child, value, or priority.
  16210. */
  16211. function startAfter(value, key) {
  16212. validateKey('startAfter', 'key', key, true);
  16213. return new QueryStartAfterConstraint(value, key);
  16214. }
  16215. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  16216. tslib.__extends(QueryLimitToFirstConstraint, _super);
  16217. function QueryLimitToFirstConstraint(_limit) {
  16218. var _this = _super.call(this) || this;
  16219. _this._limit = _limit;
  16220. return _this;
  16221. }
  16222. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  16223. if (query._queryParams.hasLimit()) {
  16224. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  16225. 'or limitToLast).');
  16226. }
  16227. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  16228. };
  16229. return QueryLimitToFirstConstraint;
  16230. }(QueryConstraint));
  16231. /**
  16232. * Creates a new `QueryConstraint` that if limited to the first specific number
  16233. * of children.
  16234. *
  16235. * The `limitToFirst()` method is used to set a maximum number of children to be
  16236. * synced for a given callback. If we set a limit of 100, we will initially only
  16237. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  16238. * stored in our Database, a `child_added` event will fire for each message.
  16239. * However, if we have over 100 messages, we will only receive a `child_added`
  16240. * event for the first 100 ordered messages. As items change, we will receive
  16241. * `child_removed` events for each item that drops out of the active list so
  16242. * that the total number stays at 100.
  16243. *
  16244. * You can read more about `limitToFirst()` in
  16245. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16246. *
  16247. * @param limit - The maximum number of nodes to include in this query.
  16248. */
  16249. function limitToFirst(limit) {
  16250. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  16251. throw new Error('limitToFirst: First argument must be a positive integer.');
  16252. }
  16253. return new QueryLimitToFirstConstraint(limit);
  16254. }
  16255. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  16256. tslib.__extends(QueryLimitToLastConstraint, _super);
  16257. function QueryLimitToLastConstraint(_limit) {
  16258. var _this = _super.call(this) || this;
  16259. _this._limit = _limit;
  16260. return _this;
  16261. }
  16262. QueryLimitToLastConstraint.prototype._apply = function (query) {
  16263. if (query._queryParams.hasLimit()) {
  16264. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  16265. 'or limitToLast).');
  16266. }
  16267. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  16268. };
  16269. return QueryLimitToLastConstraint;
  16270. }(QueryConstraint));
  16271. /**
  16272. * Creates a new `QueryConstraint` that is limited to return only the last
  16273. * specified number of children.
  16274. *
  16275. * The `limitToLast()` method is used to set a maximum number of children to be
  16276. * synced for a given callback. If we set a limit of 100, we will initially only
  16277. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  16278. * stored in our Database, a `child_added` event will fire for each message.
  16279. * However, if we have over 100 messages, we will only receive a `child_added`
  16280. * event for the last 100 ordered messages. As items change, we will receive
  16281. * `child_removed` events for each item that drops out of the active list so
  16282. * that the total number stays at 100.
  16283. *
  16284. * You can read more about `limitToLast()` in
  16285. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16286. *
  16287. * @param limit - The maximum number of nodes to include in this query.
  16288. */
  16289. function limitToLast(limit) {
  16290. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  16291. throw new Error('limitToLast: First argument must be a positive integer.');
  16292. }
  16293. return new QueryLimitToLastConstraint(limit);
  16294. }
  16295. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  16296. tslib.__extends(QueryOrderByChildConstraint, _super);
  16297. function QueryOrderByChildConstraint(_path) {
  16298. var _this = _super.call(this) || this;
  16299. _this._path = _path;
  16300. return _this;
  16301. }
  16302. QueryOrderByChildConstraint.prototype._apply = function (query) {
  16303. validateNoPreviousOrderByCall(query, 'orderByChild');
  16304. var parsedPath = new Path(this._path);
  16305. if (pathIsEmpty(parsedPath)) {
  16306. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  16307. }
  16308. var index = new PathIndex(parsedPath);
  16309. var newParams = queryParamsOrderBy(query._queryParams, index);
  16310. validateQueryEndpoints(newParams);
  16311. return new QueryImpl(query._repo, query._path, newParams,
  16312. /*orderByCalled=*/ true);
  16313. };
  16314. return QueryOrderByChildConstraint;
  16315. }(QueryConstraint));
  16316. /**
  16317. * Creates a new `QueryConstraint` that orders by the specified child key.
  16318. *
  16319. * Queries can only order by one key at a time. Calling `orderByChild()`
  16320. * multiple times on the same query is an error.
  16321. *
  16322. * Firebase queries allow you to order your data by any child key on the fly.
  16323. * However, if you know in advance what your indexes will be, you can define
  16324. * them via the .indexOn rule in your Security Rules for better performance. See
  16325. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  16326. * rule for more information.
  16327. *
  16328. * You can read more about `orderByChild()` in
  16329. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  16330. *
  16331. * @param path - The path to order by.
  16332. */
  16333. function orderByChild(path) {
  16334. if (path === '$key') {
  16335. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  16336. }
  16337. else if (path === '$priority') {
  16338. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  16339. }
  16340. else if (path === '$value') {
  16341. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  16342. }
  16343. validatePathString('orderByChild', 'path', path, false);
  16344. return new QueryOrderByChildConstraint(path);
  16345. }
  16346. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  16347. tslib.__extends(QueryOrderByKeyConstraint, _super);
  16348. function QueryOrderByKeyConstraint() {
  16349. return _super !== null && _super.apply(this, arguments) || this;
  16350. }
  16351. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  16352. validateNoPreviousOrderByCall(query, 'orderByKey');
  16353. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  16354. validateQueryEndpoints(newParams);
  16355. return new QueryImpl(query._repo, query._path, newParams,
  16356. /*orderByCalled=*/ true);
  16357. };
  16358. return QueryOrderByKeyConstraint;
  16359. }(QueryConstraint));
  16360. /**
  16361. * Creates a new `QueryConstraint` that orders by the key.
  16362. *
  16363. * Sorts the results of a query by their (ascending) key values.
  16364. *
  16365. * You can read more about `orderByKey()` in
  16366. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  16367. */
  16368. function orderByKey() {
  16369. return new QueryOrderByKeyConstraint();
  16370. }
  16371. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  16372. tslib.__extends(QueryOrderByPriorityConstraint, _super);
  16373. function QueryOrderByPriorityConstraint() {
  16374. return _super !== null && _super.apply(this, arguments) || this;
  16375. }
  16376. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  16377. validateNoPreviousOrderByCall(query, 'orderByPriority');
  16378. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  16379. validateQueryEndpoints(newParams);
  16380. return new QueryImpl(query._repo, query._path, newParams,
  16381. /*orderByCalled=*/ true);
  16382. };
  16383. return QueryOrderByPriorityConstraint;
  16384. }(QueryConstraint));
  16385. /**
  16386. * Creates a new `QueryConstraint` that orders by priority.
  16387. *
  16388. * Applications need not use priority but can order collections by
  16389. * ordinary properties (see
  16390. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  16391. * for alternatives to priority.
  16392. */
  16393. function orderByPriority() {
  16394. return new QueryOrderByPriorityConstraint();
  16395. }
  16396. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  16397. tslib.__extends(QueryOrderByValueConstraint, _super);
  16398. function QueryOrderByValueConstraint() {
  16399. return _super !== null && _super.apply(this, arguments) || this;
  16400. }
  16401. QueryOrderByValueConstraint.prototype._apply = function (query) {
  16402. validateNoPreviousOrderByCall(query, 'orderByValue');
  16403. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  16404. validateQueryEndpoints(newParams);
  16405. return new QueryImpl(query._repo, query._path, newParams,
  16406. /*orderByCalled=*/ true);
  16407. };
  16408. return QueryOrderByValueConstraint;
  16409. }(QueryConstraint));
  16410. /**
  16411. * Creates a new `QueryConstraint` that orders by value.
  16412. *
  16413. * If the children of a query are all scalar values (string, number, or
  16414. * boolean), you can order the results by their (ascending) values.
  16415. *
  16416. * You can read more about `orderByValue()` in
  16417. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  16418. */
  16419. function orderByValue() {
  16420. return new QueryOrderByValueConstraint();
  16421. }
  16422. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  16423. tslib.__extends(QueryEqualToValueConstraint, _super);
  16424. function QueryEqualToValueConstraint(_value, _key) {
  16425. var _this = _super.call(this) || this;
  16426. _this._value = _value;
  16427. _this._key = _key;
  16428. return _this;
  16429. }
  16430. QueryEqualToValueConstraint.prototype._apply = function (query) {
  16431. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  16432. if (query._queryParams.hasStart()) {
  16433. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  16434. 'equalTo).');
  16435. }
  16436. if (query._queryParams.hasEnd()) {
  16437. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  16438. 'equalTo).');
  16439. }
  16440. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  16441. };
  16442. return QueryEqualToValueConstraint;
  16443. }(QueryConstraint));
  16444. /**
  16445. * Creates a `QueryConstraint` that includes children that match the specified
  16446. * value.
  16447. *
  16448. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  16449. * allows you to choose arbitrary starting and ending points for your queries.
  16450. *
  16451. * The optional key argument can be used to further limit the range of the
  16452. * query. If it is specified, then children that have exactly the specified
  16453. * value must also have exactly the specified key as their key name. This can be
  16454. * used to filter result sets with many matches for the same value.
  16455. *
  16456. * You can read more about `equalTo()` in
  16457. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  16458. *
  16459. * @param value - The value to match for. The argument type depends on which
  16460. * `orderBy*()` function was used in this query. Specify a value that matches
  16461. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  16462. * value must be a string.
  16463. * @param key - The child key to start at, among the children with the
  16464. * previously specified priority. This argument is only allowed if ordering by
  16465. * child, value, or priority.
  16466. */
  16467. function equalTo(value, key) {
  16468. validateKey('equalTo', 'key', key, true);
  16469. return new QueryEqualToValueConstraint(value, key);
  16470. }
  16471. /**
  16472. * Creates a new immutable instance of `Query` that is extended to also include
  16473. * additional query constraints.
  16474. *
  16475. * @param query - The Query instance to use as a base for the new constraints.
  16476. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  16477. * @throws if any of the provided query constraints cannot be combined with the
  16478. * existing or new constraints.
  16479. */
  16480. function query(query) {
  16481. var e_1, _a;
  16482. var queryConstraints = [];
  16483. for (var _i = 1; _i < arguments.length; _i++) {
  16484. queryConstraints[_i - 1] = arguments[_i];
  16485. }
  16486. var queryImpl = util.getModularInstance(query);
  16487. try {
  16488. for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  16489. var constraint = queryConstraints_1_1.value;
  16490. queryImpl = constraint._apply(queryImpl);
  16491. }
  16492. }
  16493. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  16494. finally {
  16495. try {
  16496. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  16497. }
  16498. finally { if (e_1) throw e_1.error; }
  16499. }
  16500. return queryImpl;
  16501. }
  16502. /**
  16503. * Define reference constructor in various modules
  16504. *
  16505. * We are doing this here to avoid several circular
  16506. * dependency issues
  16507. */
  16508. syncPointSetReferenceConstructor(ReferenceImpl);
  16509. syncTreeSetReferenceConstructor(ReferenceImpl);
  16510. /**
  16511. * This variable is also defined in the firebase Node.js Admin SDK. Before
  16512. * modifying this definition, consult the definition in:
  16513. *
  16514. * https://github.com/firebase/firebase-admin-node
  16515. *
  16516. * and make sure the two are consistent.
  16517. */
  16518. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  16519. /**
  16520. * Creates and caches `Repo` instances.
  16521. */
  16522. var repos = {};
  16523. /**
  16524. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  16525. */
  16526. var useRestClient = false;
  16527. /**
  16528. * Update an existing `Repo` in place to point to a new host/port.
  16529. */
  16530. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  16531. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  16532. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  16533. if (tokenProvider) {
  16534. repo.authTokenProvider_ = tokenProvider;
  16535. }
  16536. }
  16537. /**
  16538. * This function should only ever be called to CREATE a new database instance.
  16539. * @internal
  16540. */
  16541. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  16542. var dbUrl = url || app.options.databaseURL;
  16543. if (dbUrl === undefined) {
  16544. if (!app.options.projectId) {
  16545. fatal("Can't determine Firebase Database URL. Be sure to include " +
  16546. ' a Project ID when calling firebase.initializeApp().');
  16547. }
  16548. log('Using default host for project ', app.options.projectId);
  16549. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  16550. }
  16551. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  16552. var repoInfo = parsedUrl.repoInfo;
  16553. var isEmulator;
  16554. var dbEmulatorHost = undefined;
  16555. if (typeof process !== 'undefined' && process.env) {
  16556. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  16557. }
  16558. if (dbEmulatorHost) {
  16559. isEmulator = true;
  16560. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  16561. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  16562. repoInfo = parsedUrl.repoInfo;
  16563. }
  16564. else {
  16565. isEmulator = !parsedUrl.repoInfo.secure;
  16566. }
  16567. var authTokenProvider = nodeAdmin && isEmulator
  16568. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  16569. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  16570. validateUrl('Invalid Firebase Database URL', parsedUrl);
  16571. if (!pathIsEmpty(parsedUrl.path)) {
  16572. fatal('Database URL must point to the root of a Firebase Database ' +
  16573. '(not including a child path).');
  16574. }
  16575. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  16576. return new Database$1(repo, app);
  16577. }
  16578. /**
  16579. * Remove the repo and make sure it is disconnected.
  16580. *
  16581. */
  16582. function repoManagerDeleteRepo(repo, appName) {
  16583. var appRepos = repos[appName];
  16584. // This should never happen...
  16585. if (!appRepos || appRepos[repo.key] !== repo) {
  16586. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  16587. }
  16588. repoInterrupt(repo);
  16589. delete appRepos[repo.key];
  16590. }
  16591. /**
  16592. * Ensures a repo doesn't already exist and then creates one using the
  16593. * provided app.
  16594. *
  16595. * @param repoInfo - The metadata about the Repo
  16596. * @returns The Repo object for the specified server / repoName.
  16597. */
  16598. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  16599. var appRepos = repos[app.name];
  16600. if (!appRepos) {
  16601. appRepos = {};
  16602. repos[app.name] = appRepos;
  16603. }
  16604. var repo = appRepos[repoInfo.toURLString()];
  16605. if (repo) {
  16606. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  16607. }
  16608. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  16609. appRepos[repoInfo.toURLString()] = repo;
  16610. return repo;
  16611. }
  16612. /**
  16613. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  16614. */
  16615. function repoManagerForceRestClient(forceRestClient) {
  16616. useRestClient = forceRestClient;
  16617. }
  16618. /**
  16619. * Class representing a Firebase Realtime Database.
  16620. */
  16621. var Database$1 = /** @class */ (function () {
  16622. /** @hideconstructor */
  16623. function Database(_repoInternal,
  16624. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  16625. app) {
  16626. this._repoInternal = _repoInternal;
  16627. this.app = app;
  16628. /** Represents a `Database` instance. */
  16629. this['type'] = 'database';
  16630. /** Track if the instance has been used (root or repo accessed) */
  16631. this._instanceStarted = false;
  16632. }
  16633. Object.defineProperty(Database.prototype, "_repo", {
  16634. get: function () {
  16635. if (!this._instanceStarted) {
  16636. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  16637. this._instanceStarted = true;
  16638. }
  16639. return this._repoInternal;
  16640. },
  16641. enumerable: false,
  16642. configurable: true
  16643. });
  16644. Object.defineProperty(Database.prototype, "_root", {
  16645. get: function () {
  16646. if (!this._rootInternal) {
  16647. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  16648. }
  16649. return this._rootInternal;
  16650. },
  16651. enumerable: false,
  16652. configurable: true
  16653. });
  16654. Database.prototype._delete = function () {
  16655. if (this._rootInternal !== null) {
  16656. repoManagerDeleteRepo(this._repo, this.app.name);
  16657. this._repoInternal = null;
  16658. this._rootInternal = null;
  16659. }
  16660. return Promise.resolve();
  16661. };
  16662. Database.prototype._checkNotDeleted = function (apiName) {
  16663. if (this._rootInternal === null) {
  16664. fatal('Cannot call ' + apiName + ' on a deleted database.');
  16665. }
  16666. };
  16667. return Database;
  16668. }());
  16669. function checkTransportInit() {
  16670. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  16671. warn$1('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  16672. }
  16673. }
  16674. /**
  16675. * Force the use of websockets instead of longPolling.
  16676. */
  16677. function forceWebSockets() {
  16678. checkTransportInit();
  16679. BrowserPollConnection.forceDisallow();
  16680. }
  16681. /**
  16682. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  16683. */
  16684. function forceLongPolling() {
  16685. checkTransportInit();
  16686. WebSocketConnection.forceDisallow();
  16687. BrowserPollConnection.forceAllow();
  16688. }
  16689. /**
  16690. * Modify the provided instance to communicate with the Realtime Database
  16691. * emulator.
  16692. *
  16693. * <p>Note: This method must be called before performing any other operation.
  16694. *
  16695. * @param db - The instance to modify.
  16696. * @param host - The emulator host (ex: localhost)
  16697. * @param port - The emulator port (ex: 8080)
  16698. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  16699. */
  16700. function connectDatabaseEmulator(db, host, port, options) {
  16701. if (options === void 0) { options = {}; }
  16702. db = util.getModularInstance(db);
  16703. db._checkNotDeleted('useEmulator');
  16704. if (db._instanceStarted) {
  16705. fatal('Cannot call useEmulator() after instance has already been initialized.');
  16706. }
  16707. var repo = db._repoInternal;
  16708. var tokenProvider = undefined;
  16709. if (repo.repoInfo_.nodeAdmin) {
  16710. if (options.mockUserToken) {
  16711. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  16712. }
  16713. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  16714. }
  16715. else if (options.mockUserToken) {
  16716. var token = typeof options.mockUserToken === 'string'
  16717. ? options.mockUserToken
  16718. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  16719. tokenProvider = new EmulatorTokenProvider(token);
  16720. }
  16721. // Modify the repo to apply emulator settings
  16722. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  16723. }
  16724. /**
  16725. * Disconnects from the server (all Database operations will be completed
  16726. * offline).
  16727. *
  16728. * The client automatically maintains a persistent connection to the Database
  16729. * server, which will remain active indefinitely and reconnect when
  16730. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  16731. * to control the client connection in cases where a persistent connection is
  16732. * undesirable.
  16733. *
  16734. * While offline, the client will no longer receive data updates from the
  16735. * Database. However, all Database operations performed locally will continue to
  16736. * immediately fire events, allowing your application to continue behaving
  16737. * normally. Additionally, each operation performed locally will automatically
  16738. * be queued and retried upon reconnection to the Database server.
  16739. *
  16740. * To reconnect to the Database and begin receiving remote events, see
  16741. * `goOnline()`.
  16742. *
  16743. * @param db - The instance to disconnect.
  16744. */
  16745. function goOffline(db) {
  16746. db = util.getModularInstance(db);
  16747. db._checkNotDeleted('goOffline');
  16748. repoInterrupt(db._repo);
  16749. }
  16750. /**
  16751. * Reconnects to the server and synchronizes the offline Database state
  16752. * with the server state.
  16753. *
  16754. * This method should be used after disabling the active connection with
  16755. * `goOffline()`. Once reconnected, the client will transmit the proper data
  16756. * and fire the appropriate events so that your client "catches up"
  16757. * automatically.
  16758. *
  16759. * @param db - The instance to reconnect.
  16760. */
  16761. function goOnline(db) {
  16762. db = util.getModularInstance(db);
  16763. db._checkNotDeleted('goOnline');
  16764. repoResume(db._repo);
  16765. }
  16766. function enableLogging(logger, persistent) {
  16767. enableLogging$1(logger, persistent);
  16768. }
  16769. /**
  16770. * @license
  16771. * Copyright 2020 Google LLC
  16772. *
  16773. * Licensed under the Apache License, Version 2.0 (the "License");
  16774. * you may not use this file except in compliance with the License.
  16775. * You may obtain a copy of the License at
  16776. *
  16777. * http://www.apache.org/licenses/LICENSE-2.0
  16778. *
  16779. * Unless required by applicable law or agreed to in writing, software
  16780. * distributed under the License is distributed on an "AS IS" BASIS,
  16781. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16782. * See the License for the specific language governing permissions and
  16783. * limitations under the License.
  16784. */
  16785. var SERVER_TIMESTAMP = {
  16786. '.sv': 'timestamp'
  16787. };
  16788. /**
  16789. * Returns a placeholder value for auto-populating the current timestamp (time
  16790. * since the Unix epoch, in milliseconds) as determined by the Firebase
  16791. * servers.
  16792. */
  16793. function serverTimestamp() {
  16794. return SERVER_TIMESTAMP;
  16795. }
  16796. /**
  16797. * Returns a placeholder value that can be used to atomically increment the
  16798. * current database value by the provided delta.
  16799. *
  16800. * @param delta - the amount to modify the current value atomically.
  16801. * @returns A placeholder value for modifying data atomically server-side.
  16802. */
  16803. function increment(delta) {
  16804. return {
  16805. '.sv': {
  16806. 'increment': delta
  16807. }
  16808. };
  16809. }
  16810. /**
  16811. * @license
  16812. * Copyright 2020 Google LLC
  16813. *
  16814. * Licensed under the Apache License, Version 2.0 (the "License");
  16815. * you may not use this file except in compliance with the License.
  16816. * You may obtain a copy of the License at
  16817. *
  16818. * http://www.apache.org/licenses/LICENSE-2.0
  16819. *
  16820. * Unless required by applicable law or agreed to in writing, software
  16821. * distributed under the License is distributed on an "AS IS" BASIS,
  16822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16823. * See the License for the specific language governing permissions and
  16824. * limitations under the License.
  16825. */
  16826. /**
  16827. * A type for the resolve value of {@link runTransaction}.
  16828. */
  16829. var TransactionResult$1 = /** @class */ (function () {
  16830. /** @hideconstructor */
  16831. function TransactionResult(
  16832. /** Whether the transaction was successfully committed. */
  16833. committed,
  16834. /** The resulting data snapshot. */
  16835. snapshot) {
  16836. this.committed = committed;
  16837. this.snapshot = snapshot;
  16838. }
  16839. /** Returns a JSON-serializable representation of this object. */
  16840. TransactionResult.prototype.toJSON = function () {
  16841. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  16842. };
  16843. return TransactionResult;
  16844. }());
  16845. /**
  16846. * Atomically modifies the data at this location.
  16847. *
  16848. * Atomically modify the data at this location. Unlike a normal `set()`, which
  16849. * just overwrites the data regardless of its previous value, `runTransaction()` is
  16850. * used to modify the existing value to a new value, ensuring there are no
  16851. * conflicts with other clients writing to the same location at the same time.
  16852. *
  16853. * To accomplish this, you pass `runTransaction()` an update function which is
  16854. * used to transform the current value into a new value. If another client
  16855. * writes to the location before your new value is successfully written, your
  16856. * update function will be called again with the new current value, and the
  16857. * write will be retried. This will happen repeatedly until your write succeeds
  16858. * without conflict or you abort the transaction by not returning a value from
  16859. * your update function.
  16860. *
  16861. * Note: Modifying data with `set()` will cancel any pending transactions at
  16862. * that location, so extreme care should be taken if mixing `set()` and
  16863. * `runTransaction()` to update the same data.
  16864. *
  16865. * Note: When using transactions with Security and Firebase Rules in place, be
  16866. * aware that a client needs `.read` access in addition to `.write` access in
  16867. * order to perform a transaction. This is because the client-side nature of
  16868. * transactions requires the client to read the data in order to transactionally
  16869. * update it.
  16870. *
  16871. * @param ref - The location to atomically modify.
  16872. * @param transactionUpdate - A developer-supplied function which will be passed
  16873. * the current data stored at this location (as a JavaScript object). The
  16874. * function should return the new value it would like written (as a JavaScript
  16875. * object). If `undefined` is returned (i.e. you return with no arguments) the
  16876. * transaction will be aborted and the data at this location will not be
  16877. * modified.
  16878. * @param options - An options object to configure transactions.
  16879. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  16880. * callback to handle success and failure.
  16881. */
  16882. function runTransaction(ref,
  16883. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16884. transactionUpdate, options) {
  16885. var _a;
  16886. ref = util.getModularInstance(ref);
  16887. validateWritablePath('Reference.transaction', ref._path);
  16888. if (ref.key === '.length' || ref.key === '.keys') {
  16889. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  16890. }
  16891. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  16892. var deferred = new util.Deferred();
  16893. var promiseComplete = function (error, committed, node) {
  16894. var dataSnapshot = null;
  16895. if (error) {
  16896. deferred.reject(error);
  16897. }
  16898. else {
  16899. dataSnapshot = new DataSnapshot$1(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  16900. deferred.resolve(new TransactionResult$1(committed, dataSnapshot));
  16901. }
  16902. };
  16903. // Add a watch to make sure we get server updates.
  16904. var unwatcher = onValue(ref, function () { });
  16905. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  16906. return deferred.promise;
  16907. }
  16908. /**
  16909. * @license
  16910. * Copyright 2017 Google LLC
  16911. *
  16912. * Licensed under the Apache License, Version 2.0 (the "License");
  16913. * you may not use this file except in compliance with the License.
  16914. * You may obtain a copy of the License at
  16915. *
  16916. * http://www.apache.org/licenses/LICENSE-2.0
  16917. *
  16918. * Unless required by applicable law or agreed to in writing, software
  16919. * distributed under the License is distributed on an "AS IS" BASIS,
  16920. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16921. * See the License for the specific language governing permissions and
  16922. * limitations under the License.
  16923. */
  16924. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16925. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  16926. this.sendRequest('q', { p: pathString }, onComplete);
  16927. };
  16928. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16929. PersistentConnection.prototype.echo = function (data, onEcho) {
  16930. this.sendRequest('echo', { d: data }, onEcho);
  16931. };
  16932. /**
  16933. * @internal
  16934. */
  16935. var hijackHash = function (newHash) {
  16936. var oldPut = PersistentConnection.prototype.put;
  16937. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  16938. if (hash !== undefined) {
  16939. hash = newHash();
  16940. }
  16941. oldPut.call(this, pathString, data, onComplete, hash);
  16942. };
  16943. return function () {
  16944. PersistentConnection.prototype.put = oldPut;
  16945. };
  16946. };
  16947. /**
  16948. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  16949. * @internal
  16950. */
  16951. var forceRestClient = function (forceRestClient) {
  16952. repoManagerForceRestClient(forceRestClient);
  16953. };
  16954. /**
  16955. * @license
  16956. * Copyright 2021 Google LLC
  16957. *
  16958. * Licensed under the Apache License, Version 2.0 (the "License");
  16959. * you may not use this file except in compliance with the License.
  16960. * You may obtain a copy of the License at
  16961. *
  16962. * http://www.apache.org/licenses/LICENSE-2.0
  16963. *
  16964. * Unless required by applicable law or agreed to in writing, software
  16965. * distributed under the License is distributed on an "AS IS" BASIS,
  16966. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16967. * See the License for the specific language governing permissions and
  16968. * limitations under the License.
  16969. */
  16970. setWebSocketImpl(Websocket__default["default"].Client);
  16971. index_standalone.DataSnapshot = DataSnapshot$1;
  16972. index_standalone.Database = Database$1;
  16973. var OnDisconnect_1 = index_standalone.OnDisconnect = OnDisconnect$1;
  16974. index_standalone.QueryConstraint = QueryConstraint;
  16975. index_standalone.TransactionResult = TransactionResult$1;
  16976. var _QueryImpl = index_standalone._QueryImpl = QueryImpl;
  16977. var _QueryParams = index_standalone._QueryParams = QueryParams;
  16978. var _ReferenceImpl = index_standalone._ReferenceImpl = ReferenceImpl;
  16979. index_standalone._TEST_ACCESS_forceRestClient = forceRestClient;
  16980. index_standalone._TEST_ACCESS_hijackHash = hijackHash;
  16981. var _repoManagerDatabaseFromApp = index_standalone._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  16982. var _setSDKVersion = index_standalone._setSDKVersion = setSDKVersion;
  16983. var _validatePathString = index_standalone._validatePathString = validatePathString;
  16984. var _validateWritablePath = index_standalone._validateWritablePath = validateWritablePath;
  16985. var child_1 = index_standalone.child = child;
  16986. var connectDatabaseEmulator_1 = index_standalone.connectDatabaseEmulator = connectDatabaseEmulator;
  16987. var enableLogging_1 = index_standalone.enableLogging = enableLogging;
  16988. var endAt_1 = index_standalone.endAt = endAt;
  16989. var endBefore_1 = index_standalone.endBefore = endBefore;
  16990. var equalTo_1 = index_standalone.equalTo = equalTo;
  16991. var forceLongPolling_1 = index_standalone.forceLongPolling = forceLongPolling;
  16992. var forceWebSockets_1 = index_standalone.forceWebSockets = forceWebSockets;
  16993. var get_1 = index_standalone.get = get;
  16994. var goOffline_1 = index_standalone.goOffline = goOffline;
  16995. var goOnline_1 = index_standalone.goOnline = goOnline;
  16996. var increment_1 = index_standalone.increment = increment;
  16997. var limitToFirst_1 = index_standalone.limitToFirst = limitToFirst;
  16998. var limitToLast_1 = index_standalone.limitToLast = limitToLast;
  16999. var off_1 = index_standalone.off = off;
  17000. var onChildAdded_1 = index_standalone.onChildAdded = onChildAdded;
  17001. var onChildChanged_1 = index_standalone.onChildChanged = onChildChanged;
  17002. var onChildMoved_1 = index_standalone.onChildMoved = onChildMoved;
  17003. var onChildRemoved_1 = index_standalone.onChildRemoved = onChildRemoved;
  17004. index_standalone.onDisconnect = onDisconnect;
  17005. var onValue_1 = index_standalone.onValue = onValue;
  17006. var orderByChild_1 = index_standalone.orderByChild = orderByChild;
  17007. var orderByKey_1 = index_standalone.orderByKey = orderByKey;
  17008. var orderByPriority_1 = index_standalone.orderByPriority = orderByPriority;
  17009. var orderByValue_1 = index_standalone.orderByValue = orderByValue;
  17010. var push_1 = index_standalone.push = push;
  17011. var query_1 = index_standalone.query = query;
  17012. var ref_1 = index_standalone.ref = ref;
  17013. var refFromURL_1 = index_standalone.refFromURL = refFromURL;
  17014. var remove_1 = index_standalone.remove = remove;
  17015. var runTransaction_1 = index_standalone.runTransaction = runTransaction;
  17016. var serverTimestamp_1 = index_standalone.serverTimestamp = serverTimestamp;
  17017. var set_1 = index_standalone.set = set;
  17018. var setPriority_1 = index_standalone.setPriority = setPriority;
  17019. var setWithPriority_1 = index_standalone.setWithPriority = setWithPriority;
  17020. var startAfter_1 = index_standalone.startAfter = startAfter;
  17021. var startAt_1 = index_standalone.startAt = startAt;
  17022. var update_1 = index_standalone.update = update;
  17023. /**
  17024. * @license
  17025. * Copyright 2021 Google LLC
  17026. *
  17027. * Licensed under the Apache License, Version 2.0 (the "License");
  17028. * you may not use this file except in compliance with the License.
  17029. * You may obtain a copy of the License at
  17030. *
  17031. * http://www.apache.org/licenses/LICENSE-2.0
  17032. *
  17033. * Unless required by applicable law or agreed to in writing, software
  17034. * distributed under the License is distributed on an "AS IS" BASIS,
  17035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17036. * See the License for the specific language governing permissions and
  17037. * limitations under the License.
  17038. */
  17039. var logClient = new require$$3.Logger('@firebase/database-compat');
  17040. var warn = function (msg) {
  17041. var message = 'FIREBASE WARNING: ' + msg;
  17042. logClient.warn(message);
  17043. };
  17044. /**
  17045. * @license
  17046. * Copyright 2021 Google LLC
  17047. *
  17048. * Licensed under the Apache License, Version 2.0 (the "License");
  17049. * you may not use this file except in compliance with the License.
  17050. * You may obtain a copy of the License at
  17051. *
  17052. * http://www.apache.org/licenses/LICENSE-2.0
  17053. *
  17054. * Unless required by applicable law or agreed to in writing, software
  17055. * distributed under the License is distributed on an "AS IS" BASIS,
  17056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17057. * See the License for the specific language governing permissions and
  17058. * limitations under the License.
  17059. */
  17060. var validateBoolean = function (fnName, argumentName, bool, optional) {
  17061. if (optional && bool === undefined) {
  17062. return;
  17063. }
  17064. if (typeof bool !== 'boolean') {
  17065. throw new Error(require$$1$3.errorPrefix(fnName, argumentName) + 'must be a boolean.');
  17066. }
  17067. };
  17068. var validateEventType = function (fnName, eventType, optional) {
  17069. if (optional && eventType === undefined) {
  17070. return;
  17071. }
  17072. switch (eventType) {
  17073. case 'value':
  17074. case 'child_added':
  17075. case 'child_removed':
  17076. case 'child_changed':
  17077. case 'child_moved':
  17078. break;
  17079. default:
  17080. throw new Error(require$$1$3.errorPrefix(fnName, 'eventType') +
  17081. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  17082. '"child_changed", or "child_moved".');
  17083. }
  17084. };
  17085. /**
  17086. * @license
  17087. * Copyright 2017 Google LLC
  17088. *
  17089. * Licensed under the Apache License, Version 2.0 (the "License");
  17090. * you may not use this file except in compliance with the License.
  17091. * You may obtain a copy of the License at
  17092. *
  17093. * http://www.apache.org/licenses/LICENSE-2.0
  17094. *
  17095. * Unless required by applicable law or agreed to in writing, software
  17096. * distributed under the License is distributed on an "AS IS" BASIS,
  17097. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17098. * See the License for the specific language governing permissions and
  17099. * limitations under the License.
  17100. */
  17101. var OnDisconnect = /** @class */ (function () {
  17102. function OnDisconnect(_delegate) {
  17103. this._delegate = _delegate;
  17104. }
  17105. OnDisconnect.prototype.cancel = function (onComplete) {
  17106. require$$1$3.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);
  17107. require$$1$3.validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);
  17108. var result = this._delegate.cancel();
  17109. if (onComplete) {
  17110. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17111. }
  17112. return result;
  17113. };
  17114. OnDisconnect.prototype.remove = function (onComplete) {
  17115. require$$1$3.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);
  17116. require$$1$3.validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);
  17117. var result = this._delegate.remove();
  17118. if (onComplete) {
  17119. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17120. }
  17121. return result;
  17122. };
  17123. OnDisconnect.prototype.set = function (value, onComplete) {
  17124. require$$1$3.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);
  17125. require$$1$3.validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);
  17126. var result = this._delegate.set(value);
  17127. if (onComplete) {
  17128. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17129. }
  17130. return result;
  17131. };
  17132. OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {
  17133. require$$1$3.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);
  17134. require$$1$3.validateCallback('OnDisconnect.setWithPriority', 'onComplete', onComplete, true);
  17135. var result = this._delegate.setWithPriority(value, priority);
  17136. if (onComplete) {
  17137. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17138. }
  17139. return result;
  17140. };
  17141. OnDisconnect.prototype.update = function (objectToMerge, onComplete) {
  17142. require$$1$3.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);
  17143. if (Array.isArray(objectToMerge)) {
  17144. var newObjectToMerge = {};
  17145. for (var i = 0; i < objectToMerge.length; ++i) {
  17146. newObjectToMerge['' + i] = objectToMerge[i];
  17147. }
  17148. objectToMerge = newObjectToMerge;
  17149. warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +
  17150. 'existing data, or an Object with integer keys if you really do want to only update some of the children.');
  17151. }
  17152. require$$1$3.validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);
  17153. var result = this._delegate.update(objectToMerge);
  17154. if (onComplete) {
  17155. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17156. }
  17157. return result;
  17158. };
  17159. return OnDisconnect;
  17160. }());
  17161. /**
  17162. * @license
  17163. * Copyright 2017 Google LLC
  17164. *
  17165. * Licensed under the Apache License, Version 2.0 (the "License");
  17166. * you may not use this file except in compliance with the License.
  17167. * You may obtain a copy of the License at
  17168. *
  17169. * http://www.apache.org/licenses/LICENSE-2.0
  17170. *
  17171. * Unless required by applicable law or agreed to in writing, software
  17172. * distributed under the License is distributed on an "AS IS" BASIS,
  17173. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17174. * See the License for the specific language governing permissions and
  17175. * limitations under the License.
  17176. */
  17177. var TransactionResult = /** @class */ (function () {
  17178. /**
  17179. * A type for the resolve value of Firebase.transaction.
  17180. */
  17181. function TransactionResult(committed, snapshot) {
  17182. this.committed = committed;
  17183. this.snapshot = snapshot;
  17184. }
  17185. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  17186. // for end-users
  17187. TransactionResult.prototype.toJSON = function () {
  17188. require$$1$3.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);
  17189. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  17190. };
  17191. return TransactionResult;
  17192. }());
  17193. /**
  17194. * @license
  17195. * Copyright 2017 Google LLC
  17196. *
  17197. * Licensed under the Apache License, Version 2.0 (the "License");
  17198. * you may not use this file except in compliance with the License.
  17199. * You may obtain a copy of the License at
  17200. *
  17201. * http://www.apache.org/licenses/LICENSE-2.0
  17202. *
  17203. * Unless required by applicable law or agreed to in writing, software
  17204. * distributed under the License is distributed on an "AS IS" BASIS,
  17205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17206. * See the License for the specific language governing permissions and
  17207. * limitations under the License.
  17208. */
  17209. /**
  17210. * Class representing a firebase data snapshot. It wraps a SnapshotNode and
  17211. * surfaces the public methods (val, forEach, etc.) we want to expose.
  17212. */
  17213. var DataSnapshot = /** @class */ (function () {
  17214. function DataSnapshot(_database, _delegate) {
  17215. this._database = _database;
  17216. this._delegate = _delegate;
  17217. }
  17218. /**
  17219. * Retrieves the snapshot contents as JSON. Returns null if the snapshot is
  17220. * empty.
  17221. *
  17222. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  17223. */
  17224. DataSnapshot.prototype.val = function () {
  17225. require$$1$3.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);
  17226. return this._delegate.val();
  17227. };
  17228. /**
  17229. * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting
  17230. * the entire node contents.
  17231. * @returns JSON representation of the DataSnapshot contents, or null if empty.
  17232. */
  17233. DataSnapshot.prototype.exportVal = function () {
  17234. require$$1$3.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);
  17235. return this._delegate.exportVal();
  17236. };
  17237. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  17238. // for end-users
  17239. DataSnapshot.prototype.toJSON = function () {
  17240. // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content
  17241. require$$1$3.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);
  17242. return this._delegate.toJSON();
  17243. };
  17244. /**
  17245. * Returns whether the snapshot contains a non-null value.
  17246. *
  17247. * @returns Whether the snapshot contains a non-null value, or is empty.
  17248. */
  17249. DataSnapshot.prototype.exists = function () {
  17250. require$$1$3.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);
  17251. return this._delegate.exists();
  17252. };
  17253. /**
  17254. * Returns a DataSnapshot of the specified child node's contents.
  17255. *
  17256. * @param path - Path to a child.
  17257. * @returns DataSnapshot for child node.
  17258. */
  17259. DataSnapshot.prototype.child = function (path) {
  17260. require$$1$3.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);
  17261. // Ensure the childPath is a string (can be a number)
  17262. path = String(path);
  17263. _validatePathString('DataSnapshot.child', 'path', path, false);
  17264. return new DataSnapshot(this._database, this._delegate.child(path));
  17265. };
  17266. /**
  17267. * Returns whether the snapshot contains a child at the specified path.
  17268. *
  17269. * @param path - Path to a child.
  17270. * @returns Whether the child exists.
  17271. */
  17272. DataSnapshot.prototype.hasChild = function (path) {
  17273. require$$1$3.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);
  17274. _validatePathString('DataSnapshot.hasChild', 'path', path, false);
  17275. return this._delegate.hasChild(path);
  17276. };
  17277. /**
  17278. * Returns the priority of the object, or null if no priority was set.
  17279. *
  17280. * @returns The priority.
  17281. */
  17282. DataSnapshot.prototype.getPriority = function () {
  17283. require$$1$3.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);
  17284. return this._delegate.priority;
  17285. };
  17286. /**
  17287. * Iterates through child nodes and calls the specified action for each one.
  17288. *
  17289. * @param action - Callback function to be called
  17290. * for each child.
  17291. * @returns True if forEach was canceled by action returning true for
  17292. * one of the child nodes.
  17293. */
  17294. DataSnapshot.prototype.forEach = function (action) {
  17295. var _this = this;
  17296. require$$1$3.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);
  17297. require$$1$3.validateCallback('DataSnapshot.forEach', 'action', action, false);
  17298. return this._delegate.forEach(function (expDataSnapshot) {
  17299. return action(new DataSnapshot(_this._database, expDataSnapshot));
  17300. });
  17301. };
  17302. /**
  17303. * Returns whether this DataSnapshot has children.
  17304. * @returns True if the DataSnapshot contains 1 or more child nodes.
  17305. */
  17306. DataSnapshot.prototype.hasChildren = function () {
  17307. require$$1$3.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);
  17308. return this._delegate.hasChildren();
  17309. };
  17310. Object.defineProperty(DataSnapshot.prototype, "key", {
  17311. get: function () {
  17312. return this._delegate.key;
  17313. },
  17314. enumerable: false,
  17315. configurable: true
  17316. });
  17317. /**
  17318. * Returns the number of children for this DataSnapshot.
  17319. * @returns The number of children that this DataSnapshot contains.
  17320. */
  17321. DataSnapshot.prototype.numChildren = function () {
  17322. require$$1$3.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);
  17323. return this._delegate.size;
  17324. };
  17325. /**
  17326. * @returns The Firebase reference for the location this snapshot's data came
  17327. * from.
  17328. */
  17329. DataSnapshot.prototype.getRef = function () {
  17330. require$$1$3.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);
  17331. return new Reference(this._database, this._delegate.ref);
  17332. };
  17333. Object.defineProperty(DataSnapshot.prototype, "ref", {
  17334. get: function () {
  17335. return this.getRef();
  17336. },
  17337. enumerable: false,
  17338. configurable: true
  17339. });
  17340. return DataSnapshot;
  17341. }());
  17342. /**
  17343. * A Query represents a filter to be applied to a firebase location. This object purely represents the
  17344. * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.
  17345. *
  17346. * Since every Firebase reference is a query, Firebase inherits from this object.
  17347. */
  17348. var Query = /** @class */ (function () {
  17349. function Query(database, _delegate) {
  17350. this.database = database;
  17351. this._delegate = _delegate;
  17352. }
  17353. Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {
  17354. var _this = this;
  17355. var _a;
  17356. require$$1$3.validateArgCount('Query.on', 2, 4, arguments.length);
  17357. require$$1$3.validateCallback('Query.on', 'callback', callback, false);
  17358. var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);
  17359. var valueCallback = function (expSnapshot, previousChildName) {
  17360. callback.call(ret.context, new DataSnapshot(_this.database, expSnapshot), previousChildName);
  17361. };
  17362. valueCallback.userCallback = callback;
  17363. valueCallback.context = ret.context;
  17364. var cancelCallback = (_a = ret.cancel) === null || _a === void 0 ? void 0 : _a.bind(ret.context);
  17365. switch (eventType) {
  17366. case 'value':
  17367. onValue_1(this._delegate, valueCallback, cancelCallback);
  17368. return callback;
  17369. case 'child_added':
  17370. onChildAdded_1(this._delegate, valueCallback, cancelCallback);
  17371. return callback;
  17372. case 'child_removed':
  17373. onChildRemoved_1(this._delegate, valueCallback, cancelCallback);
  17374. return callback;
  17375. case 'child_changed':
  17376. onChildChanged_1(this._delegate, valueCallback, cancelCallback);
  17377. return callback;
  17378. case 'child_moved':
  17379. onChildMoved_1(this._delegate, valueCallback, cancelCallback);
  17380. return callback;
  17381. default:
  17382. throw new Error(require$$1$3.errorPrefix('Query.on', 'eventType') +
  17383. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  17384. '"child_changed", or "child_moved".');
  17385. }
  17386. };
  17387. Query.prototype.off = function (eventType, callback, context) {
  17388. require$$1$3.validateArgCount('Query.off', 0, 3, arguments.length);
  17389. validateEventType('Query.off', eventType, true);
  17390. require$$1$3.validateCallback('Query.off', 'callback', callback, true);
  17391. require$$1$3.validateContextObject('Query.off', 'context', context, true);
  17392. if (callback) {
  17393. var valueCallback = function () { };
  17394. valueCallback.userCallback = callback;
  17395. valueCallback.context = context;
  17396. off_1(this._delegate, eventType, valueCallback);
  17397. }
  17398. else {
  17399. off_1(this._delegate, eventType);
  17400. }
  17401. };
  17402. /**
  17403. * Get the server-value for this query, or return a cached value if not connected.
  17404. */
  17405. Query.prototype.get = function () {
  17406. var _this = this;
  17407. return get_1(this._delegate).then(function (expSnapshot) {
  17408. return new DataSnapshot(_this.database, expSnapshot);
  17409. });
  17410. };
  17411. /**
  17412. * Attaches a listener, waits for the first event, and then removes the listener
  17413. */
  17414. Query.prototype.once = function (eventType, callback, failureCallbackOrContext, context) {
  17415. var _this = this;
  17416. require$$1$3.validateArgCount('Query.once', 1, 4, arguments.length);
  17417. require$$1$3.validateCallback('Query.once', 'callback', callback, true);
  17418. var ret = Query.getCancelAndContextArgs_('Query.once', failureCallbackOrContext, context);
  17419. var deferred = new require$$1$3.Deferred();
  17420. var valueCallback = function (expSnapshot, previousChildName) {
  17421. var result = new DataSnapshot(_this.database, expSnapshot);
  17422. if (callback) {
  17423. callback.call(ret.context, result, previousChildName);
  17424. }
  17425. deferred.resolve(result);
  17426. };
  17427. valueCallback.userCallback = callback;
  17428. valueCallback.context = ret.context;
  17429. var cancelCallback = function (error) {
  17430. if (ret.cancel) {
  17431. ret.cancel.call(ret.context, error);
  17432. }
  17433. deferred.reject(error);
  17434. };
  17435. switch (eventType) {
  17436. case 'value':
  17437. onValue_1(this._delegate, valueCallback, cancelCallback, {
  17438. onlyOnce: true
  17439. });
  17440. break;
  17441. case 'child_added':
  17442. onChildAdded_1(this._delegate, valueCallback, cancelCallback, {
  17443. onlyOnce: true
  17444. });
  17445. break;
  17446. case 'child_removed':
  17447. onChildRemoved_1(this._delegate, valueCallback, cancelCallback, {
  17448. onlyOnce: true
  17449. });
  17450. break;
  17451. case 'child_changed':
  17452. onChildChanged_1(this._delegate, valueCallback, cancelCallback, {
  17453. onlyOnce: true
  17454. });
  17455. break;
  17456. case 'child_moved':
  17457. onChildMoved_1(this._delegate, valueCallback, cancelCallback, {
  17458. onlyOnce: true
  17459. });
  17460. break;
  17461. default:
  17462. throw new Error(require$$1$3.errorPrefix('Query.once', 'eventType') +
  17463. 'must be a valid event type = "value", "child_added", "child_removed", ' +
  17464. '"child_changed", or "child_moved".');
  17465. }
  17466. return deferred.promise;
  17467. };
  17468. /**
  17469. * Set a limit and anchor it to the start of the window.
  17470. */
  17471. Query.prototype.limitToFirst = function (limit) {
  17472. require$$1$3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);
  17473. return new Query(this.database, query_1(this._delegate, limitToFirst_1(limit)));
  17474. };
  17475. /**
  17476. * Set a limit and anchor it to the end of the window.
  17477. */
  17478. Query.prototype.limitToLast = function (limit) {
  17479. require$$1$3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);
  17480. return new Query(this.database, query_1(this._delegate, limitToLast_1(limit)));
  17481. };
  17482. /**
  17483. * Given a child path, return a new query ordered by the specified grandchild path.
  17484. */
  17485. Query.prototype.orderByChild = function (path) {
  17486. require$$1$3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);
  17487. return new Query(this.database, query_1(this._delegate, orderByChild_1(path)));
  17488. };
  17489. /**
  17490. * Return a new query ordered by the KeyIndex
  17491. */
  17492. Query.prototype.orderByKey = function () {
  17493. require$$1$3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);
  17494. return new Query(this.database, query_1(this._delegate, orderByKey_1()));
  17495. };
  17496. /**
  17497. * Return a new query ordered by the PriorityIndex
  17498. */
  17499. Query.prototype.orderByPriority = function () {
  17500. require$$1$3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);
  17501. return new Query(this.database, query_1(this._delegate, orderByPriority_1()));
  17502. };
  17503. /**
  17504. * Return a new query ordered by the ValueIndex
  17505. */
  17506. Query.prototype.orderByValue = function () {
  17507. require$$1$3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);
  17508. return new Query(this.database, query_1(this._delegate, orderByValue_1()));
  17509. };
  17510. Query.prototype.startAt = function (value, name) {
  17511. if (value === void 0) { value = null; }
  17512. require$$1$3.validateArgCount('Query.startAt', 0, 2, arguments.length);
  17513. return new Query(this.database, query_1(this._delegate, startAt_1(value, name)));
  17514. };
  17515. Query.prototype.startAfter = function (value, name) {
  17516. if (value === void 0) { value = null; }
  17517. require$$1$3.validateArgCount('Query.startAfter', 0, 2, arguments.length);
  17518. return new Query(this.database, query_1(this._delegate, startAfter_1(value, name)));
  17519. };
  17520. Query.prototype.endAt = function (value, name) {
  17521. if (value === void 0) { value = null; }
  17522. require$$1$3.validateArgCount('Query.endAt', 0, 2, arguments.length);
  17523. return new Query(this.database, query_1(this._delegate, endAt_1(value, name)));
  17524. };
  17525. Query.prototype.endBefore = function (value, name) {
  17526. if (value === void 0) { value = null; }
  17527. require$$1$3.validateArgCount('Query.endBefore', 0, 2, arguments.length);
  17528. return new Query(this.database, query_1(this._delegate, endBefore_1(value, name)));
  17529. };
  17530. /**
  17531. * Load the selection of children with exactly the specified value, and, optionally,
  17532. * the specified name.
  17533. */
  17534. Query.prototype.equalTo = function (value, name) {
  17535. require$$1$3.validateArgCount('Query.equalTo', 1, 2, arguments.length);
  17536. return new Query(this.database, query_1(this._delegate, equalTo_1(value, name)));
  17537. };
  17538. /**
  17539. * @returns URL for this location.
  17540. */
  17541. Query.prototype.toString = function () {
  17542. require$$1$3.validateArgCount('Query.toString', 0, 0, arguments.length);
  17543. return this._delegate.toString();
  17544. };
  17545. // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary
  17546. // for end-users.
  17547. Query.prototype.toJSON = function () {
  17548. // An optional spacer argument is unnecessary for a string.
  17549. require$$1$3.validateArgCount('Query.toJSON', 0, 1, arguments.length);
  17550. return this._delegate.toJSON();
  17551. };
  17552. /**
  17553. * Return true if this query and the provided query are equivalent; otherwise, return false.
  17554. */
  17555. Query.prototype.isEqual = function (other) {
  17556. require$$1$3.validateArgCount('Query.isEqual', 1, 1, arguments.length);
  17557. if (!(other instanceof Query)) {
  17558. var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';
  17559. throw new Error(error);
  17560. }
  17561. return this._delegate.isEqual(other._delegate);
  17562. };
  17563. /**
  17564. * Helper used by .on and .once to extract the context and or cancel arguments.
  17565. * @param fnName - The function name (on or once)
  17566. *
  17567. */
  17568. Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {
  17569. var ret = { cancel: undefined, context: undefined };
  17570. if (cancelOrContext && context) {
  17571. ret.cancel = cancelOrContext;
  17572. require$$1$3.validateCallback(fnName, 'cancel', ret.cancel, true);
  17573. ret.context = context;
  17574. require$$1$3.validateContextObject(fnName, 'context', ret.context, true);
  17575. }
  17576. else if (cancelOrContext) {
  17577. // we have either a cancel callback or a context.
  17578. if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {
  17579. // it's a context!
  17580. ret.context = cancelOrContext;
  17581. }
  17582. else if (typeof cancelOrContext === 'function') {
  17583. ret.cancel = cancelOrContext;
  17584. }
  17585. else {
  17586. throw new Error(require$$1$3.errorPrefix(fnName, 'cancelOrContext') +
  17587. ' must either be a cancel callback or a context object.');
  17588. }
  17589. }
  17590. return ret;
  17591. };
  17592. Object.defineProperty(Query.prototype, "ref", {
  17593. get: function () {
  17594. return new Reference(this.database, new _ReferenceImpl(this._delegate._repo, this._delegate._path));
  17595. },
  17596. enumerable: false,
  17597. configurable: true
  17598. });
  17599. return Query;
  17600. }());
  17601. var Reference = /** @class */ (function (_super) {
  17602. require$$2$3.__extends(Reference, _super);
  17603. /**
  17604. * Call options:
  17605. * new Reference(Repo, Path) or
  17606. * new Reference(url: string, string|RepoManager)
  17607. *
  17608. * Externally - this is the firebase.database.Reference type.
  17609. */
  17610. function Reference(database, _delegate) {
  17611. var _this = _super.call(this, database, new _QueryImpl(_delegate._repo, _delegate._path, new _QueryParams(), false)) || this;
  17612. _this.database = database;
  17613. _this._delegate = _delegate;
  17614. return _this;
  17615. }
  17616. /** @returns {?string} */
  17617. Reference.prototype.getKey = function () {
  17618. require$$1$3.validateArgCount('Reference.key', 0, 0, arguments.length);
  17619. return this._delegate.key;
  17620. };
  17621. Reference.prototype.child = function (pathString) {
  17622. require$$1$3.validateArgCount('Reference.child', 1, 1, arguments.length);
  17623. if (typeof pathString === 'number') {
  17624. pathString = String(pathString);
  17625. }
  17626. return new Reference(this.database, child_1(this._delegate, pathString));
  17627. };
  17628. /** @returns {?Reference} */
  17629. Reference.prototype.getParent = function () {
  17630. require$$1$3.validateArgCount('Reference.parent', 0, 0, arguments.length);
  17631. var parent = this._delegate.parent;
  17632. return parent ? new Reference(this.database, parent) : null;
  17633. };
  17634. /** @returns {!Reference} */
  17635. Reference.prototype.getRoot = function () {
  17636. require$$1$3.validateArgCount('Reference.root', 0, 0, arguments.length);
  17637. return new Reference(this.database, this._delegate.root);
  17638. };
  17639. Reference.prototype.set = function (newVal, onComplete) {
  17640. require$$1$3.validateArgCount('Reference.set', 1, 2, arguments.length);
  17641. require$$1$3.validateCallback('Reference.set', 'onComplete', onComplete, true);
  17642. var result = set_1(this._delegate, newVal);
  17643. if (onComplete) {
  17644. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17645. }
  17646. return result;
  17647. };
  17648. Reference.prototype.update = function (values, onComplete) {
  17649. require$$1$3.validateArgCount('Reference.update', 1, 2, arguments.length);
  17650. if (Array.isArray(values)) {
  17651. var newObjectToMerge = {};
  17652. for (var i = 0; i < values.length; ++i) {
  17653. newObjectToMerge['' + i] = values[i];
  17654. }
  17655. values = newObjectToMerge;
  17656. warn('Passing an Array to Firebase.update() is deprecated. ' +
  17657. 'Use set() if you want to overwrite the existing data, or ' +
  17658. 'an Object with integer keys if you really do want to ' +
  17659. 'only update some of the children.');
  17660. }
  17661. _validateWritablePath('Reference.update', this._delegate._path);
  17662. require$$1$3.validateCallback('Reference.update', 'onComplete', onComplete, true);
  17663. var result = update_1(this._delegate, values);
  17664. if (onComplete) {
  17665. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17666. }
  17667. return result;
  17668. };
  17669. Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {
  17670. require$$1$3.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);
  17671. require$$1$3.validateCallback('Reference.setWithPriority', 'onComplete', onComplete, true);
  17672. var result = setWithPriority_1(this._delegate, newVal, newPriority);
  17673. if (onComplete) {
  17674. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17675. }
  17676. return result;
  17677. };
  17678. Reference.prototype.remove = function (onComplete) {
  17679. require$$1$3.validateArgCount('Reference.remove', 0, 1, arguments.length);
  17680. require$$1$3.validateCallback('Reference.remove', 'onComplete', onComplete, true);
  17681. var result = remove_1(this._delegate);
  17682. if (onComplete) {
  17683. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17684. }
  17685. return result;
  17686. };
  17687. Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {
  17688. var _this = this;
  17689. require$$1$3.validateArgCount('Reference.transaction', 1, 3, arguments.length);
  17690. require$$1$3.validateCallback('Reference.transaction', 'transactionUpdate', transactionUpdate, false);
  17691. require$$1$3.validateCallback('Reference.transaction', 'onComplete', onComplete, true);
  17692. validateBoolean('Reference.transaction', 'applyLocally', applyLocally, true);
  17693. var result = runTransaction_1(this._delegate, transactionUpdate, {
  17694. applyLocally: applyLocally
  17695. }).then(function (transactionResult) {
  17696. return new TransactionResult(transactionResult.committed, new DataSnapshot(_this.database, transactionResult.snapshot));
  17697. });
  17698. if (onComplete) {
  17699. result.then(function (transactionResult) {
  17700. return onComplete(null, transactionResult.committed, transactionResult.snapshot);
  17701. }, function (error) { return onComplete(error, false, null); });
  17702. }
  17703. return result;
  17704. };
  17705. Reference.prototype.setPriority = function (priority, onComplete) {
  17706. require$$1$3.validateArgCount('Reference.setPriority', 1, 2, arguments.length);
  17707. require$$1$3.validateCallback('Reference.setPriority', 'onComplete', onComplete, true);
  17708. var result = setPriority_1(this._delegate, priority);
  17709. if (onComplete) {
  17710. result.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17711. }
  17712. return result;
  17713. };
  17714. Reference.prototype.push = function (value, onComplete) {
  17715. var _this = this;
  17716. require$$1$3.validateArgCount('Reference.push', 0, 2, arguments.length);
  17717. require$$1$3.validateCallback('Reference.push', 'onComplete', onComplete, true);
  17718. var expPromise = push_1(this._delegate, value);
  17719. var promise = expPromise.then(function (expRef) { return new Reference(_this.database, expRef); });
  17720. if (onComplete) {
  17721. promise.then(function () { return onComplete(null); }, function (error) { return onComplete(error); });
  17722. }
  17723. var result = new Reference(this.database, expPromise);
  17724. result.then = promise.then.bind(promise);
  17725. result.catch = promise.catch.bind(promise, undefined);
  17726. return result;
  17727. };
  17728. Reference.prototype.onDisconnect = function () {
  17729. _validateWritablePath('Reference.onDisconnect', this._delegate._path);
  17730. return new OnDisconnect(new OnDisconnect_1(this._delegate._repo, this._delegate._path));
  17731. };
  17732. Object.defineProperty(Reference.prototype, "key", {
  17733. get: function () {
  17734. return this.getKey();
  17735. },
  17736. enumerable: false,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(Reference.prototype, "parent", {
  17740. get: function () {
  17741. return this.getParent();
  17742. },
  17743. enumerable: false,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Reference.prototype, "root", {
  17747. get: function () {
  17748. return this.getRoot();
  17749. },
  17750. enumerable: false,
  17751. configurable: true
  17752. });
  17753. return Reference;
  17754. }(Query));
  17755. /**
  17756. * @license
  17757. * Copyright 2017 Google LLC
  17758. *
  17759. * Licensed under the Apache License, Version 2.0 (the "License");
  17760. * you may not use this file except in compliance with the License.
  17761. * You may obtain a copy of the License at
  17762. *
  17763. * http://www.apache.org/licenses/LICENSE-2.0
  17764. *
  17765. * Unless required by applicable law or agreed to in writing, software
  17766. * distributed under the License is distributed on an "AS IS" BASIS,
  17767. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17768. * See the License for the specific language governing permissions and
  17769. * limitations under the License.
  17770. */
  17771. /**
  17772. * Class representing a firebase database.
  17773. */
  17774. var Database = /** @class */ (function () {
  17775. /**
  17776. * The constructor should not be called by users of our public API.
  17777. */
  17778. function Database(_delegate, app) {
  17779. var _this = this;
  17780. this._delegate = _delegate;
  17781. this.app = app;
  17782. this.INTERNAL = {
  17783. delete: function () { return _this._delegate._delete(); },
  17784. forceWebSockets: forceWebSockets_1,
  17785. forceLongPolling: forceLongPolling_1
  17786. };
  17787. }
  17788. /**
  17789. * Modify this instance to communicate with the Realtime Database emulator.
  17790. *
  17791. * <p>Note: This method must be called before performing any other operation.
  17792. *
  17793. * @param host - the emulator host (ex: localhost)
  17794. * @param port - the emulator port (ex: 8080)
  17795. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  17796. */
  17797. Database.prototype.useEmulator = function (host, port, options) {
  17798. if (options === void 0) { options = {}; }
  17799. connectDatabaseEmulator_1(this._delegate, host, port, options);
  17800. };
  17801. Database.prototype.ref = function (path) {
  17802. require$$1$3.validateArgCount('database.ref', 0, 1, arguments.length);
  17803. if (path instanceof Reference) {
  17804. var childRef = refFromURL_1(this._delegate, path.toString());
  17805. return new Reference(this, childRef);
  17806. }
  17807. else {
  17808. var childRef = ref_1(this._delegate, path);
  17809. return new Reference(this, childRef);
  17810. }
  17811. };
  17812. /**
  17813. * Returns a reference to the root or the path specified in url.
  17814. * We throw a exception if the url is not in the same domain as the
  17815. * current repo.
  17816. * @returns Firebase reference.
  17817. */
  17818. Database.prototype.refFromURL = function (url) {
  17819. var apiName = 'database.refFromURL';
  17820. require$$1$3.validateArgCount(apiName, 1, 1, arguments.length);
  17821. var childRef = refFromURL_1(this._delegate, url);
  17822. return new Reference(this, childRef);
  17823. };
  17824. // Make individual repo go offline.
  17825. Database.prototype.goOffline = function () {
  17826. require$$1$3.validateArgCount('database.goOffline', 0, 0, arguments.length);
  17827. return goOffline_1(this._delegate);
  17828. };
  17829. Database.prototype.goOnline = function () {
  17830. require$$1$3.validateArgCount('database.goOnline', 0, 0, arguments.length);
  17831. return goOnline_1(this._delegate);
  17832. };
  17833. Database.ServerValue = {
  17834. TIMESTAMP: serverTimestamp_1(),
  17835. increment: function (delta) { return increment_1(delta); }
  17836. };
  17837. return Database;
  17838. }());
  17839. /**
  17840. * @license
  17841. * Copyright 2017 Google LLC
  17842. *
  17843. * Licensed under the Apache License, Version 2.0 (the "License");
  17844. * you may not use this file except in compliance with the License.
  17845. * You may obtain a copy of the License at
  17846. *
  17847. * http://www.apache.org/licenses/LICENSE-2.0
  17848. *
  17849. * Unless required by applicable law or agreed to in writing, software
  17850. * distributed under the License is distributed on an "AS IS" BASIS,
  17851. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17852. * See the License for the specific language governing permissions and
  17853. * limitations under the License.
  17854. */
  17855. /**
  17856. * Used by console to create a database based on the app,
  17857. * passed database URL and a custom auth implementation.
  17858. *
  17859. * @param app - A valid FirebaseApp-like object
  17860. * @param url - A valid Firebase databaseURL
  17861. * @param version - custom version e.g. firebase-admin version
  17862. * @param customAuthImpl - custom auth implementation
  17863. */
  17864. function initStandalone$1(_a) {
  17865. var app = _a.app, url = _a.url, version = _a.version, customAuthImpl = _a.customAuthImpl, namespace = _a.namespace, _b = _a.nodeAdmin, nodeAdmin = _b === void 0 ? false : _b;
  17866. _setSDKVersion(version);
  17867. /**
  17868. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  17869. * any actual function.
  17870. */
  17871. var authProvider = new component.Provider('auth-internal', new component.ComponentContainer('database-standalone'));
  17872. authProvider.setComponent(new component.Component('auth-internal', function () { return customAuthImpl; }, "PRIVATE" /* ComponentType.PRIVATE */));
  17873. return {
  17874. instance: new Database(_repoManagerDatabaseFromApp(app, authProvider,
  17875. /* appCheckProvider= */ undefined, url, nodeAdmin), app),
  17876. namespace: namespace
  17877. };
  17878. }
  17879. var INTERNAL = /*#__PURE__*/Object.freeze({
  17880. __proto__: null,
  17881. initStandalone: initStandalone$1
  17882. });
  17883. /**
  17884. * @license
  17885. * Copyright 2021 Google LLC
  17886. *
  17887. * Licensed under the Apache License, Version 2.0 (the "License");
  17888. * you may not use this file except in compliance with the License.
  17889. * You may obtain a copy of the License at
  17890. *
  17891. * http://www.apache.org/licenses/LICENSE-2.0
  17892. *
  17893. * Unless required by applicable law or agreed to in writing, software
  17894. * distributed under the License is distributed on an "AS IS" BASIS,
  17895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17896. * See the License for the specific language governing permissions and
  17897. * limitations under the License.
  17898. */
  17899. var ServerValue = Database.ServerValue;
  17900. /**
  17901. * A one off register function which returns a database based on the app and
  17902. * passed database URL. (Used by the Admin SDK)
  17903. *
  17904. * @param app - A valid FirebaseApp-like object
  17905. * @param url - A valid Firebase databaseURL
  17906. * @param version - custom version e.g. firebase-admin version
  17907. * @param nodeAdmin - true if the SDK is being initialized from Firebase Admin.
  17908. */
  17909. function initStandalone(app, url, version, nodeAdmin) {
  17910. if (nodeAdmin === void 0) { nodeAdmin = true; }
  17911. require$$1$3.CONSTANTS.NODE_ADMIN = nodeAdmin;
  17912. return initStandalone$1({
  17913. app: app,
  17914. url: url,
  17915. version: version,
  17916. // firebase-admin-node's app.INTERNAL implements FirebaseAuthInternal interface
  17917. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17918. customAuthImpl: app.INTERNAL,
  17919. namespace: {
  17920. Reference: Reference,
  17921. Query: Query,
  17922. Database: Database,
  17923. DataSnapshot: DataSnapshot,
  17924. enableLogging: enableLogging_1,
  17925. INTERNAL: INTERNAL,
  17926. ServerValue: ServerValue
  17927. },
  17928. nodeAdmin: nodeAdmin
  17929. });
  17930. }
  17931. exports.DataSnapshot = DataSnapshot;
  17932. exports.Database = Database;
  17933. exports.OnDisconnect = OnDisconnect_1;
  17934. exports.Query = Query;
  17935. exports.Reference = Reference;
  17936. exports.ServerValue = ServerValue;
  17937. exports.enableLogging = enableLogging_1;
  17938. exports.initStandalone = initStandalone;
  17939. //# sourceMappingURL=index.standalone.js.map