Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936
  1. import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
  4. import { Logger, LogLevel } from '@firebase/logger';
  5. const name = "@firebase/database";
  6. const version = "0.14.1";
  7. /**
  8. * @license
  9. * Copyright 2019 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /** The semver (www.semver.org) version of the SDK. */
  24. let SDK_VERSION = '';
  25. /**
  26. * SDK_VERSION should be set before any database instance is created
  27. * @internal
  28. */
  29. function setSDKVersion(version) {
  30. SDK_VERSION = version;
  31. }
  32. /**
  33. * @license
  34. * Copyright 2017 Google LLC
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. /**
  49. * Wraps a DOM Storage object and:
  50. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  51. * - prefixes names with "firebase:" to avoid collisions with app data.
  52. *
  53. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  54. * and one for localStorage.
  55. *
  56. */
  57. class DOMStorageWrapper {
  58. /**
  59. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  60. */
  61. constructor(domStorage_) {
  62. this.domStorage_ = domStorage_;
  63. // Use a prefix to avoid collisions with other stuff saved by the app.
  64. this.prefix_ = 'firebase:';
  65. }
  66. /**
  67. * @param key - The key to save the value under
  68. * @param value - The value being stored, or null to remove the key.
  69. */
  70. set(key, value) {
  71. if (value == null) {
  72. this.domStorage_.removeItem(this.prefixedName_(key));
  73. }
  74. else {
  75. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  76. }
  77. }
  78. /**
  79. * @returns The value that was stored under this key, or null
  80. */
  81. get(key) {
  82. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  83. if (storedVal == null) {
  84. return null;
  85. }
  86. else {
  87. return jsonEval(storedVal);
  88. }
  89. }
  90. remove(key) {
  91. this.domStorage_.removeItem(this.prefixedName_(key));
  92. }
  93. prefixedName_(name) {
  94. return this.prefix_ + name;
  95. }
  96. toString() {
  97. return this.domStorage_.toString();
  98. }
  99. }
  100. /**
  101. * @license
  102. * Copyright 2017 Google LLC
  103. *
  104. * Licensed under the Apache License, Version 2.0 (the "License");
  105. * you may not use this file except in compliance with the License.
  106. * You may obtain a copy of the License at
  107. *
  108. * http://www.apache.org/licenses/LICENSE-2.0
  109. *
  110. * Unless required by applicable law or agreed to in writing, software
  111. * distributed under the License is distributed on an "AS IS" BASIS,
  112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  113. * See the License for the specific language governing permissions and
  114. * limitations under the License.
  115. */
  116. /**
  117. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  118. * (TODO: create interface for both to implement).
  119. */
  120. class MemoryStorage {
  121. constructor() {
  122. this.cache_ = {};
  123. this.isInMemoryStorage = true;
  124. }
  125. set(key, value) {
  126. if (value == null) {
  127. delete this.cache_[key];
  128. }
  129. else {
  130. this.cache_[key] = value;
  131. }
  132. }
  133. get(key) {
  134. if (contains(this.cache_, key)) {
  135. return this.cache_[key];
  136. }
  137. return null;
  138. }
  139. remove(key) {
  140. delete this.cache_[key];
  141. }
  142. }
  143. /**
  144. * @license
  145. * Copyright 2017 Google LLC
  146. *
  147. * Licensed under the Apache License, Version 2.0 (the "License");
  148. * you may not use this file except in compliance with the License.
  149. * You may obtain a copy of the License at
  150. *
  151. * http://www.apache.org/licenses/LICENSE-2.0
  152. *
  153. * Unless required by applicable law or agreed to in writing, software
  154. * distributed under the License is distributed on an "AS IS" BASIS,
  155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  156. * See the License for the specific language governing permissions and
  157. * limitations under the License.
  158. */
  159. /**
  160. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  161. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  162. * to reflect this type
  163. *
  164. * @param domStorageName - Name of the underlying storage object
  165. * (e.g. 'localStorage' or 'sessionStorage').
  166. * @returns Turning off type information until a common interface is defined.
  167. */
  168. const createStoragefor = function (domStorageName) {
  169. try {
  170. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  171. // so it must be inside the try/catch.
  172. if (typeof window !== 'undefined' &&
  173. typeof window[domStorageName] !== 'undefined') {
  174. // Need to test cache. Just because it's here doesn't mean it works
  175. const domStorage = window[domStorageName];
  176. domStorage.setItem('firebase:sentinel', 'cache');
  177. domStorage.removeItem('firebase:sentinel');
  178. return new DOMStorageWrapper(domStorage);
  179. }
  180. }
  181. catch (e) { }
  182. // Failed to create wrapper. Just return in-memory storage.
  183. // TODO: log?
  184. return new MemoryStorage();
  185. };
  186. /** A storage object that lasts across sessions */
  187. const PersistentStorage = createStoragefor('localStorage');
  188. /** A storage object that only lasts one session */
  189. const SessionStorage = createStoragefor('sessionStorage');
  190. /**
  191. * @license
  192. * Copyright 2017 Google LLC
  193. *
  194. * Licensed under the Apache License, Version 2.0 (the "License");
  195. * you may not use this file except in compliance with the License.
  196. * You may obtain a copy of the License at
  197. *
  198. * http://www.apache.org/licenses/LICENSE-2.0
  199. *
  200. * Unless required by applicable law or agreed to in writing, software
  201. * distributed under the License is distributed on an "AS IS" BASIS,
  202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  203. * See the License for the specific language governing permissions and
  204. * limitations under the License.
  205. */
  206. const logClient = new Logger('@firebase/database');
  207. /**
  208. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  209. */
  210. const LUIDGenerator = (function () {
  211. let id = 1;
  212. return function () {
  213. return id++;
  214. };
  215. })();
  216. /**
  217. * Sha1 hash of the input string
  218. * @param str - The string to hash
  219. * @returns {!string} The resulting hash
  220. */
  221. const sha1 = function (str) {
  222. const utf8Bytes = stringToByteArray(str);
  223. const sha1 = new Sha1();
  224. sha1.update(utf8Bytes);
  225. const sha1Bytes = sha1.digest();
  226. return base64.encodeByteArray(sha1Bytes);
  227. };
  228. const buildLogMessage_ = function (...varArgs) {
  229. let message = '';
  230. for (let i = 0; i < varArgs.length; i++) {
  231. const arg = varArgs[i];
  232. if (Array.isArray(arg) ||
  233. (arg &&
  234. typeof arg === 'object' &&
  235. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  236. typeof arg.length === 'number')) {
  237. message += buildLogMessage_.apply(null, arg);
  238. }
  239. else if (typeof arg === 'object') {
  240. message += stringify(arg);
  241. }
  242. else {
  243. message += arg;
  244. }
  245. message += ' ';
  246. }
  247. return message;
  248. };
  249. /**
  250. * Use this for all debug messages in Firebase.
  251. */
  252. let logger = null;
  253. /**
  254. * Flag to check for log availability on first log message
  255. */
  256. let firstLog_ = true;
  257. /**
  258. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  259. * @param logger_ - A flag to turn on logging, or a custom logger
  260. * @param persistent - Whether or not to persist logging settings across refreshes
  261. */
  262. const enableLogging$1 = function (logger_, persistent) {
  263. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  264. if (logger_ === true) {
  265. logClient.logLevel = LogLevel.VERBOSE;
  266. logger = logClient.log.bind(logClient);
  267. if (persistent) {
  268. SessionStorage.set('logging_enabled', true);
  269. }
  270. }
  271. else if (typeof logger_ === 'function') {
  272. logger = logger_;
  273. }
  274. else {
  275. logger = null;
  276. SessionStorage.remove('logging_enabled');
  277. }
  278. };
  279. const log = function (...varArgs) {
  280. if (firstLog_ === true) {
  281. firstLog_ = false;
  282. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  283. enableLogging$1(true);
  284. }
  285. }
  286. if (logger) {
  287. const message = buildLogMessage_.apply(null, varArgs);
  288. logger(message);
  289. }
  290. };
  291. const logWrapper = function (prefix) {
  292. return function (...varArgs) {
  293. log(prefix, ...varArgs);
  294. };
  295. };
  296. const error = function (...varArgs) {
  297. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  298. logClient.error(message);
  299. };
  300. const fatal = function (...varArgs) {
  301. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  302. logClient.error(message);
  303. throw new Error(message);
  304. };
  305. const warn = function (...varArgs) {
  306. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  307. logClient.warn(message);
  308. };
  309. /**
  310. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  311. * does not use https.
  312. */
  313. const warnIfPageIsSecure = function () {
  314. // Be very careful accessing browser globals. Who knows what may or may not exist.
  315. if (typeof window !== 'undefined' &&
  316. window.location &&
  317. window.location.protocol &&
  318. window.location.protocol.indexOf('https:') !== -1) {
  319. warn('Insecure Firebase access from a secure page. ' +
  320. 'Please use https in calls to new Firebase().');
  321. }
  322. };
  323. /**
  324. * Returns true if data is NaN, or +/- Infinity.
  325. */
  326. const isInvalidJSONNumber = function (data) {
  327. return (typeof data === 'number' &&
  328. (data !== data || // NaN
  329. data === Number.POSITIVE_INFINITY ||
  330. data === Number.NEGATIVE_INFINITY));
  331. };
  332. const executeWhenDOMReady = function (fn) {
  333. if (isNodeSdk() || document.readyState === 'complete') {
  334. fn();
  335. }
  336. else {
  337. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  338. // fire before onload), but fall back to onload.
  339. let called = false;
  340. const wrappedFn = function () {
  341. if (!document.body) {
  342. setTimeout(wrappedFn, Math.floor(10));
  343. return;
  344. }
  345. if (!called) {
  346. called = true;
  347. fn();
  348. }
  349. };
  350. if (document.addEventListener) {
  351. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  352. // fallback to onload.
  353. window.addEventListener('load', wrappedFn, false);
  354. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  355. }
  356. else if (document.attachEvent) {
  357. // IE.
  358. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  359. document.attachEvent('onreadystatechange', () => {
  360. if (document.readyState === 'complete') {
  361. wrappedFn();
  362. }
  363. });
  364. // fallback to onload.
  365. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  366. window.attachEvent('onload', wrappedFn);
  367. // jQuery has an extra hack for IE that we could employ (based on
  368. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  369. // I'm hoping we don't need it.
  370. }
  371. }
  372. };
  373. /**
  374. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  375. */
  376. const MIN_NAME = '[MIN_NAME]';
  377. /**
  378. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  379. */
  380. const MAX_NAME = '[MAX_NAME]';
  381. /**
  382. * Compares valid Firebase key names, plus min and max name
  383. */
  384. const nameCompare = function (a, b) {
  385. if (a === b) {
  386. return 0;
  387. }
  388. else if (a === MIN_NAME || b === MAX_NAME) {
  389. return -1;
  390. }
  391. else if (b === MIN_NAME || a === MAX_NAME) {
  392. return 1;
  393. }
  394. else {
  395. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  396. if (aAsInt !== null) {
  397. if (bAsInt !== null) {
  398. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  399. }
  400. else {
  401. return -1;
  402. }
  403. }
  404. else if (bAsInt !== null) {
  405. return 1;
  406. }
  407. else {
  408. return a < b ? -1 : 1;
  409. }
  410. }
  411. };
  412. /**
  413. * @returns {!number} comparison result.
  414. */
  415. const stringCompare = function (a, b) {
  416. if (a === b) {
  417. return 0;
  418. }
  419. else if (a < b) {
  420. return -1;
  421. }
  422. else {
  423. return 1;
  424. }
  425. };
  426. const requireKey = function (key, obj) {
  427. if (obj && key in obj) {
  428. return obj[key];
  429. }
  430. else {
  431. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  432. }
  433. };
  434. const ObjectToUniqueKey = function (obj) {
  435. if (typeof obj !== 'object' || obj === null) {
  436. return stringify(obj);
  437. }
  438. const keys = [];
  439. // eslint-disable-next-line guard-for-in
  440. for (const k in obj) {
  441. keys.push(k);
  442. }
  443. // Export as json, but with the keys sorted.
  444. keys.sort();
  445. let key = '{';
  446. for (let i = 0; i < keys.length; i++) {
  447. if (i !== 0) {
  448. key += ',';
  449. }
  450. key += stringify(keys[i]);
  451. key += ':';
  452. key += ObjectToUniqueKey(obj[keys[i]]);
  453. }
  454. key += '}';
  455. return key;
  456. };
  457. /**
  458. * Splits a string into a number of smaller segments of maximum size
  459. * @param str - The string
  460. * @param segsize - The maximum number of chars in the string.
  461. * @returns The string, split into appropriately-sized chunks
  462. */
  463. const splitStringBySize = function (str, segsize) {
  464. const len = str.length;
  465. if (len <= segsize) {
  466. return [str];
  467. }
  468. const dataSegs = [];
  469. for (let c = 0; c < len; c += segsize) {
  470. if (c + segsize > len) {
  471. dataSegs.push(str.substring(c, len));
  472. }
  473. else {
  474. dataSegs.push(str.substring(c, c + segsize));
  475. }
  476. }
  477. return dataSegs;
  478. };
  479. /**
  480. * Apply a function to each (key, value) pair in an object or
  481. * apply a function to each (index, value) pair in an array
  482. * @param obj - The object or array to iterate over
  483. * @param fn - The function to apply
  484. */
  485. function each(obj, fn) {
  486. for (const key in obj) {
  487. if (obj.hasOwnProperty(key)) {
  488. fn(key, obj[key]);
  489. }
  490. }
  491. }
  492. /**
  493. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  494. * I made one modification at the end and removed the NaN / Infinity
  495. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  496. * @param v - A double
  497. *
  498. */
  499. const doubleToIEEE754String = function (v) {
  500. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  501. const ebits = 11, fbits = 52;
  502. const bias = (1 << (ebits - 1)) - 1;
  503. let s, e, f, ln, i;
  504. // Compute sign, exponent, fraction
  505. // Skip NaN / Infinity handling --MJL.
  506. if (v === 0) {
  507. e = 0;
  508. f = 0;
  509. s = 1 / v === -Infinity ? 1 : 0;
  510. }
  511. else {
  512. s = v < 0;
  513. v = Math.abs(v);
  514. if (v >= Math.pow(2, 1 - bias)) {
  515. // Normalized
  516. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  517. e = ln + bias;
  518. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  519. }
  520. else {
  521. // Denormalized
  522. e = 0;
  523. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  524. }
  525. }
  526. // Pack sign, exponent, fraction
  527. const bits = [];
  528. for (i = fbits; i; i -= 1) {
  529. bits.push(f % 2 ? 1 : 0);
  530. f = Math.floor(f / 2);
  531. }
  532. for (i = ebits; i; i -= 1) {
  533. bits.push(e % 2 ? 1 : 0);
  534. e = Math.floor(e / 2);
  535. }
  536. bits.push(s ? 1 : 0);
  537. bits.reverse();
  538. const str = bits.join('');
  539. // Return the data as a hex string. --MJL
  540. let hexByteString = '';
  541. for (i = 0; i < 64; i += 8) {
  542. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  543. if (hexByte.length === 1) {
  544. hexByte = '0' + hexByte;
  545. }
  546. hexByteString = hexByteString + hexByte;
  547. }
  548. return hexByteString.toLowerCase();
  549. };
  550. /**
  551. * Used to detect if we're in a Chrome content script (which executes in an
  552. * isolated environment where long-polling doesn't work).
  553. */
  554. const isChromeExtensionContentScript = function () {
  555. return !!(typeof window === 'object' &&
  556. window['chrome'] &&
  557. window['chrome']['extension'] &&
  558. !/^chrome/.test(window.location.href));
  559. };
  560. /**
  561. * Used to detect if we're in a Windows 8 Store app.
  562. */
  563. const isWindowsStoreApp = function () {
  564. // Check for the presence of a couple WinRT globals
  565. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  566. };
  567. /**
  568. * Converts a server error code to a Javascript Error
  569. */
  570. function errorForServerCode(code, query) {
  571. let reason = 'Unknown Error';
  572. if (code === 'too_big') {
  573. reason =
  574. 'The data requested exceeds the maximum size ' +
  575. 'that can be accessed with a single request.';
  576. }
  577. else if (code === 'permission_denied') {
  578. reason = "Client doesn't have permission to access the desired data.";
  579. }
  580. else if (code === 'unavailable') {
  581. reason = 'The service is unavailable';
  582. }
  583. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  585. error.code = code.toUpperCase();
  586. return error;
  587. }
  588. /**
  589. * Used to test for integer-looking strings
  590. */
  591. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  592. /**
  593. * For use in keys, the minimum possible 32-bit integer.
  594. */
  595. const INTEGER_32_MIN = -2147483648;
  596. /**
  597. * For use in kyes, the maximum possible 32-bit integer.
  598. */
  599. const INTEGER_32_MAX = 2147483647;
  600. /**
  601. * If the string contains a 32-bit integer, return it. Else return null.
  602. */
  603. const tryParseInt = function (str) {
  604. if (INTEGER_REGEXP_.test(str)) {
  605. const intVal = Number(str);
  606. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  607. return intVal;
  608. }
  609. }
  610. return null;
  611. };
  612. /**
  613. * Helper to run some code but catch any exceptions and re-throw them later.
  614. * Useful for preventing user callbacks from breaking internal code.
  615. *
  616. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  617. * convenient (we don't have to try to figure out when is a safe point to
  618. * re-throw it), and the behavior seems reasonable:
  619. *
  620. * * If you aren't pausing on exceptions, you get an error in the console with
  621. * the correct stack trace.
  622. * * If you're pausing on all exceptions, the debugger will pause on your
  623. * exception and then again when we rethrow it.
  624. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  625. * on us re-throwing it.
  626. *
  627. * @param fn - The code to guard.
  628. */
  629. const exceptionGuard = function (fn) {
  630. try {
  631. fn();
  632. }
  633. catch (e) {
  634. // Re-throw exception when it's safe.
  635. setTimeout(() => {
  636. // It used to be that "throw e" would result in a good console error with
  637. // relevant context, but as of Chrome 39, you just get the firebase.js
  638. // file/line number where we re-throw it, which is useless. So we log
  639. // e.stack explicitly.
  640. const stack = e.stack || '';
  641. warn('Exception was thrown by user callback.', stack);
  642. throw e;
  643. }, Math.floor(0));
  644. }
  645. };
  646. /**
  647. * @returns {boolean} true if we think we're currently being crawled.
  648. */
  649. const beingCrawled = function () {
  650. const userAgent = (typeof window === 'object' &&
  651. window['navigator'] &&
  652. window['navigator']['userAgent']) ||
  653. '';
  654. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  655. // believe to support JavaScript/AJAX rendering.
  656. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  657. // would have seen the page" is flaky if we don't treat it as a crawler.
  658. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  659. };
  660. /**
  661. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  662. *
  663. * It is removed with clearTimeout() as normal.
  664. *
  665. * @param fn - Function to run.
  666. * @param time - Milliseconds to wait before running.
  667. * @returns The setTimeout() return value.
  668. */
  669. const setTimeoutNonBlocking = function (fn, time) {
  670. const timeout = setTimeout(fn, time);
  671. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  672. if (typeof timeout === 'number' &&
  673. // @ts-ignore Is only defined in Deno environments.
  674. typeof Deno !== 'undefined' &&
  675. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  676. Deno['unrefTimer']) {
  677. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  678. Deno.unrefTimer(timeout);
  679. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  680. }
  681. else if (typeof timeout === 'object' && timeout['unref']) {
  682. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  683. timeout['unref']();
  684. }
  685. return timeout;
  686. };
  687. /**
  688. * @license
  689. * Copyright 2021 Google LLC
  690. *
  691. * Licensed under the Apache License, Version 2.0 (the "License");
  692. * you may not use this file except in compliance with the License.
  693. * You may obtain a copy of the License at
  694. *
  695. * http://www.apache.org/licenses/LICENSE-2.0
  696. *
  697. * Unless required by applicable law or agreed to in writing, software
  698. * distributed under the License is distributed on an "AS IS" BASIS,
  699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  700. * See the License for the specific language governing permissions and
  701. * limitations under the License.
  702. */
  703. /**
  704. * Abstraction around AppCheck's token fetching capabilities.
  705. */
  706. class AppCheckTokenProvider {
  707. constructor(appName_, appCheckProvider) {
  708. this.appName_ = appName_;
  709. this.appCheckProvider = appCheckProvider;
  710. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  711. if (!this.appCheck) {
  712. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  713. }
  714. }
  715. getToken(forceRefresh) {
  716. if (!this.appCheck) {
  717. return new Promise((resolve, reject) => {
  718. // Support delayed initialization of FirebaseAppCheck. This allows our
  719. // customers to initialize the RTDB SDK before initializing Firebase
  720. // AppCheck and ensures that all requests are authenticated if a token
  721. // becomes available before the timoeout below expires.
  722. setTimeout(() => {
  723. if (this.appCheck) {
  724. this.getToken(forceRefresh).then(resolve, reject);
  725. }
  726. else {
  727. resolve(null);
  728. }
  729. }, 0);
  730. });
  731. }
  732. return this.appCheck.getToken(forceRefresh);
  733. }
  734. addTokenChangeListener(listener) {
  735. var _a;
  736. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  737. }
  738. notifyForInvalidToken() {
  739. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  740. 'are invalid. This usually indicates your app was not initialized correctly.');
  741. }
  742. }
  743. /**
  744. * @license
  745. * Copyright 2017 Google LLC
  746. *
  747. * Licensed under the Apache License, Version 2.0 (the "License");
  748. * you may not use this file except in compliance with the License.
  749. * You may obtain a copy of the License at
  750. *
  751. * http://www.apache.org/licenses/LICENSE-2.0
  752. *
  753. * Unless required by applicable law or agreed to in writing, software
  754. * distributed under the License is distributed on an "AS IS" BASIS,
  755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  756. * See the License for the specific language governing permissions and
  757. * limitations under the License.
  758. */
  759. /**
  760. * Abstraction around FirebaseApp's token fetching capabilities.
  761. */
  762. class FirebaseAuthTokenProvider {
  763. constructor(appName_, firebaseOptions_, authProvider_) {
  764. this.appName_ = appName_;
  765. this.firebaseOptions_ = firebaseOptions_;
  766. this.authProvider_ = authProvider_;
  767. this.auth_ = null;
  768. this.auth_ = authProvider_.getImmediate({ optional: true });
  769. if (!this.auth_) {
  770. authProvider_.onInit(auth => (this.auth_ = auth));
  771. }
  772. }
  773. getToken(forceRefresh) {
  774. if (!this.auth_) {
  775. return new Promise((resolve, reject) => {
  776. // Support delayed initialization of FirebaseAuth. This allows our
  777. // customers to initialize the RTDB SDK before initializing Firebase
  778. // Auth and ensures that all requests are authenticated if a token
  779. // becomes available before the timoeout below expires.
  780. setTimeout(() => {
  781. if (this.auth_) {
  782. this.getToken(forceRefresh).then(resolve, reject);
  783. }
  784. else {
  785. resolve(null);
  786. }
  787. }, 0);
  788. });
  789. }
  790. return this.auth_.getToken(forceRefresh).catch(error => {
  791. // TODO: Need to figure out all the cases this is raised and whether
  792. // this makes sense.
  793. if (error && error.code === 'auth/token-not-initialized') {
  794. log('Got auth/token-not-initialized error. Treating as null token.');
  795. return null;
  796. }
  797. else {
  798. return Promise.reject(error);
  799. }
  800. });
  801. }
  802. addTokenChangeListener(listener) {
  803. // TODO: We might want to wrap the listener and call it with no args to
  804. // avoid a leaky abstraction, but that makes removing the listener harder.
  805. if (this.auth_) {
  806. this.auth_.addAuthTokenListener(listener);
  807. }
  808. else {
  809. this.authProvider_
  810. .get()
  811. .then(auth => auth.addAuthTokenListener(listener));
  812. }
  813. }
  814. removeTokenChangeListener(listener) {
  815. this.authProvider_
  816. .get()
  817. .then(auth => auth.removeAuthTokenListener(listener));
  818. }
  819. notifyForInvalidToken() {
  820. let errorMessage = 'Provided authentication credentials for the app named "' +
  821. this.appName_ +
  822. '" are invalid. This usually indicates your app was not ' +
  823. 'initialized correctly. ';
  824. if ('credential' in this.firebaseOptions_) {
  825. errorMessage +=
  826. 'Make sure the "credential" property provided to initializeApp() ' +
  827. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  828. 'project.';
  829. }
  830. else if ('serviceAccount' in this.firebaseOptions_) {
  831. errorMessage +=
  832. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  833. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  834. 'project.';
  835. }
  836. else {
  837. errorMessage +=
  838. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  839. 'initializeApp() match the values provided for your app at ' +
  840. 'https://console.firebase.google.com/.';
  841. }
  842. warn(errorMessage);
  843. }
  844. }
  845. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  846. class EmulatorTokenProvider {
  847. constructor(accessToken) {
  848. this.accessToken = accessToken;
  849. }
  850. getToken(forceRefresh) {
  851. return Promise.resolve({
  852. accessToken: this.accessToken
  853. });
  854. }
  855. addTokenChangeListener(listener) {
  856. // Invoke the listener immediately to match the behavior in Firebase Auth
  857. // (see packages/auth/src/auth.js#L1807)
  858. listener(this.accessToken);
  859. }
  860. removeTokenChangeListener(listener) { }
  861. notifyForInvalidToken() { }
  862. }
  863. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  864. EmulatorTokenProvider.OWNER = 'owner';
  865. /**
  866. * @license
  867. * Copyright 2017 Google LLC
  868. *
  869. * Licensed under the Apache License, Version 2.0 (the "License");
  870. * you may not use this file except in compliance with the License.
  871. * You may obtain a copy of the License at
  872. *
  873. * http://www.apache.org/licenses/LICENSE-2.0
  874. *
  875. * Unless required by applicable law or agreed to in writing, software
  876. * distributed under the License is distributed on an "AS IS" BASIS,
  877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  878. * See the License for the specific language governing permissions and
  879. * limitations under the License.
  880. */
  881. const PROTOCOL_VERSION = '5';
  882. const VERSION_PARAM = 'v';
  883. const TRANSPORT_SESSION_PARAM = 's';
  884. const REFERER_PARAM = 'r';
  885. const FORGE_REF = 'f';
  886. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  887. // firebase.corp.google.com
  888. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  889. const LAST_SESSION_PARAM = 'ls';
  890. const APPLICATION_ID_PARAM = 'p';
  891. const APP_CHECK_TOKEN_PARAM = 'ac';
  892. const WEBSOCKET = 'websocket';
  893. const LONG_POLLING = 'long_polling';
  894. /**
  895. * @license
  896. * Copyright 2017 Google LLC
  897. *
  898. * Licensed under the Apache License, Version 2.0 (the "License");
  899. * you may not use this file except in compliance with the License.
  900. * You may obtain a copy of the License at
  901. *
  902. * http://www.apache.org/licenses/LICENSE-2.0
  903. *
  904. * Unless required by applicable law or agreed to in writing, software
  905. * distributed under the License is distributed on an "AS IS" BASIS,
  906. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  907. * See the License for the specific language governing permissions and
  908. * limitations under the License.
  909. */
  910. /**
  911. * A class that holds metadata about a Repo object
  912. */
  913. class RepoInfo {
  914. /**
  915. * @param host - Hostname portion of the url for the repo
  916. * @param secure - Whether or not this repo is accessed over ssl
  917. * @param namespace - The namespace represented by the repo
  918. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  919. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  920. * @param persistenceKey - Override the default session persistence storage key
  921. */
  922. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) {
  923. this.secure = secure;
  924. this.namespace = namespace;
  925. this.webSocketOnly = webSocketOnly;
  926. this.nodeAdmin = nodeAdmin;
  927. this.persistenceKey = persistenceKey;
  928. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  929. this._host = host.toLowerCase();
  930. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  931. this.internalHost =
  932. PersistentStorage.get('host:' + host) || this._host;
  933. }
  934. isCacheableHost() {
  935. return this.internalHost.substr(0, 2) === 's-';
  936. }
  937. isCustomHost() {
  938. return (this._domain !== 'firebaseio.com' &&
  939. this._domain !== 'firebaseio-demo.com');
  940. }
  941. get host() {
  942. return this._host;
  943. }
  944. set host(newHost) {
  945. if (newHost !== this.internalHost) {
  946. this.internalHost = newHost;
  947. if (this.isCacheableHost()) {
  948. PersistentStorage.set('host:' + this._host, this.internalHost);
  949. }
  950. }
  951. }
  952. toString() {
  953. let str = this.toURLString();
  954. if (this.persistenceKey) {
  955. str += '<' + this.persistenceKey + '>';
  956. }
  957. return str;
  958. }
  959. toURLString() {
  960. const protocol = this.secure ? 'https://' : 'http://';
  961. const query = this.includeNamespaceInQueryParams
  962. ? `?ns=${this.namespace}`
  963. : '';
  964. return `${protocol}${this.host}/${query}`;
  965. }
  966. }
  967. function repoInfoNeedsQueryParam(repoInfo) {
  968. return (repoInfo.host !== repoInfo.internalHost ||
  969. repoInfo.isCustomHost() ||
  970. repoInfo.includeNamespaceInQueryParams);
  971. }
  972. /**
  973. * Returns the websocket URL for this repo
  974. * @param repoInfo - RepoInfo object
  975. * @param type - of connection
  976. * @param params - list
  977. * @returns The URL for this repo
  978. */
  979. function repoInfoConnectionURL(repoInfo, type, params) {
  980. assert(typeof type === 'string', 'typeof type must == string');
  981. assert(typeof params === 'object', 'typeof params must == object');
  982. let connURL;
  983. if (type === WEBSOCKET) {
  984. connURL =
  985. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  986. }
  987. else if (type === LONG_POLLING) {
  988. connURL =
  989. (repoInfo.secure ? 'https://' : 'http://') +
  990. repoInfo.internalHost +
  991. '/.lp?';
  992. }
  993. else {
  994. throw new Error('Unknown connection type: ' + type);
  995. }
  996. if (repoInfoNeedsQueryParam(repoInfo)) {
  997. params['ns'] = repoInfo.namespace;
  998. }
  999. const pairs = [];
  1000. each(params, (key, value) => {
  1001. pairs.push(key + '=' + value);
  1002. });
  1003. return connURL + pairs.join('&');
  1004. }
  1005. /**
  1006. * @license
  1007. * Copyright 2017 Google LLC
  1008. *
  1009. * Licensed under the Apache License, Version 2.0 (the "License");
  1010. * you may not use this file except in compliance with the License.
  1011. * You may obtain a copy of the License at
  1012. *
  1013. * http://www.apache.org/licenses/LICENSE-2.0
  1014. *
  1015. * Unless required by applicable law or agreed to in writing, software
  1016. * distributed under the License is distributed on an "AS IS" BASIS,
  1017. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1018. * See the License for the specific language governing permissions and
  1019. * limitations under the License.
  1020. */
  1021. /**
  1022. * Tracks a collection of stats.
  1023. */
  1024. class StatsCollection {
  1025. constructor() {
  1026. this.counters_ = {};
  1027. }
  1028. incrementCounter(name, amount = 1) {
  1029. if (!contains(this.counters_, name)) {
  1030. this.counters_[name] = 0;
  1031. }
  1032. this.counters_[name] += amount;
  1033. }
  1034. get() {
  1035. return deepCopy(this.counters_);
  1036. }
  1037. }
  1038. /**
  1039. * @license
  1040. * Copyright 2017 Google LLC
  1041. *
  1042. * Licensed under the Apache License, Version 2.0 (the "License");
  1043. * you may not use this file except in compliance with the License.
  1044. * You may obtain a copy of the License at
  1045. *
  1046. * http://www.apache.org/licenses/LICENSE-2.0
  1047. *
  1048. * Unless required by applicable law or agreed to in writing, software
  1049. * distributed under the License is distributed on an "AS IS" BASIS,
  1050. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1051. * See the License for the specific language governing permissions and
  1052. * limitations under the License.
  1053. */
  1054. const collections = {};
  1055. const reporters = {};
  1056. function statsManagerGetCollection(repoInfo) {
  1057. const hashString = repoInfo.toString();
  1058. if (!collections[hashString]) {
  1059. collections[hashString] = new StatsCollection();
  1060. }
  1061. return collections[hashString];
  1062. }
  1063. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1064. const hashString = repoInfo.toString();
  1065. if (!reporters[hashString]) {
  1066. reporters[hashString] = creatorFunction();
  1067. }
  1068. return reporters[hashString];
  1069. }
  1070. /**
  1071. * @license
  1072. * Copyright 2017 Google LLC
  1073. *
  1074. * Licensed under the Apache License, Version 2.0 (the "License");
  1075. * you may not use this file except in compliance with the License.
  1076. * You may obtain a copy of the License at
  1077. *
  1078. * http://www.apache.org/licenses/LICENSE-2.0
  1079. *
  1080. * Unless required by applicable law or agreed to in writing, software
  1081. * distributed under the License is distributed on an "AS IS" BASIS,
  1082. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1083. * See the License for the specific language governing permissions and
  1084. * limitations under the License.
  1085. */
  1086. /**
  1087. * This class ensures the packets from the server arrive in order
  1088. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1089. */
  1090. class PacketReceiver {
  1091. /**
  1092. * @param onMessage_
  1093. */
  1094. constructor(onMessage_) {
  1095. this.onMessage_ = onMessage_;
  1096. this.pendingResponses = [];
  1097. this.currentResponseNum = 0;
  1098. this.closeAfterResponse = -1;
  1099. this.onClose = null;
  1100. }
  1101. closeAfter(responseNum, callback) {
  1102. this.closeAfterResponse = responseNum;
  1103. this.onClose = callback;
  1104. if (this.closeAfterResponse < this.currentResponseNum) {
  1105. this.onClose();
  1106. this.onClose = null;
  1107. }
  1108. }
  1109. /**
  1110. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1111. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1112. * browsers will respond in the same order as the requests we sent
  1113. */
  1114. handleResponse(requestNum, data) {
  1115. this.pendingResponses[requestNum] = data;
  1116. while (this.pendingResponses[this.currentResponseNum]) {
  1117. const toProcess = this.pendingResponses[this.currentResponseNum];
  1118. delete this.pendingResponses[this.currentResponseNum];
  1119. for (let i = 0; i < toProcess.length; ++i) {
  1120. if (toProcess[i]) {
  1121. exceptionGuard(() => {
  1122. this.onMessage_(toProcess[i]);
  1123. });
  1124. }
  1125. }
  1126. if (this.currentResponseNum === this.closeAfterResponse) {
  1127. if (this.onClose) {
  1128. this.onClose();
  1129. this.onClose = null;
  1130. }
  1131. break;
  1132. }
  1133. this.currentResponseNum++;
  1134. }
  1135. }
  1136. }
  1137. /**
  1138. * @license
  1139. * Copyright 2017 Google LLC
  1140. *
  1141. * Licensed under the Apache License, Version 2.0 (the "License");
  1142. * you may not use this file except in compliance with the License.
  1143. * You may obtain a copy of the License at
  1144. *
  1145. * http://www.apache.org/licenses/LICENSE-2.0
  1146. *
  1147. * Unless required by applicable law or agreed to in writing, software
  1148. * distributed under the License is distributed on an "AS IS" BASIS,
  1149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1150. * See the License for the specific language governing permissions and
  1151. * limitations under the License.
  1152. */
  1153. // URL query parameters associated with longpolling
  1154. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1155. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1156. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1157. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1158. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1159. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1160. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1161. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1162. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1163. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1164. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1165. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1166. //Data size constants.
  1167. //TODO: Perf: the maximum length actually differs from browser to browser.
  1168. // We should check what browser we're on and set accordingly.
  1169. const MAX_URL_DATA_SIZE = 1870;
  1170. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1171. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1172. /**
  1173. * Keepalive period
  1174. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1175. * length of 30 seconds that we can't exceed.
  1176. */
  1177. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1178. /**
  1179. * How long to wait before aborting a long-polling connection attempt.
  1180. */
  1181. const LP_CONNECT_TIMEOUT = 30000;
  1182. /**
  1183. * This class manages a single long-polling connection.
  1184. */
  1185. class BrowserPollConnection {
  1186. /**
  1187. * @param connId An identifier for this connection, used for logging
  1188. * @param repoInfo The info for the endpoint to send data to.
  1189. * @param applicationId The Firebase App ID for this project.
  1190. * @param appCheckToken The AppCheck token for this client.
  1191. * @param authToken The AuthToken to use for this connection.
  1192. * @param transportSessionId Optional transportSessionid if we are
  1193. * reconnecting for an existing transport session
  1194. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1195. * already created a connection previously
  1196. */
  1197. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1198. this.connId = connId;
  1199. this.repoInfo = repoInfo;
  1200. this.applicationId = applicationId;
  1201. this.appCheckToken = appCheckToken;
  1202. this.authToken = authToken;
  1203. this.transportSessionId = transportSessionId;
  1204. this.lastSessionId = lastSessionId;
  1205. this.bytesSent = 0;
  1206. this.bytesReceived = 0;
  1207. this.everConnected_ = false;
  1208. this.log_ = logWrapper(connId);
  1209. this.stats_ = statsManagerGetCollection(repoInfo);
  1210. this.urlFn = (params) => {
  1211. // Always add the token if we have one.
  1212. if (this.appCheckToken) {
  1213. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1214. }
  1215. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1216. };
  1217. }
  1218. /**
  1219. * @param onMessage - Callback when messages arrive
  1220. * @param onDisconnect - Callback with connection lost.
  1221. */
  1222. open(onMessage, onDisconnect) {
  1223. this.curSegmentNum = 0;
  1224. this.onDisconnect_ = onDisconnect;
  1225. this.myPacketOrderer = new PacketReceiver(onMessage);
  1226. this.isClosed_ = false;
  1227. this.connectTimeoutTimer_ = setTimeout(() => {
  1228. this.log_('Timed out trying to connect.');
  1229. // Make sure we clear the host cache
  1230. this.onClosed_();
  1231. this.connectTimeoutTimer_ = null;
  1232. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1233. }, Math.floor(LP_CONNECT_TIMEOUT));
  1234. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1235. executeWhenDOMReady(() => {
  1236. if (this.isClosed_) {
  1237. return;
  1238. }
  1239. //Set up a callback that gets triggered once a connection is set up.
  1240. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1241. const [command, arg1, arg2, arg3, arg4] = args;
  1242. this.incrementIncomingBytes_(args);
  1243. if (!this.scriptTagHolder) {
  1244. return; // we closed the connection.
  1245. }
  1246. if (this.connectTimeoutTimer_) {
  1247. clearTimeout(this.connectTimeoutTimer_);
  1248. this.connectTimeoutTimer_ = null;
  1249. }
  1250. this.everConnected_ = true;
  1251. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1252. this.id = arg1;
  1253. this.password = arg2;
  1254. }
  1255. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1256. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1257. if (arg1) {
  1258. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1259. // through our already open polls), so don't send any more.
  1260. this.scriptTagHolder.sendNewPolls = false;
  1261. // arg1 in this case is the last response number sent by the server. We should try to receive
  1262. // all of the responses up to this one before closing
  1263. this.myPacketOrderer.closeAfter(arg1, () => {
  1264. this.onClosed_();
  1265. });
  1266. }
  1267. else {
  1268. this.onClosed_();
  1269. }
  1270. }
  1271. else {
  1272. throw new Error('Unrecognized command received: ' + command);
  1273. }
  1274. }, (...args) => {
  1275. const [pN, data] = args;
  1276. this.incrementIncomingBytes_(args);
  1277. this.myPacketOrderer.handleResponse(pN, data);
  1278. }, () => {
  1279. this.onClosed_();
  1280. }, this.urlFn);
  1281. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1282. //from cache.
  1283. const urlParams = {};
  1284. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1285. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1286. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1287. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1288. this.scriptTagHolder.uniqueCallbackIdentifier;
  1289. }
  1290. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1291. if (this.transportSessionId) {
  1292. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1293. }
  1294. if (this.lastSessionId) {
  1295. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1296. }
  1297. if (this.applicationId) {
  1298. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1299. }
  1300. if (this.appCheckToken) {
  1301. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1302. }
  1303. if (typeof location !== 'undefined' &&
  1304. location.hostname &&
  1305. FORGE_DOMAIN_RE.test(location.hostname)) {
  1306. urlParams[REFERER_PARAM] = FORGE_REF;
  1307. }
  1308. const connectURL = this.urlFn(urlParams);
  1309. this.log_('Connecting via long-poll to ' + connectURL);
  1310. this.scriptTagHolder.addTag(connectURL, () => {
  1311. /* do nothing */
  1312. });
  1313. });
  1314. }
  1315. /**
  1316. * Call this when a handshake has completed successfully and we want to consider the connection established
  1317. */
  1318. start() {
  1319. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1320. this.addDisconnectPingFrame(this.id, this.password);
  1321. }
  1322. /**
  1323. * Forces long polling to be considered as a potential transport
  1324. */
  1325. static forceAllow() {
  1326. BrowserPollConnection.forceAllow_ = true;
  1327. }
  1328. /**
  1329. * Forces longpolling to not be considered as a potential transport
  1330. */
  1331. static forceDisallow() {
  1332. BrowserPollConnection.forceDisallow_ = true;
  1333. }
  1334. // Static method, use string literal so it can be accessed in a generic way
  1335. static isAvailable() {
  1336. if (isNodeSdk()) {
  1337. return false;
  1338. }
  1339. else if (BrowserPollConnection.forceAllow_) {
  1340. return true;
  1341. }
  1342. else {
  1343. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1344. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1345. return (!BrowserPollConnection.forceDisallow_ &&
  1346. typeof document !== 'undefined' &&
  1347. document.createElement != null &&
  1348. !isChromeExtensionContentScript() &&
  1349. !isWindowsStoreApp());
  1350. }
  1351. }
  1352. /**
  1353. * No-op for polling
  1354. */
  1355. markConnectionHealthy() { }
  1356. /**
  1357. * Stops polling and cleans up the iframe
  1358. */
  1359. shutdown_() {
  1360. this.isClosed_ = true;
  1361. if (this.scriptTagHolder) {
  1362. this.scriptTagHolder.close();
  1363. this.scriptTagHolder = null;
  1364. }
  1365. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1366. if (this.myDisconnFrame) {
  1367. document.body.removeChild(this.myDisconnFrame);
  1368. this.myDisconnFrame = null;
  1369. }
  1370. if (this.connectTimeoutTimer_) {
  1371. clearTimeout(this.connectTimeoutTimer_);
  1372. this.connectTimeoutTimer_ = null;
  1373. }
  1374. }
  1375. /**
  1376. * Triggered when this transport is closed
  1377. */
  1378. onClosed_() {
  1379. if (!this.isClosed_) {
  1380. this.log_('Longpoll is closing itself');
  1381. this.shutdown_();
  1382. if (this.onDisconnect_) {
  1383. this.onDisconnect_(this.everConnected_);
  1384. this.onDisconnect_ = null;
  1385. }
  1386. }
  1387. }
  1388. /**
  1389. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1390. * that we've left.
  1391. */
  1392. close() {
  1393. if (!this.isClosed_) {
  1394. this.log_('Longpoll is being closed.');
  1395. this.shutdown_();
  1396. }
  1397. }
  1398. /**
  1399. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1400. * broken into chunks (since URLs have a small maximum length).
  1401. * @param data - The JSON data to transmit.
  1402. */
  1403. send(data) {
  1404. const dataStr = stringify(data);
  1405. this.bytesSent += dataStr.length;
  1406. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1407. //first, lets get the base64-encoded data
  1408. const base64data = base64Encode(dataStr);
  1409. //We can only fit a certain amount in each URL, so we need to split this request
  1410. //up into multiple pieces if it doesn't fit in one request.
  1411. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1412. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1413. //of segments so that we can reassemble the packet on the server.
  1414. for (let i = 0; i < dataSegs.length; i++) {
  1415. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1416. this.curSegmentNum++;
  1417. }
  1418. }
  1419. /**
  1420. * This is how we notify the server that we're leaving.
  1421. * We aren't able to send requests with DHTML on a window close event, but we can
  1422. * trigger XHR requests in some browsers (everything but Opera basically).
  1423. */
  1424. addDisconnectPingFrame(id, pw) {
  1425. if (isNodeSdk()) {
  1426. return;
  1427. }
  1428. this.myDisconnFrame = document.createElement('iframe');
  1429. const urlParams = {};
  1430. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1431. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1432. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1433. this.myDisconnFrame.src = this.urlFn(urlParams);
  1434. this.myDisconnFrame.style.display = 'none';
  1435. document.body.appendChild(this.myDisconnFrame);
  1436. }
  1437. /**
  1438. * Used to track the bytes received by this client
  1439. */
  1440. incrementIncomingBytes_(args) {
  1441. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1442. const bytesReceived = stringify(args).length;
  1443. this.bytesReceived += bytesReceived;
  1444. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1445. }
  1446. }
  1447. /*********************************************************************************************
  1448. * A wrapper around an iframe that is used as a long-polling script holder.
  1449. *********************************************************************************************/
  1450. class FirebaseIFrameScriptHolder {
  1451. /**
  1452. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1453. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1454. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1455. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1456. */
  1457. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1458. this.onDisconnect = onDisconnect;
  1459. this.urlFn = urlFn;
  1460. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1461. //problems in some browsers.
  1462. this.outstandingRequests = new Set();
  1463. //A queue of the pending segments waiting for transmission to the server.
  1464. this.pendingSegs = [];
  1465. //A serial number. We use this for two things:
  1466. // 1) A way to ensure the browser doesn't cache responses to polls
  1467. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1468. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1469. // JSONP code in the order it was added to the iframe.
  1470. this.currentSerial = Math.floor(Math.random() * 100000000);
  1471. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1472. // incoming data from the server that we're waiting for).
  1473. this.sendNewPolls = true;
  1474. if (!isNodeSdk()) {
  1475. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1476. //iframes where we put the long-polling script tags. We have two callbacks:
  1477. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1478. // 2) Message Callback - Triggered when new data arrives.
  1479. this.uniqueCallbackIdentifier = LUIDGenerator();
  1480. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1481. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1482. onMessageCB;
  1483. //Create an iframe for us to add script tags to.
  1484. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1485. // Set the iframe's contents.
  1486. let script = '';
  1487. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1488. // for ie9, but ie8 needs to do it again in the document itself.
  1489. if (this.myIFrame.src &&
  1490. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1491. const currentDomain = document.domain;
  1492. script = '<script>document.domain="' + currentDomain + '";</script>';
  1493. }
  1494. const iframeContents = '<html><body>' + script + '</body></html>';
  1495. try {
  1496. this.myIFrame.doc.open();
  1497. this.myIFrame.doc.write(iframeContents);
  1498. this.myIFrame.doc.close();
  1499. }
  1500. catch (e) {
  1501. log('frame writing exception');
  1502. if (e.stack) {
  1503. log(e.stack);
  1504. }
  1505. log(e);
  1506. }
  1507. }
  1508. else {
  1509. this.commandCB = commandCB;
  1510. this.onMessageCB = onMessageCB;
  1511. }
  1512. }
  1513. /**
  1514. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1515. * actually use.
  1516. */
  1517. static createIFrame_() {
  1518. const iframe = document.createElement('iframe');
  1519. iframe.style.display = 'none';
  1520. // This is necessary in order to initialize the document inside the iframe
  1521. if (document.body) {
  1522. document.body.appendChild(iframe);
  1523. try {
  1524. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1525. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1526. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1527. const a = iframe.contentWindow.document;
  1528. if (!a) {
  1529. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1530. log('No IE domain setting required');
  1531. }
  1532. }
  1533. catch (e) {
  1534. const domain = document.domain;
  1535. iframe.src =
  1536. "javascript:void((function(){document.open();document.domain='" +
  1537. domain +
  1538. "';document.close();})())";
  1539. }
  1540. }
  1541. else {
  1542. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1543. // never gets hit.
  1544. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1545. }
  1546. // Get the document of the iframe in a browser-specific way.
  1547. if (iframe.contentDocument) {
  1548. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1549. }
  1550. else if (iframe.contentWindow) {
  1551. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1552. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1553. }
  1554. else if (iframe.document) {
  1555. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1556. iframe.doc = iframe.document; //others?
  1557. }
  1558. return iframe;
  1559. }
  1560. /**
  1561. * Cancel all outstanding queries and remove the frame.
  1562. */
  1563. close() {
  1564. //Mark this iframe as dead, so no new requests are sent.
  1565. this.alive = false;
  1566. if (this.myIFrame) {
  1567. //We have to actually remove all of the html inside this iframe before removing it from the
  1568. //window, or IE will continue loading and executing the script tags we've already added, which
  1569. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1570. this.myIFrame.doc.body.textContent = '';
  1571. setTimeout(() => {
  1572. if (this.myIFrame !== null) {
  1573. document.body.removeChild(this.myIFrame);
  1574. this.myIFrame = null;
  1575. }
  1576. }, Math.floor(0));
  1577. }
  1578. // Protect from being called recursively.
  1579. const onDisconnect = this.onDisconnect;
  1580. if (onDisconnect) {
  1581. this.onDisconnect = null;
  1582. onDisconnect();
  1583. }
  1584. }
  1585. /**
  1586. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1587. * @param id - The ID of this connection
  1588. * @param pw - The password for this connection
  1589. */
  1590. startLongPoll(id, pw) {
  1591. this.myID = id;
  1592. this.myPW = pw;
  1593. this.alive = true;
  1594. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1595. while (this.newRequest_()) { }
  1596. }
  1597. /**
  1598. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1599. * too many outstanding requests and we are still alive.
  1600. *
  1601. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1602. * needed.
  1603. */
  1604. newRequest_() {
  1605. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1606. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1607. // close the old request.
  1608. if (this.alive &&
  1609. this.sendNewPolls &&
  1610. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1611. //construct our url
  1612. this.currentSerial++;
  1613. const urlParams = {};
  1614. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1615. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1616. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1617. let theURL = this.urlFn(urlParams);
  1618. //Now add as much data as we can.
  1619. let curDataString = '';
  1620. let i = 0;
  1621. while (this.pendingSegs.length > 0) {
  1622. //first, lets see if the next segment will fit.
  1623. const nextSeg = this.pendingSegs[0];
  1624. if (nextSeg.d.length +
  1625. SEG_HEADER_SIZE +
  1626. curDataString.length <=
  1627. MAX_URL_DATA_SIZE) {
  1628. //great, the segment will fit. Lets append it.
  1629. const theSeg = this.pendingSegs.shift();
  1630. curDataString =
  1631. curDataString +
  1632. '&' +
  1633. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1634. i +
  1635. '=' +
  1636. theSeg.seg +
  1637. '&' +
  1638. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1639. i +
  1640. '=' +
  1641. theSeg.ts +
  1642. '&' +
  1643. FIREBASE_LONGPOLL_DATA_PARAM +
  1644. i +
  1645. '=' +
  1646. theSeg.d;
  1647. i++;
  1648. }
  1649. else {
  1650. break;
  1651. }
  1652. }
  1653. theURL = theURL + curDataString;
  1654. this.addLongPollTag_(theURL, this.currentSerial);
  1655. return true;
  1656. }
  1657. else {
  1658. return false;
  1659. }
  1660. }
  1661. /**
  1662. * Queue a packet for transmission to the server.
  1663. * @param segnum - A sequential id for this packet segment used for reassembly
  1664. * @param totalsegs - The total number of segments in this packet
  1665. * @param data - The data for this segment.
  1666. */
  1667. enqueueSegment(segnum, totalsegs, data) {
  1668. //add this to the queue of segments to send.
  1669. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1670. //send the data immediately if there isn't already data being transmitted, unless
  1671. //startLongPoll hasn't been called yet.
  1672. if (this.alive) {
  1673. this.newRequest_();
  1674. }
  1675. }
  1676. /**
  1677. * Add a script tag for a regular long-poll request.
  1678. * @param url - The URL of the script tag.
  1679. * @param serial - The serial number of the request.
  1680. */
  1681. addLongPollTag_(url, serial) {
  1682. //remember that we sent this request.
  1683. this.outstandingRequests.add(serial);
  1684. const doNewRequest = () => {
  1685. this.outstandingRequests.delete(serial);
  1686. this.newRequest_();
  1687. };
  1688. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1689. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1690. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1691. const readyStateCB = () => {
  1692. // Request completed. Cancel the keepalive.
  1693. clearTimeout(keepaliveTimeout);
  1694. // Trigger a new request so we can continue receiving data.
  1695. doNewRequest();
  1696. };
  1697. this.addTag(url, readyStateCB);
  1698. }
  1699. /**
  1700. * Add an arbitrary script tag to the iframe.
  1701. * @param url - The URL for the script tag source.
  1702. * @param loadCB - A callback to be triggered once the script has loaded.
  1703. */
  1704. addTag(url, loadCB) {
  1705. if (isNodeSdk()) {
  1706. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1707. this.doNodeLongPoll(url, loadCB);
  1708. }
  1709. else {
  1710. setTimeout(() => {
  1711. try {
  1712. // if we're already closed, don't add this poll
  1713. if (!this.sendNewPolls) {
  1714. return;
  1715. }
  1716. const newScript = this.myIFrame.doc.createElement('script');
  1717. newScript.type = 'text/javascript';
  1718. newScript.async = true;
  1719. newScript.src = url;
  1720. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1721. newScript.onload = newScript.onreadystatechange =
  1722. function () {
  1723. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1724. const rstate = newScript.readyState;
  1725. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1726. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1727. newScript.onload = newScript.onreadystatechange = null;
  1728. if (newScript.parentNode) {
  1729. newScript.parentNode.removeChild(newScript);
  1730. }
  1731. loadCB();
  1732. }
  1733. };
  1734. newScript.onerror = () => {
  1735. log('Long-poll script failed to load: ' + url);
  1736. this.sendNewPolls = false;
  1737. this.close();
  1738. };
  1739. this.myIFrame.doc.body.appendChild(newScript);
  1740. }
  1741. catch (e) {
  1742. // TODO: we should make this error visible somehow
  1743. }
  1744. }, Math.floor(1));
  1745. }
  1746. }
  1747. }
  1748. /**
  1749. * @license
  1750. * Copyright 2017 Google LLC
  1751. *
  1752. * Licensed under the Apache License, Version 2.0 (the "License");
  1753. * you may not use this file except in compliance with the License.
  1754. * You may obtain a copy of the License at
  1755. *
  1756. * http://www.apache.org/licenses/LICENSE-2.0
  1757. *
  1758. * Unless required by applicable law or agreed to in writing, software
  1759. * distributed under the License is distributed on an "AS IS" BASIS,
  1760. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1761. * See the License for the specific language governing permissions and
  1762. * limitations under the License.
  1763. */
  1764. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1765. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1766. let WebSocketImpl = null;
  1767. if (typeof MozWebSocket !== 'undefined') {
  1768. WebSocketImpl = MozWebSocket;
  1769. }
  1770. else if (typeof WebSocket !== 'undefined') {
  1771. WebSocketImpl = WebSocket;
  1772. }
  1773. /**
  1774. * Create a new websocket connection with the given callbacks.
  1775. */
  1776. class WebSocketConnection {
  1777. /**
  1778. * @param connId identifier for this transport
  1779. * @param repoInfo The info for the websocket endpoint.
  1780. * @param applicationId The Firebase App ID for this project.
  1781. * @param appCheckToken The App Check Token for this client.
  1782. * @param authToken The Auth Token for this client.
  1783. * @param transportSessionId Optional transportSessionId if this is connecting
  1784. * to an existing transport session
  1785. * @param lastSessionId Optional lastSessionId if there was a previous
  1786. * connection
  1787. */
  1788. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1789. this.connId = connId;
  1790. this.applicationId = applicationId;
  1791. this.appCheckToken = appCheckToken;
  1792. this.authToken = authToken;
  1793. this.keepaliveTimer = null;
  1794. this.frames = null;
  1795. this.totalFrames = 0;
  1796. this.bytesSent = 0;
  1797. this.bytesReceived = 0;
  1798. this.log_ = logWrapper(this.connId);
  1799. this.stats_ = statsManagerGetCollection(repoInfo);
  1800. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1801. this.nodeAdmin = repoInfo.nodeAdmin;
  1802. }
  1803. /**
  1804. * @param repoInfo - The info for the websocket endpoint.
  1805. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1806. * session
  1807. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1808. * @returns connection url
  1809. */
  1810. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1811. const urlParams = {};
  1812. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1813. if (!isNodeSdk() &&
  1814. typeof location !== 'undefined' &&
  1815. location.hostname &&
  1816. FORGE_DOMAIN_RE.test(location.hostname)) {
  1817. urlParams[REFERER_PARAM] = FORGE_REF;
  1818. }
  1819. if (transportSessionId) {
  1820. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1821. }
  1822. if (lastSessionId) {
  1823. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1824. }
  1825. if (appCheckToken) {
  1826. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1827. }
  1828. if (applicationId) {
  1829. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1830. }
  1831. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1832. }
  1833. /**
  1834. * @param onMessage - Callback when messages arrive
  1835. * @param onDisconnect - Callback with connection lost.
  1836. */
  1837. open(onMessage, onDisconnect) {
  1838. this.onDisconnect = onDisconnect;
  1839. this.onMessage = onMessage;
  1840. this.log_('Websocket connecting to ' + this.connURL);
  1841. this.everConnected_ = false;
  1842. // Assume failure until proven otherwise.
  1843. PersistentStorage.set('previous_websocket_failure', true);
  1844. try {
  1845. let options;
  1846. if (isNodeSdk()) {
  1847. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1848. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1849. options = {
  1850. headers: {
  1851. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1852. 'X-Firebase-GMPID': this.applicationId || ''
  1853. }
  1854. };
  1855. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1856. // Note that we send the credentials here even if they aren't admin credentials, which is
  1857. // not a problem.
  1858. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1859. // through the websocket connection once it is established.
  1860. if (this.authToken) {
  1861. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1862. }
  1863. if (this.appCheckToken) {
  1864. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1865. }
  1866. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1867. const env = process['env'];
  1868. const proxy = this.connURL.indexOf('wss://') === 0
  1869. ? env['HTTPS_PROXY'] || env['https_proxy']
  1870. : env['HTTP_PROXY'] || env['http_proxy'];
  1871. if (proxy) {
  1872. options['proxy'] = { origin: proxy };
  1873. }
  1874. }
  1875. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1876. }
  1877. catch (e) {
  1878. this.log_('Error instantiating WebSocket.');
  1879. const error = e.message || e.data;
  1880. if (error) {
  1881. this.log_(error);
  1882. }
  1883. this.onClosed_();
  1884. return;
  1885. }
  1886. this.mySock.onopen = () => {
  1887. this.log_('Websocket connected.');
  1888. this.everConnected_ = true;
  1889. };
  1890. this.mySock.onclose = () => {
  1891. this.log_('Websocket connection was disconnected.');
  1892. this.mySock = null;
  1893. this.onClosed_();
  1894. };
  1895. this.mySock.onmessage = m => {
  1896. this.handleIncomingFrame(m);
  1897. };
  1898. this.mySock.onerror = e => {
  1899. this.log_('WebSocket error. Closing connection.');
  1900. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1901. const error = e.message || e.data;
  1902. if (error) {
  1903. this.log_(error);
  1904. }
  1905. this.onClosed_();
  1906. };
  1907. }
  1908. /**
  1909. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1910. */
  1911. start() { }
  1912. static forceDisallow() {
  1913. WebSocketConnection.forceDisallow_ = true;
  1914. }
  1915. static isAvailable() {
  1916. let isOldAndroid = false;
  1917. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1918. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1919. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1920. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1921. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1922. isOldAndroid = true;
  1923. }
  1924. }
  1925. }
  1926. return (!isOldAndroid &&
  1927. WebSocketImpl !== null &&
  1928. !WebSocketConnection.forceDisallow_);
  1929. }
  1930. /**
  1931. * Returns true if we previously failed to connect with this transport.
  1932. */
  1933. static previouslyFailed() {
  1934. // If our persistent storage is actually only in-memory storage,
  1935. // we default to assuming that it previously failed to be safe.
  1936. return (PersistentStorage.isInMemoryStorage ||
  1937. PersistentStorage.get('previous_websocket_failure') === true);
  1938. }
  1939. markConnectionHealthy() {
  1940. PersistentStorage.remove('previous_websocket_failure');
  1941. }
  1942. appendFrame_(data) {
  1943. this.frames.push(data);
  1944. if (this.frames.length === this.totalFrames) {
  1945. const fullMess = this.frames.join('');
  1946. this.frames = null;
  1947. const jsonMess = jsonEval(fullMess);
  1948. //handle the message
  1949. this.onMessage(jsonMess);
  1950. }
  1951. }
  1952. /**
  1953. * @param frameCount - The number of frames we are expecting from the server
  1954. */
  1955. handleNewFrameCount_(frameCount) {
  1956. this.totalFrames = frameCount;
  1957. this.frames = [];
  1958. }
  1959. /**
  1960. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1961. * @returns Any remaining data to be process, or null if there is none
  1962. */
  1963. extractFrameCount_(data) {
  1964. assert(this.frames === null, 'We already have a frame buffer');
  1965. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1966. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1967. if (data.length <= 6) {
  1968. const frameCount = Number(data);
  1969. if (!isNaN(frameCount)) {
  1970. this.handleNewFrameCount_(frameCount);
  1971. return null;
  1972. }
  1973. }
  1974. this.handleNewFrameCount_(1);
  1975. return data;
  1976. }
  1977. /**
  1978. * Process a websocket frame that has arrived from the server.
  1979. * @param mess - The frame data
  1980. */
  1981. handleIncomingFrame(mess) {
  1982. if (this.mySock === null) {
  1983. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1984. }
  1985. const data = mess['data'];
  1986. this.bytesReceived += data.length;
  1987. this.stats_.incrementCounter('bytes_received', data.length);
  1988. this.resetKeepAlive();
  1989. if (this.frames !== null) {
  1990. // we're buffering
  1991. this.appendFrame_(data);
  1992. }
  1993. else {
  1994. // try to parse out a frame count, otherwise, assume 1 and process it
  1995. const remainingData = this.extractFrameCount_(data);
  1996. if (remainingData !== null) {
  1997. this.appendFrame_(remainingData);
  1998. }
  1999. }
  2000. }
  2001. /**
  2002. * Send a message to the server
  2003. * @param data - The JSON object to transmit
  2004. */
  2005. send(data) {
  2006. this.resetKeepAlive();
  2007. const dataStr = stringify(data);
  2008. this.bytesSent += dataStr.length;
  2009. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2010. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2011. //up into multiple pieces if it doesn't fit in one request.
  2012. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2013. //Send the length header
  2014. if (dataSegs.length > 1) {
  2015. this.sendString_(String(dataSegs.length));
  2016. }
  2017. //Send the actual data in segments.
  2018. for (let i = 0; i < dataSegs.length; i++) {
  2019. this.sendString_(dataSegs[i]);
  2020. }
  2021. }
  2022. shutdown_() {
  2023. this.isClosed_ = true;
  2024. if (this.keepaliveTimer) {
  2025. clearInterval(this.keepaliveTimer);
  2026. this.keepaliveTimer = null;
  2027. }
  2028. if (this.mySock) {
  2029. this.mySock.close();
  2030. this.mySock = null;
  2031. }
  2032. }
  2033. onClosed_() {
  2034. if (!this.isClosed_) {
  2035. this.log_('WebSocket is closing itself');
  2036. this.shutdown_();
  2037. // since this is an internal close, trigger the close listener
  2038. if (this.onDisconnect) {
  2039. this.onDisconnect(this.everConnected_);
  2040. this.onDisconnect = null;
  2041. }
  2042. }
  2043. }
  2044. /**
  2045. * External-facing close handler.
  2046. * Close the websocket and kill the connection.
  2047. */
  2048. close() {
  2049. if (!this.isClosed_) {
  2050. this.log_('WebSocket is being closed');
  2051. this.shutdown_();
  2052. }
  2053. }
  2054. /**
  2055. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2056. * the last activity.
  2057. */
  2058. resetKeepAlive() {
  2059. clearInterval(this.keepaliveTimer);
  2060. this.keepaliveTimer = setInterval(() => {
  2061. //If there has been no websocket activity for a while, send a no-op
  2062. if (this.mySock) {
  2063. this.sendString_('0');
  2064. }
  2065. this.resetKeepAlive();
  2066. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2067. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2068. }
  2069. /**
  2070. * Send a string over the websocket.
  2071. *
  2072. * @param str - String to send.
  2073. */
  2074. sendString_(str) {
  2075. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2076. // calls for some unknown reason. We treat these as an error and disconnect.
  2077. // See https://app.asana.com/0/58926111402292/68021340250410
  2078. try {
  2079. this.mySock.send(str);
  2080. }
  2081. catch (e) {
  2082. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2083. setTimeout(this.onClosed_.bind(this), 0);
  2084. }
  2085. }
  2086. }
  2087. /**
  2088. * Number of response before we consider the connection "healthy."
  2089. */
  2090. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2091. /**
  2092. * Time to wait for the connection te become healthy before giving up.
  2093. */
  2094. WebSocketConnection.healthyTimeout = 30000;
  2095. /**
  2096. * @license
  2097. * Copyright 2017 Google LLC
  2098. *
  2099. * Licensed under the Apache License, Version 2.0 (the "License");
  2100. * you may not use this file except in compliance with the License.
  2101. * You may obtain a copy of the License at
  2102. *
  2103. * http://www.apache.org/licenses/LICENSE-2.0
  2104. *
  2105. * Unless required by applicable law or agreed to in writing, software
  2106. * distributed under the License is distributed on an "AS IS" BASIS,
  2107. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2108. * See the License for the specific language governing permissions and
  2109. * limitations under the License.
  2110. */
  2111. /**
  2112. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2113. * lifecycle.
  2114. *
  2115. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2116. * they are available.
  2117. */
  2118. class TransportManager {
  2119. /**
  2120. * @param repoInfo - Metadata around the namespace we're connecting to
  2121. */
  2122. constructor(repoInfo) {
  2123. this.initTransports_(repoInfo);
  2124. }
  2125. static get ALL_TRANSPORTS() {
  2126. return [BrowserPollConnection, WebSocketConnection];
  2127. }
  2128. /**
  2129. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2130. * TransportManager has already set up transports_
  2131. */
  2132. static get IS_TRANSPORT_INITIALIZED() {
  2133. return this.globalTransportInitialized_;
  2134. }
  2135. initTransports_(repoInfo) {
  2136. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2137. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2138. if (repoInfo.webSocketOnly) {
  2139. if (!isWebSocketsAvailable) {
  2140. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2141. }
  2142. isSkipPollConnection = true;
  2143. }
  2144. if (isSkipPollConnection) {
  2145. this.transports_ = [WebSocketConnection];
  2146. }
  2147. else {
  2148. const transports = (this.transports_ = []);
  2149. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2150. if (transport && transport['isAvailable']()) {
  2151. transports.push(transport);
  2152. }
  2153. }
  2154. TransportManager.globalTransportInitialized_ = true;
  2155. }
  2156. }
  2157. /**
  2158. * @returns The constructor for the initial transport to use
  2159. */
  2160. initialTransport() {
  2161. if (this.transports_.length > 0) {
  2162. return this.transports_[0];
  2163. }
  2164. else {
  2165. throw new Error('No transports available');
  2166. }
  2167. }
  2168. /**
  2169. * @returns The constructor for the next transport, or null
  2170. */
  2171. upgradeTransport() {
  2172. if (this.transports_.length > 1) {
  2173. return this.transports_[1];
  2174. }
  2175. else {
  2176. return null;
  2177. }
  2178. }
  2179. }
  2180. // Keeps track of whether the TransportManager has already chosen a transport to use
  2181. TransportManager.globalTransportInitialized_ = false;
  2182. /**
  2183. * @license
  2184. * Copyright 2017 Google LLC
  2185. *
  2186. * Licensed under the Apache License, Version 2.0 (the "License");
  2187. * you may not use this file except in compliance with the License.
  2188. * You may obtain a copy of the License at
  2189. *
  2190. * http://www.apache.org/licenses/LICENSE-2.0
  2191. *
  2192. * Unless required by applicable law or agreed to in writing, software
  2193. * distributed under the License is distributed on an "AS IS" BASIS,
  2194. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2195. * See the License for the specific language governing permissions and
  2196. * limitations under the License.
  2197. */
  2198. // Abort upgrade attempt if it takes longer than 60s.
  2199. const UPGRADE_TIMEOUT = 60000;
  2200. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2201. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2202. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2203. // 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)
  2204. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2205. // but we've sent/received enough bytes, we don't cancel the connection.
  2206. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2207. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2208. const MESSAGE_TYPE = 't';
  2209. const MESSAGE_DATA = 'd';
  2210. const CONTROL_SHUTDOWN = 's';
  2211. const CONTROL_RESET = 'r';
  2212. const CONTROL_ERROR = 'e';
  2213. const CONTROL_PONG = 'o';
  2214. const SWITCH_ACK = 'a';
  2215. const END_TRANSMISSION = 'n';
  2216. const PING = 'p';
  2217. const SERVER_HELLO = 'h';
  2218. /**
  2219. * Creates a new real-time connection to the server using whichever method works
  2220. * best in the current browser.
  2221. */
  2222. class Connection {
  2223. /**
  2224. * @param id - an id for this connection
  2225. * @param repoInfo_ - the info for the endpoint to connect to
  2226. * @param applicationId_ - the Firebase App ID for this project
  2227. * @param appCheckToken_ - The App Check Token for this device.
  2228. * @param authToken_ - The auth token for this session.
  2229. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2230. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2231. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2232. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2233. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2234. */
  2235. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2236. this.id = id;
  2237. this.repoInfo_ = repoInfo_;
  2238. this.applicationId_ = applicationId_;
  2239. this.appCheckToken_ = appCheckToken_;
  2240. this.authToken_ = authToken_;
  2241. this.onMessage_ = onMessage_;
  2242. this.onReady_ = onReady_;
  2243. this.onDisconnect_ = onDisconnect_;
  2244. this.onKill_ = onKill_;
  2245. this.lastSessionId = lastSessionId;
  2246. this.connectionCount = 0;
  2247. this.pendingDataMessages = [];
  2248. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2249. this.log_ = logWrapper('c:' + this.id + ':');
  2250. this.transportManager_ = new TransportManager(repoInfo_);
  2251. this.log_('Connection created');
  2252. this.start_();
  2253. }
  2254. /**
  2255. * Starts a connection attempt
  2256. */
  2257. start_() {
  2258. const conn = this.transportManager_.initialTransport();
  2259. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2260. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2261. // can consider the transport healthy.
  2262. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2263. const onMessageReceived = this.connReceiver_(this.conn_);
  2264. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2265. this.tx_ = this.conn_;
  2266. this.rx_ = this.conn_;
  2267. this.secondaryConn_ = null;
  2268. this.isHealthy_ = false;
  2269. /*
  2270. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2271. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2272. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2273. * still have the context of your originating frame.
  2274. */
  2275. setTimeout(() => {
  2276. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2277. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2278. }, Math.floor(0));
  2279. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2280. if (healthyTimeoutMS > 0) {
  2281. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2282. this.healthyTimeout_ = null;
  2283. if (!this.isHealthy_) {
  2284. if (this.conn_ &&
  2285. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2286. this.log_('Connection exceeded healthy timeout but has received ' +
  2287. this.conn_.bytesReceived +
  2288. ' bytes. Marking connection healthy.');
  2289. this.isHealthy_ = true;
  2290. this.conn_.markConnectionHealthy();
  2291. }
  2292. else if (this.conn_ &&
  2293. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2294. this.log_('Connection exceeded healthy timeout but has sent ' +
  2295. this.conn_.bytesSent +
  2296. ' bytes. Leaving connection alive.');
  2297. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2298. // the server.
  2299. }
  2300. else {
  2301. this.log_('Closing unhealthy connection after timeout.');
  2302. this.close();
  2303. }
  2304. }
  2305. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2306. }, Math.floor(healthyTimeoutMS));
  2307. }
  2308. }
  2309. nextTransportId_() {
  2310. return 'c:' + this.id + ':' + this.connectionCount++;
  2311. }
  2312. disconnReceiver_(conn) {
  2313. return everConnected => {
  2314. if (conn === this.conn_) {
  2315. this.onConnectionLost_(everConnected);
  2316. }
  2317. else if (conn === this.secondaryConn_) {
  2318. this.log_('Secondary connection lost.');
  2319. this.onSecondaryConnectionLost_();
  2320. }
  2321. else {
  2322. this.log_('closing an old connection');
  2323. }
  2324. };
  2325. }
  2326. connReceiver_(conn) {
  2327. return (message) => {
  2328. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2329. if (conn === this.rx_) {
  2330. this.onPrimaryMessageReceived_(message);
  2331. }
  2332. else if (conn === this.secondaryConn_) {
  2333. this.onSecondaryMessageReceived_(message);
  2334. }
  2335. else {
  2336. this.log_('message on old connection');
  2337. }
  2338. }
  2339. };
  2340. }
  2341. /**
  2342. * @param dataMsg - An arbitrary data message to be sent to the server
  2343. */
  2344. sendRequest(dataMsg) {
  2345. // wrap in a data message envelope and send it on
  2346. const msg = { t: 'd', d: dataMsg };
  2347. this.sendData_(msg);
  2348. }
  2349. tryCleanupConnection() {
  2350. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2351. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2352. this.conn_ = this.secondaryConn_;
  2353. this.secondaryConn_ = null;
  2354. // the server will shutdown the old connection
  2355. }
  2356. }
  2357. onSecondaryControl_(controlData) {
  2358. if (MESSAGE_TYPE in controlData) {
  2359. const cmd = controlData[MESSAGE_TYPE];
  2360. if (cmd === SWITCH_ACK) {
  2361. this.upgradeIfSecondaryHealthy_();
  2362. }
  2363. else if (cmd === CONTROL_RESET) {
  2364. // Most likely the session wasn't valid. Abandon the switch attempt
  2365. this.log_('Got a reset on secondary, closing it');
  2366. this.secondaryConn_.close();
  2367. // If we were already using this connection for something, than we need to fully close
  2368. if (this.tx_ === this.secondaryConn_ ||
  2369. this.rx_ === this.secondaryConn_) {
  2370. this.close();
  2371. }
  2372. }
  2373. else if (cmd === CONTROL_PONG) {
  2374. this.log_('got pong on secondary.');
  2375. this.secondaryResponsesRequired_--;
  2376. this.upgradeIfSecondaryHealthy_();
  2377. }
  2378. }
  2379. }
  2380. onSecondaryMessageReceived_(parsedData) {
  2381. const layer = requireKey('t', parsedData);
  2382. const data = requireKey('d', parsedData);
  2383. if (layer === 'c') {
  2384. this.onSecondaryControl_(data);
  2385. }
  2386. else if (layer === 'd') {
  2387. // got a data message, but we're still second connection. Need to buffer it up
  2388. this.pendingDataMessages.push(data);
  2389. }
  2390. else {
  2391. throw new Error('Unknown protocol layer: ' + layer);
  2392. }
  2393. }
  2394. upgradeIfSecondaryHealthy_() {
  2395. if (this.secondaryResponsesRequired_ <= 0) {
  2396. this.log_('Secondary connection is healthy.');
  2397. this.isHealthy_ = true;
  2398. this.secondaryConn_.markConnectionHealthy();
  2399. this.proceedWithUpgrade_();
  2400. }
  2401. else {
  2402. // Send a ping to make sure the connection is healthy.
  2403. this.log_('sending ping on secondary.');
  2404. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2405. }
  2406. }
  2407. proceedWithUpgrade_() {
  2408. // tell this connection to consider itself open
  2409. this.secondaryConn_.start();
  2410. // send ack
  2411. this.log_('sending client ack on secondary');
  2412. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2413. // send end packet on primary transport, switch to sending on this one
  2414. // can receive on this one, buffer responses until end received on primary transport
  2415. this.log_('Ending transmission on primary');
  2416. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2417. this.tx_ = this.secondaryConn_;
  2418. this.tryCleanupConnection();
  2419. }
  2420. onPrimaryMessageReceived_(parsedData) {
  2421. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2422. const layer = requireKey('t', parsedData);
  2423. const data = requireKey('d', parsedData);
  2424. if (layer === 'c') {
  2425. this.onControl_(data);
  2426. }
  2427. else if (layer === 'd') {
  2428. this.onDataMessage_(data);
  2429. }
  2430. }
  2431. onDataMessage_(message) {
  2432. this.onPrimaryResponse_();
  2433. // We don't do anything with data messages, just kick them up a level
  2434. this.onMessage_(message);
  2435. }
  2436. onPrimaryResponse_() {
  2437. if (!this.isHealthy_) {
  2438. this.primaryResponsesRequired_--;
  2439. if (this.primaryResponsesRequired_ <= 0) {
  2440. this.log_('Primary connection is healthy.');
  2441. this.isHealthy_ = true;
  2442. this.conn_.markConnectionHealthy();
  2443. }
  2444. }
  2445. }
  2446. onControl_(controlData) {
  2447. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2448. if (MESSAGE_DATA in controlData) {
  2449. const payload = controlData[MESSAGE_DATA];
  2450. if (cmd === SERVER_HELLO) {
  2451. this.onHandshake_(payload);
  2452. }
  2453. else if (cmd === END_TRANSMISSION) {
  2454. this.log_('recvd end transmission on primary');
  2455. this.rx_ = this.secondaryConn_;
  2456. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2457. this.onDataMessage_(this.pendingDataMessages[i]);
  2458. }
  2459. this.pendingDataMessages = [];
  2460. this.tryCleanupConnection();
  2461. }
  2462. else if (cmd === CONTROL_SHUTDOWN) {
  2463. // This was previously the 'onKill' callback passed to the lower-level connection
  2464. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2465. this.onConnectionShutdown_(payload);
  2466. }
  2467. else if (cmd === CONTROL_RESET) {
  2468. // payload in this case is the host we should contact
  2469. this.onReset_(payload);
  2470. }
  2471. else if (cmd === CONTROL_ERROR) {
  2472. error('Server Error: ' + payload);
  2473. }
  2474. else if (cmd === CONTROL_PONG) {
  2475. this.log_('got pong on primary.');
  2476. this.onPrimaryResponse_();
  2477. this.sendPingOnPrimaryIfNecessary_();
  2478. }
  2479. else {
  2480. error('Unknown control packet command: ' + cmd);
  2481. }
  2482. }
  2483. }
  2484. /**
  2485. * @param handshake - The handshake data returned from the server
  2486. */
  2487. onHandshake_(handshake) {
  2488. const timestamp = handshake.ts;
  2489. const version = handshake.v;
  2490. const host = handshake.h;
  2491. this.sessionId = handshake.s;
  2492. this.repoInfo_.host = host;
  2493. // if we've already closed the connection, then don't bother trying to progress further
  2494. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2495. this.conn_.start();
  2496. this.onConnectionEstablished_(this.conn_, timestamp);
  2497. if (PROTOCOL_VERSION !== version) {
  2498. warn('Protocol version mismatch detected');
  2499. }
  2500. // TODO: do we want to upgrade? when? maybe a delay?
  2501. this.tryStartUpgrade_();
  2502. }
  2503. }
  2504. tryStartUpgrade_() {
  2505. const conn = this.transportManager_.upgradeTransport();
  2506. if (conn) {
  2507. this.startUpgrade_(conn);
  2508. }
  2509. }
  2510. startUpgrade_(conn) {
  2511. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2512. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2513. // can consider the transport healthy.
  2514. this.secondaryResponsesRequired_ =
  2515. conn['responsesRequiredToBeHealthy'] || 0;
  2516. const onMessage = this.connReceiver_(this.secondaryConn_);
  2517. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2518. this.secondaryConn_.open(onMessage, onDisconnect);
  2519. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2520. setTimeoutNonBlocking(() => {
  2521. if (this.secondaryConn_) {
  2522. this.log_('Timed out trying to upgrade.');
  2523. this.secondaryConn_.close();
  2524. }
  2525. }, Math.floor(UPGRADE_TIMEOUT));
  2526. }
  2527. onReset_(host) {
  2528. this.log_('Reset packet received. New host: ' + host);
  2529. this.repoInfo_.host = host;
  2530. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2531. // We don't currently support resets after the connection has already been established
  2532. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2533. this.close();
  2534. }
  2535. else {
  2536. // Close whatever connections we have open and start again.
  2537. this.closeConnections_();
  2538. this.start_();
  2539. }
  2540. }
  2541. onConnectionEstablished_(conn, timestamp) {
  2542. this.log_('Realtime connection established.');
  2543. this.conn_ = conn;
  2544. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2545. if (this.onReady_) {
  2546. this.onReady_(timestamp, this.sessionId);
  2547. this.onReady_ = null;
  2548. }
  2549. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2550. // send some pings.
  2551. if (this.primaryResponsesRequired_ === 0) {
  2552. this.log_('Primary connection is healthy.');
  2553. this.isHealthy_ = true;
  2554. }
  2555. else {
  2556. setTimeoutNonBlocking(() => {
  2557. this.sendPingOnPrimaryIfNecessary_();
  2558. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2559. }
  2560. }
  2561. sendPingOnPrimaryIfNecessary_() {
  2562. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2563. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2564. this.log_('sending ping on primary.');
  2565. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2566. }
  2567. }
  2568. onSecondaryConnectionLost_() {
  2569. const conn = this.secondaryConn_;
  2570. this.secondaryConn_ = null;
  2571. if (this.tx_ === conn || this.rx_ === conn) {
  2572. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2573. this.close();
  2574. }
  2575. }
  2576. /**
  2577. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2578. * we should flush the host cache
  2579. */
  2580. onConnectionLost_(everConnected) {
  2581. this.conn_ = null;
  2582. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2583. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2584. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2585. this.log_('Realtime connection failed.');
  2586. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2587. if (this.repoInfo_.isCacheableHost()) {
  2588. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2589. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2590. this.repoInfo_.internalHost = this.repoInfo_.host;
  2591. }
  2592. }
  2593. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2594. this.log_('Realtime connection lost.');
  2595. }
  2596. this.close();
  2597. }
  2598. onConnectionShutdown_(reason) {
  2599. this.log_('Connection shutdown command received. Shutting down...');
  2600. if (this.onKill_) {
  2601. this.onKill_(reason);
  2602. this.onKill_ = null;
  2603. }
  2604. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2605. // so clear the callback.
  2606. this.onDisconnect_ = null;
  2607. this.close();
  2608. }
  2609. sendData_(data) {
  2610. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2611. throw 'Connection is not connected';
  2612. }
  2613. else {
  2614. this.tx_.send(data);
  2615. }
  2616. }
  2617. /**
  2618. * Cleans up this connection, calling the appropriate callbacks
  2619. */
  2620. close() {
  2621. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2622. this.log_('Closing realtime connection.');
  2623. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2624. this.closeConnections_();
  2625. if (this.onDisconnect_) {
  2626. this.onDisconnect_();
  2627. this.onDisconnect_ = null;
  2628. }
  2629. }
  2630. }
  2631. closeConnections_() {
  2632. this.log_('Shutting down all connections');
  2633. if (this.conn_) {
  2634. this.conn_.close();
  2635. this.conn_ = null;
  2636. }
  2637. if (this.secondaryConn_) {
  2638. this.secondaryConn_.close();
  2639. this.secondaryConn_ = null;
  2640. }
  2641. if (this.healthyTimeout_) {
  2642. clearTimeout(this.healthyTimeout_);
  2643. this.healthyTimeout_ = null;
  2644. }
  2645. }
  2646. }
  2647. /**
  2648. * @license
  2649. * Copyright 2017 Google LLC
  2650. *
  2651. * Licensed under the Apache License, Version 2.0 (the "License");
  2652. * you may not use this file except in compliance with the License.
  2653. * You may obtain a copy of the License at
  2654. *
  2655. * http://www.apache.org/licenses/LICENSE-2.0
  2656. *
  2657. * Unless required by applicable law or agreed to in writing, software
  2658. * distributed under the License is distributed on an "AS IS" BASIS,
  2659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2660. * See the License for the specific language governing permissions and
  2661. * limitations under the License.
  2662. */
  2663. /**
  2664. * Interface defining the set of actions that can be performed against the Firebase server
  2665. * (basically corresponds to our wire protocol).
  2666. *
  2667. * @interface
  2668. */
  2669. class ServerActions {
  2670. put(pathString, data, onComplete, hash) { }
  2671. merge(pathString, data, onComplete, hash) { }
  2672. /**
  2673. * Refreshes the auth token for the current connection.
  2674. * @param token - The authentication token
  2675. */
  2676. refreshAuthToken(token) { }
  2677. /**
  2678. * Refreshes the app check token for the current connection.
  2679. * @param token The app check token
  2680. */
  2681. refreshAppCheckToken(token) { }
  2682. onDisconnectPut(pathString, data, onComplete) { }
  2683. onDisconnectMerge(pathString, data, onComplete) { }
  2684. onDisconnectCancel(pathString, onComplete) { }
  2685. reportStats(stats) { }
  2686. }
  2687. /**
  2688. * @license
  2689. * Copyright 2017 Google LLC
  2690. *
  2691. * Licensed under the Apache License, Version 2.0 (the "License");
  2692. * you may not use this file except in compliance with the License.
  2693. * You may obtain a copy of the License at
  2694. *
  2695. * http://www.apache.org/licenses/LICENSE-2.0
  2696. *
  2697. * Unless required by applicable law or agreed to in writing, software
  2698. * distributed under the License is distributed on an "AS IS" BASIS,
  2699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2700. * See the License for the specific language governing permissions and
  2701. * limitations under the License.
  2702. */
  2703. /**
  2704. * Base class to be used if you want to emit events. Call the constructor with
  2705. * the set of allowed event names.
  2706. */
  2707. class EventEmitter {
  2708. constructor(allowedEvents_) {
  2709. this.allowedEvents_ = allowedEvents_;
  2710. this.listeners_ = {};
  2711. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2712. }
  2713. /**
  2714. * To be called by derived classes to trigger events.
  2715. */
  2716. trigger(eventType, ...varArgs) {
  2717. if (Array.isArray(this.listeners_[eventType])) {
  2718. // Clone the list, since callbacks could add/remove listeners.
  2719. const listeners = [...this.listeners_[eventType]];
  2720. for (let i = 0; i < listeners.length; i++) {
  2721. listeners[i].callback.apply(listeners[i].context, varArgs);
  2722. }
  2723. }
  2724. }
  2725. on(eventType, callback, context) {
  2726. this.validateEventType_(eventType);
  2727. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2728. this.listeners_[eventType].push({ callback, context });
  2729. const eventData = this.getInitialEvent(eventType);
  2730. if (eventData) {
  2731. callback.apply(context, eventData);
  2732. }
  2733. }
  2734. off(eventType, callback, context) {
  2735. this.validateEventType_(eventType);
  2736. const listeners = this.listeners_[eventType] || [];
  2737. for (let i = 0; i < listeners.length; i++) {
  2738. if (listeners[i].callback === callback &&
  2739. (!context || context === listeners[i].context)) {
  2740. listeners.splice(i, 1);
  2741. return;
  2742. }
  2743. }
  2744. }
  2745. validateEventType_(eventType) {
  2746. assert(this.allowedEvents_.find(et => {
  2747. return et === eventType;
  2748. }), 'Unknown event: ' + eventType);
  2749. }
  2750. }
  2751. /**
  2752. * @license
  2753. * Copyright 2017 Google LLC
  2754. *
  2755. * Licensed under the Apache License, Version 2.0 (the "License");
  2756. * you may not use this file except in compliance with the License.
  2757. * You may obtain a copy of the License at
  2758. *
  2759. * http://www.apache.org/licenses/LICENSE-2.0
  2760. *
  2761. * Unless required by applicable law or agreed to in writing, software
  2762. * distributed under the License is distributed on an "AS IS" BASIS,
  2763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2764. * See the License for the specific language governing permissions and
  2765. * limitations under the License.
  2766. */
  2767. /**
  2768. * Monitors online state (as reported by window.online/offline events).
  2769. *
  2770. * The expectation is that this could have many false positives (thinks we are online
  2771. * when we're not), but no false negatives. So we can safely use it to determine when
  2772. * we definitely cannot reach the internet.
  2773. */
  2774. class OnlineMonitor extends EventEmitter {
  2775. constructor() {
  2776. super(['online']);
  2777. this.online_ = true;
  2778. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2779. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2780. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2781. // for Cordova.
  2782. if (typeof window !== 'undefined' &&
  2783. typeof window.addEventListener !== 'undefined' &&
  2784. !isMobileCordova()) {
  2785. window.addEventListener('online', () => {
  2786. if (!this.online_) {
  2787. this.online_ = true;
  2788. this.trigger('online', true);
  2789. }
  2790. }, false);
  2791. window.addEventListener('offline', () => {
  2792. if (this.online_) {
  2793. this.online_ = false;
  2794. this.trigger('online', false);
  2795. }
  2796. }, false);
  2797. }
  2798. }
  2799. static getInstance() {
  2800. return new OnlineMonitor();
  2801. }
  2802. getInitialEvent(eventType) {
  2803. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2804. return [this.online_];
  2805. }
  2806. currentlyOnline() {
  2807. return this.online_;
  2808. }
  2809. }
  2810. /**
  2811. * @license
  2812. * Copyright 2017 Google LLC
  2813. *
  2814. * Licensed under the Apache License, Version 2.0 (the "License");
  2815. * you may not use this file except in compliance with the License.
  2816. * You may obtain a copy of the License at
  2817. *
  2818. * http://www.apache.org/licenses/LICENSE-2.0
  2819. *
  2820. * Unless required by applicable law or agreed to in writing, software
  2821. * distributed under the License is distributed on an "AS IS" BASIS,
  2822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2823. * See the License for the specific language governing permissions and
  2824. * limitations under the License.
  2825. */
  2826. /** Maximum key depth. */
  2827. const MAX_PATH_DEPTH = 32;
  2828. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2829. const MAX_PATH_LENGTH_BYTES = 768;
  2830. /**
  2831. * An immutable object representing a parsed path. It's immutable so that you
  2832. * can pass them around to other functions without worrying about them changing
  2833. * it.
  2834. */
  2835. class Path {
  2836. /**
  2837. * @param pathOrString - Path string to parse, or another path, or the raw
  2838. * tokens array
  2839. */
  2840. constructor(pathOrString, pieceNum) {
  2841. if (pieceNum === void 0) {
  2842. this.pieces_ = pathOrString.split('/');
  2843. // Remove empty pieces.
  2844. let copyTo = 0;
  2845. for (let i = 0; i < this.pieces_.length; i++) {
  2846. if (this.pieces_[i].length > 0) {
  2847. this.pieces_[copyTo] = this.pieces_[i];
  2848. copyTo++;
  2849. }
  2850. }
  2851. this.pieces_.length = copyTo;
  2852. this.pieceNum_ = 0;
  2853. }
  2854. else {
  2855. this.pieces_ = pathOrString;
  2856. this.pieceNum_ = pieceNum;
  2857. }
  2858. }
  2859. toString() {
  2860. let pathString = '';
  2861. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2862. if (this.pieces_[i] !== '') {
  2863. pathString += '/' + this.pieces_[i];
  2864. }
  2865. }
  2866. return pathString || '/';
  2867. }
  2868. }
  2869. function newEmptyPath() {
  2870. return new Path('');
  2871. }
  2872. function pathGetFront(path) {
  2873. if (path.pieceNum_ >= path.pieces_.length) {
  2874. return null;
  2875. }
  2876. return path.pieces_[path.pieceNum_];
  2877. }
  2878. /**
  2879. * @returns The number of segments in this path
  2880. */
  2881. function pathGetLength(path) {
  2882. return path.pieces_.length - path.pieceNum_;
  2883. }
  2884. function pathPopFront(path) {
  2885. let pieceNum = path.pieceNum_;
  2886. if (pieceNum < path.pieces_.length) {
  2887. pieceNum++;
  2888. }
  2889. return new Path(path.pieces_, pieceNum);
  2890. }
  2891. function pathGetBack(path) {
  2892. if (path.pieceNum_ < path.pieces_.length) {
  2893. return path.pieces_[path.pieces_.length - 1];
  2894. }
  2895. return null;
  2896. }
  2897. function pathToUrlEncodedString(path) {
  2898. let pathString = '';
  2899. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2900. if (path.pieces_[i] !== '') {
  2901. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2902. }
  2903. }
  2904. return pathString || '/';
  2905. }
  2906. /**
  2907. * Shallow copy of the parts of the path.
  2908. *
  2909. */
  2910. function pathSlice(path, begin = 0) {
  2911. return path.pieces_.slice(path.pieceNum_ + begin);
  2912. }
  2913. function pathParent(path) {
  2914. if (path.pieceNum_ >= path.pieces_.length) {
  2915. return null;
  2916. }
  2917. const pieces = [];
  2918. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2919. pieces.push(path.pieces_[i]);
  2920. }
  2921. return new Path(pieces, 0);
  2922. }
  2923. function pathChild(path, childPathObj) {
  2924. const pieces = [];
  2925. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2926. pieces.push(path.pieces_[i]);
  2927. }
  2928. if (childPathObj instanceof Path) {
  2929. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2930. pieces.push(childPathObj.pieces_[i]);
  2931. }
  2932. }
  2933. else {
  2934. const childPieces = childPathObj.split('/');
  2935. for (let i = 0; i < childPieces.length; i++) {
  2936. if (childPieces[i].length > 0) {
  2937. pieces.push(childPieces[i]);
  2938. }
  2939. }
  2940. }
  2941. return new Path(pieces, 0);
  2942. }
  2943. /**
  2944. * @returns True if there are no segments in this path
  2945. */
  2946. function pathIsEmpty(path) {
  2947. return path.pieceNum_ >= path.pieces_.length;
  2948. }
  2949. /**
  2950. * @returns The path from outerPath to innerPath
  2951. */
  2952. function newRelativePath(outerPath, innerPath) {
  2953. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2954. if (outer === null) {
  2955. return innerPath;
  2956. }
  2957. else if (outer === inner) {
  2958. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2959. }
  2960. else {
  2961. throw new Error('INTERNAL ERROR: innerPath (' +
  2962. innerPath +
  2963. ') is not within ' +
  2964. 'outerPath (' +
  2965. outerPath +
  2966. ')');
  2967. }
  2968. }
  2969. /**
  2970. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2971. */
  2972. function pathCompare(left, right) {
  2973. const leftKeys = pathSlice(left, 0);
  2974. const rightKeys = pathSlice(right, 0);
  2975. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2976. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2977. if (cmp !== 0) {
  2978. return cmp;
  2979. }
  2980. }
  2981. if (leftKeys.length === rightKeys.length) {
  2982. return 0;
  2983. }
  2984. return leftKeys.length < rightKeys.length ? -1 : 1;
  2985. }
  2986. /**
  2987. * @returns true if paths are the same.
  2988. */
  2989. function pathEquals(path, other) {
  2990. if (pathGetLength(path) !== pathGetLength(other)) {
  2991. return false;
  2992. }
  2993. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  2994. if (path.pieces_[i] !== other.pieces_[j]) {
  2995. return false;
  2996. }
  2997. }
  2998. return true;
  2999. }
  3000. /**
  3001. * @returns True if this path is a parent of (or the same as) other
  3002. */
  3003. function pathContains(path, other) {
  3004. let i = path.pieceNum_;
  3005. let j = other.pieceNum_;
  3006. if (pathGetLength(path) > pathGetLength(other)) {
  3007. return false;
  3008. }
  3009. while (i < path.pieces_.length) {
  3010. if (path.pieces_[i] !== other.pieces_[j]) {
  3011. return false;
  3012. }
  3013. ++i;
  3014. ++j;
  3015. }
  3016. return true;
  3017. }
  3018. /**
  3019. * Dynamic (mutable) path used to count path lengths.
  3020. *
  3021. * This class is used to efficiently check paths for valid
  3022. * length (in UTF8 bytes) and depth (used in path validation).
  3023. *
  3024. * Throws Error exception if path is ever invalid.
  3025. *
  3026. * The definition of a path always begins with '/'.
  3027. */
  3028. class ValidationPath {
  3029. /**
  3030. * @param path - Initial Path.
  3031. * @param errorPrefix_ - Prefix for any error messages.
  3032. */
  3033. constructor(path, errorPrefix_) {
  3034. this.errorPrefix_ = errorPrefix_;
  3035. this.parts_ = pathSlice(path, 0);
  3036. /** Initialize to number of '/' chars needed in path. */
  3037. this.byteLength_ = Math.max(1, this.parts_.length);
  3038. for (let i = 0; i < this.parts_.length; i++) {
  3039. this.byteLength_ += stringLength(this.parts_[i]);
  3040. }
  3041. validationPathCheckValid(this);
  3042. }
  3043. }
  3044. function validationPathPush(validationPath, child) {
  3045. // Count the needed '/'
  3046. if (validationPath.parts_.length > 0) {
  3047. validationPath.byteLength_ += 1;
  3048. }
  3049. validationPath.parts_.push(child);
  3050. validationPath.byteLength_ += stringLength(child);
  3051. validationPathCheckValid(validationPath);
  3052. }
  3053. function validationPathPop(validationPath) {
  3054. const last = validationPath.parts_.pop();
  3055. validationPath.byteLength_ -= stringLength(last);
  3056. // Un-count the previous '/'
  3057. if (validationPath.parts_.length > 0) {
  3058. validationPath.byteLength_ -= 1;
  3059. }
  3060. }
  3061. function validationPathCheckValid(validationPath) {
  3062. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3063. throw new Error(validationPath.errorPrefix_ +
  3064. 'has a key path longer than ' +
  3065. MAX_PATH_LENGTH_BYTES +
  3066. ' bytes (' +
  3067. validationPath.byteLength_ +
  3068. ').');
  3069. }
  3070. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3071. throw new Error(validationPath.errorPrefix_ +
  3072. 'path specified exceeds the maximum depth that can be written (' +
  3073. MAX_PATH_DEPTH +
  3074. ') or object contains a cycle ' +
  3075. validationPathToErrorString(validationPath));
  3076. }
  3077. }
  3078. /**
  3079. * String for use in error messages - uses '.' notation for path.
  3080. */
  3081. function validationPathToErrorString(validationPath) {
  3082. if (validationPath.parts_.length === 0) {
  3083. return '';
  3084. }
  3085. return "in property '" + validationPath.parts_.join('.') + "'";
  3086. }
  3087. /**
  3088. * @license
  3089. * Copyright 2017 Google LLC
  3090. *
  3091. * Licensed under the Apache License, Version 2.0 (the "License");
  3092. * you may not use this file except in compliance with the License.
  3093. * You may obtain a copy of the License at
  3094. *
  3095. * http://www.apache.org/licenses/LICENSE-2.0
  3096. *
  3097. * Unless required by applicable law or agreed to in writing, software
  3098. * distributed under the License is distributed on an "AS IS" BASIS,
  3099. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3100. * See the License for the specific language governing permissions and
  3101. * limitations under the License.
  3102. */
  3103. class VisibilityMonitor extends EventEmitter {
  3104. constructor() {
  3105. super(['visible']);
  3106. let hidden;
  3107. let visibilityChange;
  3108. if (typeof document !== 'undefined' &&
  3109. typeof document.addEventListener !== 'undefined') {
  3110. if (typeof document['hidden'] !== 'undefined') {
  3111. // Opera 12.10 and Firefox 18 and later support
  3112. visibilityChange = 'visibilitychange';
  3113. hidden = 'hidden';
  3114. }
  3115. else if (typeof document['mozHidden'] !== 'undefined') {
  3116. visibilityChange = 'mozvisibilitychange';
  3117. hidden = 'mozHidden';
  3118. }
  3119. else if (typeof document['msHidden'] !== 'undefined') {
  3120. visibilityChange = 'msvisibilitychange';
  3121. hidden = 'msHidden';
  3122. }
  3123. else if (typeof document['webkitHidden'] !== 'undefined') {
  3124. visibilityChange = 'webkitvisibilitychange';
  3125. hidden = 'webkitHidden';
  3126. }
  3127. }
  3128. // Initially, we always assume we are visible. This ensures that in browsers
  3129. // without page visibility support or in cases where we are never visible
  3130. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3131. // reconnects
  3132. this.visible_ = true;
  3133. if (visibilityChange) {
  3134. document.addEventListener(visibilityChange, () => {
  3135. const visible = !document[hidden];
  3136. if (visible !== this.visible_) {
  3137. this.visible_ = visible;
  3138. this.trigger('visible', visible);
  3139. }
  3140. }, false);
  3141. }
  3142. }
  3143. static getInstance() {
  3144. return new VisibilityMonitor();
  3145. }
  3146. getInitialEvent(eventType) {
  3147. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3148. return [this.visible_];
  3149. }
  3150. }
  3151. /**
  3152. * @license
  3153. * Copyright 2017 Google LLC
  3154. *
  3155. * Licensed under the Apache License, Version 2.0 (the "License");
  3156. * you may not use this file except in compliance with the License.
  3157. * You may obtain a copy of the License at
  3158. *
  3159. * http://www.apache.org/licenses/LICENSE-2.0
  3160. *
  3161. * Unless required by applicable law or agreed to in writing, software
  3162. * distributed under the License is distributed on an "AS IS" BASIS,
  3163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3164. * See the License for the specific language governing permissions and
  3165. * limitations under the License.
  3166. */
  3167. const RECONNECT_MIN_DELAY = 1000;
  3168. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3169. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3170. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3171. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3172. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3173. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3174. const INVALID_TOKEN_THRESHOLD = 3;
  3175. /**
  3176. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3177. *
  3178. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3179. * in quotes to make sure the closure compiler does not minify them.
  3180. */
  3181. class PersistentConnection extends ServerActions {
  3182. /**
  3183. * @param repoInfo_ - Data about the namespace we are connecting to
  3184. * @param applicationId_ - The Firebase App ID for this project
  3185. * @param onDataUpdate_ - A callback for new data from the server
  3186. */
  3187. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3188. super();
  3189. this.repoInfo_ = repoInfo_;
  3190. this.applicationId_ = applicationId_;
  3191. this.onDataUpdate_ = onDataUpdate_;
  3192. this.onConnectStatus_ = onConnectStatus_;
  3193. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3194. this.authTokenProvider_ = authTokenProvider_;
  3195. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3196. this.authOverride_ = authOverride_;
  3197. // Used for diagnostic logging.
  3198. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3199. this.log_ = logWrapper('p:' + this.id + ':');
  3200. this.interruptReasons_ = {};
  3201. this.listens = new Map();
  3202. this.outstandingPuts_ = [];
  3203. this.outstandingGets_ = [];
  3204. this.outstandingPutCount_ = 0;
  3205. this.outstandingGetCount_ = 0;
  3206. this.onDisconnectRequestQueue_ = [];
  3207. this.connected_ = false;
  3208. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3209. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3210. this.securityDebugCallback_ = null;
  3211. this.lastSessionId = null;
  3212. this.establishConnectionTimer_ = null;
  3213. this.visible_ = false;
  3214. // Before we get connected, we keep a queue of pending messages to send.
  3215. this.requestCBHash_ = {};
  3216. this.requestNumber_ = 0;
  3217. this.realtime_ = null;
  3218. this.authToken_ = null;
  3219. this.appCheckToken_ = null;
  3220. this.forceTokenRefresh_ = false;
  3221. this.invalidAuthTokenCount_ = 0;
  3222. this.invalidAppCheckTokenCount_ = 0;
  3223. this.firstConnection_ = true;
  3224. this.lastConnectionAttemptTime_ = null;
  3225. this.lastConnectionEstablishedTime_ = null;
  3226. if (authOverride_ && !isNodeSdk()) {
  3227. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3228. }
  3229. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3230. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3231. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3232. }
  3233. }
  3234. sendRequest(action, body, onResponse) {
  3235. const curReqNum = ++this.requestNumber_;
  3236. const msg = { r: curReqNum, a: action, b: body };
  3237. this.log_(stringify(msg));
  3238. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3239. this.realtime_.sendRequest(msg);
  3240. if (onResponse) {
  3241. this.requestCBHash_[curReqNum] = onResponse;
  3242. }
  3243. }
  3244. get(query) {
  3245. this.initConnection_();
  3246. const deferred = new Deferred();
  3247. const request = {
  3248. p: query._path.toString(),
  3249. q: query._queryObject
  3250. };
  3251. const outstandingGet = {
  3252. action: 'g',
  3253. request,
  3254. onComplete: (message) => {
  3255. const payload = message['d'];
  3256. if (message['s'] === 'ok') {
  3257. deferred.resolve(payload);
  3258. }
  3259. else {
  3260. deferred.reject(payload);
  3261. }
  3262. }
  3263. };
  3264. this.outstandingGets_.push(outstandingGet);
  3265. this.outstandingGetCount_++;
  3266. const index = this.outstandingGets_.length - 1;
  3267. if (this.connected_) {
  3268. this.sendGet_(index);
  3269. }
  3270. return deferred.promise;
  3271. }
  3272. listen(query, currentHashFn, tag, onComplete) {
  3273. this.initConnection_();
  3274. const queryId = query._queryIdentifier;
  3275. const pathString = query._path.toString();
  3276. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3277. if (!this.listens.has(pathString)) {
  3278. this.listens.set(pathString, new Map());
  3279. }
  3280. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3281. assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3282. const listenSpec = {
  3283. onComplete,
  3284. hashFn: currentHashFn,
  3285. query,
  3286. tag
  3287. };
  3288. this.listens.get(pathString).set(queryId, listenSpec);
  3289. if (this.connected_) {
  3290. this.sendListen_(listenSpec);
  3291. }
  3292. }
  3293. sendGet_(index) {
  3294. const get = this.outstandingGets_[index];
  3295. this.sendRequest('g', get.request, (message) => {
  3296. delete this.outstandingGets_[index];
  3297. this.outstandingGetCount_--;
  3298. if (this.outstandingGetCount_ === 0) {
  3299. this.outstandingGets_ = [];
  3300. }
  3301. if (get.onComplete) {
  3302. get.onComplete(message);
  3303. }
  3304. });
  3305. }
  3306. sendListen_(listenSpec) {
  3307. const query = listenSpec.query;
  3308. const pathString = query._path.toString();
  3309. const queryId = query._queryIdentifier;
  3310. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3311. const req = { /*path*/ p: pathString };
  3312. const action = 'q';
  3313. // Only bother to send query if it's non-default.
  3314. if (listenSpec.tag) {
  3315. req['q'] = query._queryObject;
  3316. req['t'] = listenSpec.tag;
  3317. }
  3318. req[ /*hash*/'h'] = listenSpec.hashFn();
  3319. this.sendRequest(action, req, (message) => {
  3320. const payload = message[ /*data*/'d'];
  3321. const status = message[ /*status*/'s'];
  3322. // print warnings in any case...
  3323. PersistentConnection.warnOnListenWarnings_(payload, query);
  3324. const currentListenSpec = this.listens.get(pathString) &&
  3325. this.listens.get(pathString).get(queryId);
  3326. // only trigger actions if the listen hasn't been removed and readded
  3327. if (currentListenSpec === listenSpec) {
  3328. this.log_('listen response', message);
  3329. if (status !== 'ok') {
  3330. this.removeListen_(pathString, queryId);
  3331. }
  3332. if (listenSpec.onComplete) {
  3333. listenSpec.onComplete(status, payload);
  3334. }
  3335. }
  3336. });
  3337. }
  3338. static warnOnListenWarnings_(payload, query) {
  3339. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3340. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3341. const warnings = safeGet(payload, 'w');
  3342. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3343. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3344. const indexPath = query._path.toString();
  3345. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3346. `filtered on the client. Consider adding ${indexSpec} at ` +
  3347. `${indexPath} to your security rules for better performance.`);
  3348. }
  3349. }
  3350. }
  3351. refreshAuthToken(token) {
  3352. this.authToken_ = token;
  3353. this.log_('Auth token refreshed');
  3354. if (this.authToken_) {
  3355. this.tryAuth();
  3356. }
  3357. else {
  3358. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3359. //the credential so we dont become authenticated next time we connect.
  3360. if (this.connected_) {
  3361. this.sendRequest('unauth', {}, () => { });
  3362. }
  3363. }
  3364. this.reduceReconnectDelayIfAdminCredential_(token);
  3365. }
  3366. reduceReconnectDelayIfAdminCredential_(credential) {
  3367. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3368. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3369. const isFirebaseSecret = credential && credential.length === 40;
  3370. if (isFirebaseSecret || isAdmin(credential)) {
  3371. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3372. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3373. }
  3374. }
  3375. refreshAppCheckToken(token) {
  3376. this.appCheckToken_ = token;
  3377. this.log_('App check token refreshed');
  3378. if (this.appCheckToken_) {
  3379. this.tryAppCheck();
  3380. }
  3381. else {
  3382. //If we're connected we want to let the server know to unauthenticate us.
  3383. //If we're not connected, simply delete the credential so we dont become
  3384. // authenticated next time we connect.
  3385. if (this.connected_) {
  3386. this.sendRequest('unappeck', {}, () => { });
  3387. }
  3388. }
  3389. }
  3390. /**
  3391. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3392. * a auth revoked (the connection is closed).
  3393. */
  3394. tryAuth() {
  3395. if (this.connected_ && this.authToken_) {
  3396. const token = this.authToken_;
  3397. const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
  3398. const requestData = { cred: token };
  3399. if (this.authOverride_ === null) {
  3400. requestData['noauth'] = true;
  3401. }
  3402. else if (typeof this.authOverride_ === 'object') {
  3403. requestData['authvar'] = this.authOverride_;
  3404. }
  3405. this.sendRequest(authMethod, requestData, (res) => {
  3406. const status = res[ /*status*/'s'];
  3407. const data = res[ /*data*/'d'] || 'error';
  3408. if (this.authToken_ === token) {
  3409. if (status === 'ok') {
  3410. this.invalidAuthTokenCount_ = 0;
  3411. }
  3412. else {
  3413. // Triggers reconnect and force refresh for auth token
  3414. this.onAuthRevoked_(status, data);
  3415. }
  3416. }
  3417. });
  3418. }
  3419. }
  3420. /**
  3421. * Attempts to authenticate with the given token. If the authentication
  3422. * attempt fails, it's triggered like the token was revoked (the connection is
  3423. * closed).
  3424. */
  3425. tryAppCheck() {
  3426. if (this.connected_ && this.appCheckToken_) {
  3427. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3428. const status = res[ /*status*/'s'];
  3429. const data = res[ /*data*/'d'] || 'error';
  3430. if (status === 'ok') {
  3431. this.invalidAppCheckTokenCount_ = 0;
  3432. }
  3433. else {
  3434. this.onAppCheckRevoked_(status, data);
  3435. }
  3436. });
  3437. }
  3438. }
  3439. /**
  3440. * @inheritDoc
  3441. */
  3442. unlisten(query, tag) {
  3443. const pathString = query._path.toString();
  3444. const queryId = query._queryIdentifier;
  3445. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3446. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3447. const listen = this.removeListen_(pathString, queryId);
  3448. if (listen && this.connected_) {
  3449. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3450. }
  3451. }
  3452. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3453. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3454. const req = { /*path*/ p: pathString };
  3455. const action = 'n';
  3456. // Only bother sending queryId if it's non-default.
  3457. if (tag) {
  3458. req['q'] = queryObj;
  3459. req['t'] = tag;
  3460. }
  3461. this.sendRequest(action, req);
  3462. }
  3463. onDisconnectPut(pathString, data, onComplete) {
  3464. this.initConnection_();
  3465. if (this.connected_) {
  3466. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3467. }
  3468. else {
  3469. this.onDisconnectRequestQueue_.push({
  3470. pathString,
  3471. action: 'o',
  3472. data,
  3473. onComplete
  3474. });
  3475. }
  3476. }
  3477. onDisconnectMerge(pathString, data, onComplete) {
  3478. this.initConnection_();
  3479. if (this.connected_) {
  3480. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3481. }
  3482. else {
  3483. this.onDisconnectRequestQueue_.push({
  3484. pathString,
  3485. action: 'om',
  3486. data,
  3487. onComplete
  3488. });
  3489. }
  3490. }
  3491. onDisconnectCancel(pathString, onComplete) {
  3492. this.initConnection_();
  3493. if (this.connected_) {
  3494. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3495. }
  3496. else {
  3497. this.onDisconnectRequestQueue_.push({
  3498. pathString,
  3499. action: 'oc',
  3500. data: null,
  3501. onComplete
  3502. });
  3503. }
  3504. }
  3505. sendOnDisconnect_(action, pathString, data, onComplete) {
  3506. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3507. this.log_('onDisconnect ' + action, request);
  3508. this.sendRequest(action, request, (response) => {
  3509. if (onComplete) {
  3510. setTimeout(() => {
  3511. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3512. }, Math.floor(0));
  3513. }
  3514. });
  3515. }
  3516. put(pathString, data, onComplete, hash) {
  3517. this.putInternal('p', pathString, data, onComplete, hash);
  3518. }
  3519. merge(pathString, data, onComplete, hash) {
  3520. this.putInternal('m', pathString, data, onComplete, hash);
  3521. }
  3522. putInternal(action, pathString, data, onComplete, hash) {
  3523. this.initConnection_();
  3524. const request = {
  3525. /*path*/ p: pathString,
  3526. /*data*/ d: data
  3527. };
  3528. if (hash !== undefined) {
  3529. request[ /*hash*/'h'] = hash;
  3530. }
  3531. // TODO: Only keep track of the most recent put for a given path?
  3532. this.outstandingPuts_.push({
  3533. action,
  3534. request,
  3535. onComplete
  3536. });
  3537. this.outstandingPutCount_++;
  3538. const index = this.outstandingPuts_.length - 1;
  3539. if (this.connected_) {
  3540. this.sendPut_(index);
  3541. }
  3542. else {
  3543. this.log_('Buffering put: ' + pathString);
  3544. }
  3545. }
  3546. sendPut_(index) {
  3547. const action = this.outstandingPuts_[index].action;
  3548. const request = this.outstandingPuts_[index].request;
  3549. const onComplete = this.outstandingPuts_[index].onComplete;
  3550. this.outstandingPuts_[index].queued = this.connected_;
  3551. this.sendRequest(action, request, (message) => {
  3552. this.log_(action + ' response', message);
  3553. delete this.outstandingPuts_[index];
  3554. this.outstandingPutCount_--;
  3555. // Clean up array occasionally.
  3556. if (this.outstandingPutCount_ === 0) {
  3557. this.outstandingPuts_ = [];
  3558. }
  3559. if (onComplete) {
  3560. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3561. }
  3562. });
  3563. }
  3564. reportStats(stats) {
  3565. // If we're not connected, we just drop the stats.
  3566. if (this.connected_) {
  3567. const request = { /*counters*/ c: stats };
  3568. this.log_('reportStats', request);
  3569. this.sendRequest(/*stats*/ 's', request, result => {
  3570. const status = result[ /*status*/'s'];
  3571. if (status !== 'ok') {
  3572. const errorReason = result[ /* data */'d'];
  3573. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3574. }
  3575. });
  3576. }
  3577. }
  3578. onDataMessage_(message) {
  3579. if ('r' in message) {
  3580. // this is a response
  3581. this.log_('from server: ' + stringify(message));
  3582. const reqNum = message['r'];
  3583. const onResponse = this.requestCBHash_[reqNum];
  3584. if (onResponse) {
  3585. delete this.requestCBHash_[reqNum];
  3586. onResponse(message[ /*body*/'b']);
  3587. }
  3588. }
  3589. else if ('error' in message) {
  3590. throw 'A server-side error has occurred: ' + message['error'];
  3591. }
  3592. else if ('a' in message) {
  3593. // a and b are action and body, respectively
  3594. this.onDataPush_(message['a'], message['b']);
  3595. }
  3596. }
  3597. onDataPush_(action, body) {
  3598. this.log_('handleServerMessage', action, body);
  3599. if (action === 'd') {
  3600. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3601. /*isMerge*/ false, body['t']);
  3602. }
  3603. else if (action === 'm') {
  3604. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3605. /*isMerge=*/ true, body['t']);
  3606. }
  3607. else if (action === 'c') {
  3608. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3609. }
  3610. else if (action === 'ac') {
  3611. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3612. }
  3613. else if (action === 'apc') {
  3614. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3615. }
  3616. else if (action === 'sd') {
  3617. this.onSecurityDebugPacket_(body);
  3618. }
  3619. else {
  3620. error('Unrecognized action received from server: ' +
  3621. stringify(action) +
  3622. '\nAre you using the latest client?');
  3623. }
  3624. }
  3625. onReady_(timestamp, sessionId) {
  3626. this.log_('connection ready');
  3627. this.connected_ = true;
  3628. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3629. this.handleTimestamp_(timestamp);
  3630. this.lastSessionId = sessionId;
  3631. if (this.firstConnection_) {
  3632. this.sendConnectStats_();
  3633. }
  3634. this.restoreState_();
  3635. this.firstConnection_ = false;
  3636. this.onConnectStatus_(true);
  3637. }
  3638. scheduleConnect_(timeout) {
  3639. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3640. if (this.establishConnectionTimer_) {
  3641. clearTimeout(this.establishConnectionTimer_);
  3642. }
  3643. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3644. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3645. this.establishConnectionTimer_ = setTimeout(() => {
  3646. this.establishConnectionTimer_ = null;
  3647. this.establishConnection_();
  3648. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3649. }, Math.floor(timeout));
  3650. }
  3651. initConnection_() {
  3652. if (!this.realtime_ && this.firstConnection_) {
  3653. this.scheduleConnect_(0);
  3654. }
  3655. }
  3656. onVisible_(visible) {
  3657. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3658. if (visible &&
  3659. !this.visible_ &&
  3660. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3661. this.log_('Window became visible. Reducing delay.');
  3662. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3663. if (!this.realtime_) {
  3664. this.scheduleConnect_(0);
  3665. }
  3666. }
  3667. this.visible_ = visible;
  3668. }
  3669. onOnline_(online) {
  3670. if (online) {
  3671. this.log_('Browser went online.');
  3672. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3673. if (!this.realtime_) {
  3674. this.scheduleConnect_(0);
  3675. }
  3676. }
  3677. else {
  3678. this.log_('Browser went offline. Killing connection.');
  3679. if (this.realtime_) {
  3680. this.realtime_.close();
  3681. }
  3682. }
  3683. }
  3684. onRealtimeDisconnect_() {
  3685. this.log_('data client disconnected');
  3686. this.connected_ = false;
  3687. this.realtime_ = null;
  3688. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3689. this.cancelSentTransactions_();
  3690. // Clear out the pending requests.
  3691. this.requestCBHash_ = {};
  3692. if (this.shouldReconnect_()) {
  3693. if (!this.visible_) {
  3694. this.log_("Window isn't visible. Delaying reconnect.");
  3695. this.reconnectDelay_ = this.maxReconnectDelay_;
  3696. this.lastConnectionAttemptTime_ = new Date().getTime();
  3697. }
  3698. else if (this.lastConnectionEstablishedTime_) {
  3699. // If we've been connected long enough, reset reconnect delay to minimum.
  3700. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3701. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3702. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3703. }
  3704. this.lastConnectionEstablishedTime_ = null;
  3705. }
  3706. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3707. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3708. reconnectDelay = Math.random() * reconnectDelay;
  3709. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3710. this.scheduleConnect_(reconnectDelay);
  3711. // Adjust reconnect delay for next time.
  3712. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3713. }
  3714. this.onConnectStatus_(false);
  3715. }
  3716. async establishConnection_() {
  3717. if (this.shouldReconnect_()) {
  3718. this.log_('Making a connection attempt');
  3719. this.lastConnectionAttemptTime_ = new Date().getTime();
  3720. this.lastConnectionEstablishedTime_ = null;
  3721. const onDataMessage = this.onDataMessage_.bind(this);
  3722. const onReady = this.onReady_.bind(this);
  3723. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3724. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3725. const lastSessionId = this.lastSessionId;
  3726. let canceled = false;
  3727. let connection = null;
  3728. const closeFn = function () {
  3729. if (connection) {
  3730. connection.close();
  3731. }
  3732. else {
  3733. canceled = true;
  3734. onDisconnect();
  3735. }
  3736. };
  3737. const sendRequestFn = function (msg) {
  3738. assert(connection, "sendRequest call when we're not connected not allowed.");
  3739. connection.sendRequest(msg);
  3740. };
  3741. this.realtime_ = {
  3742. close: closeFn,
  3743. sendRequest: sendRequestFn
  3744. };
  3745. const forceRefresh = this.forceTokenRefresh_;
  3746. this.forceTokenRefresh_ = false;
  3747. try {
  3748. // First fetch auth and app check token, and establish connection after
  3749. // fetching the token was successful
  3750. const [authToken, appCheckToken] = await Promise.all([
  3751. this.authTokenProvider_.getToken(forceRefresh),
  3752. this.appCheckTokenProvider_.getToken(forceRefresh)
  3753. ]);
  3754. if (!canceled) {
  3755. log('getToken() completed. Creating connection.');
  3756. this.authToken_ = authToken && authToken.accessToken;
  3757. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3758. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3759. /* onKill= */ reason => {
  3760. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3761. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3762. }, lastSessionId);
  3763. }
  3764. else {
  3765. log('getToken() completed but was canceled');
  3766. }
  3767. }
  3768. catch (error) {
  3769. this.log_('Failed to get token: ' + error);
  3770. if (!canceled) {
  3771. if (this.repoInfo_.nodeAdmin) {
  3772. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3773. // But getToken() may also just have temporarily failed, so we still want to
  3774. // continue retrying.
  3775. warn(error);
  3776. }
  3777. closeFn();
  3778. }
  3779. }
  3780. }
  3781. }
  3782. interrupt(reason) {
  3783. log('Interrupting connection for reason: ' + reason);
  3784. this.interruptReasons_[reason] = true;
  3785. if (this.realtime_) {
  3786. this.realtime_.close();
  3787. }
  3788. else {
  3789. if (this.establishConnectionTimer_) {
  3790. clearTimeout(this.establishConnectionTimer_);
  3791. this.establishConnectionTimer_ = null;
  3792. }
  3793. if (this.connected_) {
  3794. this.onRealtimeDisconnect_();
  3795. }
  3796. }
  3797. }
  3798. resume(reason) {
  3799. log('Resuming connection for reason: ' + reason);
  3800. delete this.interruptReasons_[reason];
  3801. if (isEmpty(this.interruptReasons_)) {
  3802. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3803. if (!this.realtime_) {
  3804. this.scheduleConnect_(0);
  3805. }
  3806. }
  3807. }
  3808. handleTimestamp_(timestamp) {
  3809. const delta = timestamp - new Date().getTime();
  3810. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3811. }
  3812. cancelSentTransactions_() {
  3813. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3814. const put = this.outstandingPuts_[i];
  3815. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3816. if (put.onComplete) {
  3817. put.onComplete('disconnect');
  3818. }
  3819. delete this.outstandingPuts_[i];
  3820. this.outstandingPutCount_--;
  3821. }
  3822. }
  3823. // Clean up array occasionally.
  3824. if (this.outstandingPutCount_ === 0) {
  3825. this.outstandingPuts_ = [];
  3826. }
  3827. }
  3828. onListenRevoked_(pathString, query) {
  3829. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3830. let queryId;
  3831. if (!query) {
  3832. queryId = 'default';
  3833. }
  3834. else {
  3835. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3836. }
  3837. const listen = this.removeListen_(pathString, queryId);
  3838. if (listen && listen.onComplete) {
  3839. listen.onComplete('permission_denied');
  3840. }
  3841. }
  3842. removeListen_(pathString, queryId) {
  3843. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3844. let listen;
  3845. if (this.listens.has(normalizedPathString)) {
  3846. const map = this.listens.get(normalizedPathString);
  3847. listen = map.get(queryId);
  3848. map.delete(queryId);
  3849. if (map.size === 0) {
  3850. this.listens.delete(normalizedPathString);
  3851. }
  3852. }
  3853. else {
  3854. // all listens for this path has already been removed
  3855. listen = undefined;
  3856. }
  3857. return listen;
  3858. }
  3859. onAuthRevoked_(statusCode, explanation) {
  3860. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3861. this.authToken_ = null;
  3862. this.forceTokenRefresh_ = true;
  3863. this.realtime_.close();
  3864. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3865. // We'll wait a couple times before logging the warning / increasing the
  3866. // retry period since oauth tokens will report as "invalid" if they're
  3867. // just expired. Plus there may be transient issues that resolve themselves.
  3868. this.invalidAuthTokenCount_++;
  3869. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3870. // Set a long reconnect delay because recovery is unlikely
  3871. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3872. // Notify the auth token provider that the token is invalid, which will log
  3873. // a warning
  3874. this.authTokenProvider_.notifyForInvalidToken();
  3875. }
  3876. }
  3877. }
  3878. onAppCheckRevoked_(statusCode, explanation) {
  3879. log('App check token revoked: ' + statusCode + '/' + explanation);
  3880. this.appCheckToken_ = null;
  3881. this.forceTokenRefresh_ = true;
  3882. // Note: We don't close the connection as the developer may not have
  3883. // enforcement enabled. The backend closes connections with enforcements.
  3884. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3885. // We'll wait a couple times before logging the warning / increasing the
  3886. // retry period since oauth tokens will report as "invalid" if they're
  3887. // just expired. Plus there may be transient issues that resolve themselves.
  3888. this.invalidAppCheckTokenCount_++;
  3889. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3890. this.appCheckTokenProvider_.notifyForInvalidToken();
  3891. }
  3892. }
  3893. }
  3894. onSecurityDebugPacket_(body) {
  3895. if (this.securityDebugCallback_) {
  3896. this.securityDebugCallback_(body);
  3897. }
  3898. else {
  3899. if ('msg' in body) {
  3900. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3901. }
  3902. }
  3903. }
  3904. restoreState_() {
  3905. //Re-authenticate ourselves if we have a credential stored.
  3906. this.tryAuth();
  3907. this.tryAppCheck();
  3908. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3909. // make sure to send listens before puts.
  3910. for (const queries of this.listens.values()) {
  3911. for (const listenSpec of queries.values()) {
  3912. this.sendListen_(listenSpec);
  3913. }
  3914. }
  3915. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3916. if (this.outstandingPuts_[i]) {
  3917. this.sendPut_(i);
  3918. }
  3919. }
  3920. while (this.onDisconnectRequestQueue_.length) {
  3921. const request = this.onDisconnectRequestQueue_.shift();
  3922. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3923. }
  3924. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3925. if (this.outstandingGets_[i]) {
  3926. this.sendGet_(i);
  3927. }
  3928. }
  3929. }
  3930. /**
  3931. * Sends client stats for first connection
  3932. */
  3933. sendConnectStats_() {
  3934. const stats = {};
  3935. let clientName = 'js';
  3936. if (isNodeSdk()) {
  3937. if (this.repoInfo_.nodeAdmin) {
  3938. clientName = 'admin_node';
  3939. }
  3940. else {
  3941. clientName = 'node';
  3942. }
  3943. }
  3944. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3945. if (isMobileCordova()) {
  3946. stats['framework.cordova'] = 1;
  3947. }
  3948. else if (isReactNative()) {
  3949. stats['framework.reactnative'] = 1;
  3950. }
  3951. this.reportStats(stats);
  3952. }
  3953. shouldReconnect_() {
  3954. const online = OnlineMonitor.getInstance().currentlyOnline();
  3955. return isEmpty(this.interruptReasons_) && online;
  3956. }
  3957. }
  3958. PersistentConnection.nextPersistentConnectionId_ = 0;
  3959. /**
  3960. * Counter for number of connections created. Mainly used for tagging in the logs
  3961. */
  3962. PersistentConnection.nextConnectionId_ = 0;
  3963. /**
  3964. * @license
  3965. * Copyright 2017 Google LLC
  3966. *
  3967. * Licensed under the Apache License, Version 2.0 (the "License");
  3968. * you may not use this file except in compliance with the License.
  3969. * You may obtain a copy of the License at
  3970. *
  3971. * http://www.apache.org/licenses/LICENSE-2.0
  3972. *
  3973. * Unless required by applicable law or agreed to in writing, software
  3974. * distributed under the License is distributed on an "AS IS" BASIS,
  3975. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3976. * See the License for the specific language governing permissions and
  3977. * limitations under the License.
  3978. */
  3979. class NamedNode {
  3980. constructor(name, node) {
  3981. this.name = name;
  3982. this.node = node;
  3983. }
  3984. static Wrap(name, node) {
  3985. return new NamedNode(name, node);
  3986. }
  3987. }
  3988. /**
  3989. * @license
  3990. * Copyright 2017 Google LLC
  3991. *
  3992. * Licensed under the Apache License, Version 2.0 (the "License");
  3993. * you may not use this file except in compliance with the License.
  3994. * You may obtain a copy of the License at
  3995. *
  3996. * http://www.apache.org/licenses/LICENSE-2.0
  3997. *
  3998. * Unless required by applicable law or agreed to in writing, software
  3999. * distributed under the License is distributed on an "AS IS" BASIS,
  4000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4001. * See the License for the specific language governing permissions and
  4002. * limitations under the License.
  4003. */
  4004. class Index {
  4005. /**
  4006. * @returns A standalone comparison function for
  4007. * this index
  4008. */
  4009. getCompare() {
  4010. return this.compare.bind(this);
  4011. }
  4012. /**
  4013. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4014. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4015. *
  4016. *
  4017. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4018. */
  4019. indexedValueChanged(oldNode, newNode) {
  4020. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4021. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4022. return this.compare(oldWrapped, newWrapped) !== 0;
  4023. }
  4024. /**
  4025. * @returns a node wrapper that will sort equal to or less than
  4026. * any other node wrapper, using this index
  4027. */
  4028. minPost() {
  4029. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4030. return NamedNode.MIN;
  4031. }
  4032. }
  4033. /**
  4034. * @license
  4035. * Copyright 2017 Google LLC
  4036. *
  4037. * Licensed under the Apache License, Version 2.0 (the "License");
  4038. * you may not use this file except in compliance with the License.
  4039. * You may obtain a copy of the License at
  4040. *
  4041. * http://www.apache.org/licenses/LICENSE-2.0
  4042. *
  4043. * Unless required by applicable law or agreed to in writing, software
  4044. * distributed under the License is distributed on an "AS IS" BASIS,
  4045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4046. * See the License for the specific language governing permissions and
  4047. * limitations under the License.
  4048. */
  4049. let __EMPTY_NODE;
  4050. class KeyIndex extends Index {
  4051. static get __EMPTY_NODE() {
  4052. return __EMPTY_NODE;
  4053. }
  4054. static set __EMPTY_NODE(val) {
  4055. __EMPTY_NODE = val;
  4056. }
  4057. compare(a, b) {
  4058. return nameCompare(a.name, b.name);
  4059. }
  4060. isDefinedOn(node) {
  4061. // We could probably return true here (since every node has a key), but it's never called
  4062. // so just leaving unimplemented for now.
  4063. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4064. }
  4065. indexedValueChanged(oldNode, newNode) {
  4066. return false; // The key for a node never changes.
  4067. }
  4068. minPost() {
  4069. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4070. return NamedNode.MIN;
  4071. }
  4072. maxPost() {
  4073. // TODO: This should really be created once and cached in a static property, but
  4074. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4075. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4076. }
  4077. makePost(indexValue, name) {
  4078. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4079. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4080. return new NamedNode(indexValue, __EMPTY_NODE);
  4081. }
  4082. /**
  4083. * @returns String representation for inclusion in a query spec
  4084. */
  4085. toString() {
  4086. return '.key';
  4087. }
  4088. }
  4089. const KEY_INDEX = new KeyIndex();
  4090. /**
  4091. * @license
  4092. * Copyright 2017 Google LLC
  4093. *
  4094. * Licensed under the Apache License, Version 2.0 (the "License");
  4095. * you may not use this file except in compliance with the License.
  4096. * You may obtain a copy of the License at
  4097. *
  4098. * http://www.apache.org/licenses/LICENSE-2.0
  4099. *
  4100. * Unless required by applicable law or agreed to in writing, software
  4101. * distributed under the License is distributed on an "AS IS" BASIS,
  4102. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4103. * See the License for the specific language governing permissions and
  4104. * limitations under the License.
  4105. */
  4106. /**
  4107. * An iterator over an LLRBNode.
  4108. */
  4109. class SortedMapIterator {
  4110. /**
  4111. * @param node - Node to iterate.
  4112. * @param isReverse_ - Whether or not to iterate in reverse
  4113. */
  4114. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4115. this.isReverse_ = isReverse_;
  4116. this.resultGenerator_ = resultGenerator_;
  4117. this.nodeStack_ = [];
  4118. let cmp = 1;
  4119. while (!node.isEmpty()) {
  4120. node = node;
  4121. cmp = startKey ? comparator(node.key, startKey) : 1;
  4122. // flip the comparison if we're going in reverse
  4123. if (isReverse_) {
  4124. cmp *= -1;
  4125. }
  4126. if (cmp < 0) {
  4127. // This node is less than our start key. ignore it
  4128. if (this.isReverse_) {
  4129. node = node.left;
  4130. }
  4131. else {
  4132. node = node.right;
  4133. }
  4134. }
  4135. else if (cmp === 0) {
  4136. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4137. this.nodeStack_.push(node);
  4138. break;
  4139. }
  4140. else {
  4141. // This node is greater than our start key, add it to the stack and move to the next one
  4142. this.nodeStack_.push(node);
  4143. if (this.isReverse_) {
  4144. node = node.right;
  4145. }
  4146. else {
  4147. node = node.left;
  4148. }
  4149. }
  4150. }
  4151. }
  4152. getNext() {
  4153. if (this.nodeStack_.length === 0) {
  4154. return null;
  4155. }
  4156. let node = this.nodeStack_.pop();
  4157. let result;
  4158. if (this.resultGenerator_) {
  4159. result = this.resultGenerator_(node.key, node.value);
  4160. }
  4161. else {
  4162. result = { key: node.key, value: node.value };
  4163. }
  4164. if (this.isReverse_) {
  4165. node = node.left;
  4166. while (!node.isEmpty()) {
  4167. this.nodeStack_.push(node);
  4168. node = node.right;
  4169. }
  4170. }
  4171. else {
  4172. node = node.right;
  4173. while (!node.isEmpty()) {
  4174. this.nodeStack_.push(node);
  4175. node = node.left;
  4176. }
  4177. }
  4178. return result;
  4179. }
  4180. hasNext() {
  4181. return this.nodeStack_.length > 0;
  4182. }
  4183. peek() {
  4184. if (this.nodeStack_.length === 0) {
  4185. return null;
  4186. }
  4187. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4188. if (this.resultGenerator_) {
  4189. return this.resultGenerator_(node.key, node.value);
  4190. }
  4191. else {
  4192. return { key: node.key, value: node.value };
  4193. }
  4194. }
  4195. }
  4196. /**
  4197. * Represents a node in a Left-leaning Red-Black tree.
  4198. */
  4199. class LLRBNode {
  4200. /**
  4201. * @param key - Key associated with this node.
  4202. * @param value - Value associated with this node.
  4203. * @param color - Whether this node is red.
  4204. * @param left - Left child.
  4205. * @param right - Right child.
  4206. */
  4207. constructor(key, value, color, left, right) {
  4208. this.key = key;
  4209. this.value = value;
  4210. this.color = color != null ? color : LLRBNode.RED;
  4211. this.left =
  4212. left != null ? left : SortedMap.EMPTY_NODE;
  4213. this.right =
  4214. right != null ? right : SortedMap.EMPTY_NODE;
  4215. }
  4216. /**
  4217. * Returns a copy of the current node, optionally replacing pieces of it.
  4218. *
  4219. * @param key - New key for the node, or null.
  4220. * @param value - New value for the node, or null.
  4221. * @param color - New color for the node, or null.
  4222. * @param left - New left child for the node, or null.
  4223. * @param right - New right child for the node, or null.
  4224. * @returns The node copy.
  4225. */
  4226. copy(key, value, color, left, right) {
  4227. 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);
  4228. }
  4229. /**
  4230. * @returns The total number of nodes in the tree.
  4231. */
  4232. count() {
  4233. return this.left.count() + 1 + this.right.count();
  4234. }
  4235. /**
  4236. * @returns True if the tree is empty.
  4237. */
  4238. isEmpty() {
  4239. return false;
  4240. }
  4241. /**
  4242. * Traverses the tree in key order and calls the specified action function
  4243. * for each node.
  4244. *
  4245. * @param action - Callback function to be called for each
  4246. * node. If it returns true, traversal is aborted.
  4247. * @returns The first truthy value returned by action, or the last falsey
  4248. * value returned by action
  4249. */
  4250. inorderTraversal(action) {
  4251. return (this.left.inorderTraversal(action) ||
  4252. !!action(this.key, this.value) ||
  4253. this.right.inorderTraversal(action));
  4254. }
  4255. /**
  4256. * Traverses the tree in reverse key order and calls the specified action function
  4257. * for each node.
  4258. *
  4259. * @param action - Callback function to be called for each
  4260. * node. If it returns true, traversal is aborted.
  4261. * @returns True if traversal was aborted.
  4262. */
  4263. reverseTraversal(action) {
  4264. return (this.right.reverseTraversal(action) ||
  4265. action(this.key, this.value) ||
  4266. this.left.reverseTraversal(action));
  4267. }
  4268. /**
  4269. * @returns The minimum node in the tree.
  4270. */
  4271. min_() {
  4272. if (this.left.isEmpty()) {
  4273. return this;
  4274. }
  4275. else {
  4276. return this.left.min_();
  4277. }
  4278. }
  4279. /**
  4280. * @returns The maximum key in the tree.
  4281. */
  4282. minKey() {
  4283. return this.min_().key;
  4284. }
  4285. /**
  4286. * @returns The maximum key in the tree.
  4287. */
  4288. maxKey() {
  4289. if (this.right.isEmpty()) {
  4290. return this.key;
  4291. }
  4292. else {
  4293. return this.right.maxKey();
  4294. }
  4295. }
  4296. /**
  4297. * @param key - Key to insert.
  4298. * @param value - Value to insert.
  4299. * @param comparator - Comparator.
  4300. * @returns New tree, with the key/value added.
  4301. */
  4302. insert(key, value, comparator) {
  4303. let n = this;
  4304. const cmp = comparator(key, n.key);
  4305. if (cmp < 0) {
  4306. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4307. }
  4308. else if (cmp === 0) {
  4309. n = n.copy(null, value, null, null, null);
  4310. }
  4311. else {
  4312. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4313. }
  4314. return n.fixUp_();
  4315. }
  4316. /**
  4317. * @returns New tree, with the minimum key removed.
  4318. */
  4319. removeMin_() {
  4320. if (this.left.isEmpty()) {
  4321. return SortedMap.EMPTY_NODE;
  4322. }
  4323. let n = this;
  4324. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4325. n = n.moveRedLeft_();
  4326. }
  4327. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4328. return n.fixUp_();
  4329. }
  4330. /**
  4331. * @param key - The key of the item to remove.
  4332. * @param comparator - Comparator.
  4333. * @returns New tree, with the specified item removed.
  4334. */
  4335. remove(key, comparator) {
  4336. let n, smallest;
  4337. n = this;
  4338. if (comparator(key, n.key) < 0) {
  4339. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4340. n = n.moveRedLeft_();
  4341. }
  4342. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4343. }
  4344. else {
  4345. if (n.left.isRed_()) {
  4346. n = n.rotateRight_();
  4347. }
  4348. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4349. n = n.moveRedRight_();
  4350. }
  4351. if (comparator(key, n.key) === 0) {
  4352. if (n.right.isEmpty()) {
  4353. return SortedMap.EMPTY_NODE;
  4354. }
  4355. else {
  4356. smallest = n.right.min_();
  4357. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4358. }
  4359. }
  4360. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4361. }
  4362. return n.fixUp_();
  4363. }
  4364. /**
  4365. * @returns Whether this is a RED node.
  4366. */
  4367. isRed_() {
  4368. return this.color;
  4369. }
  4370. /**
  4371. * @returns New tree after performing any needed rotations.
  4372. */
  4373. fixUp_() {
  4374. let n = this;
  4375. if (n.right.isRed_() && !n.left.isRed_()) {
  4376. n = n.rotateLeft_();
  4377. }
  4378. if (n.left.isRed_() && n.left.left.isRed_()) {
  4379. n = n.rotateRight_();
  4380. }
  4381. if (n.left.isRed_() && n.right.isRed_()) {
  4382. n = n.colorFlip_();
  4383. }
  4384. return n;
  4385. }
  4386. /**
  4387. * @returns New tree, after moveRedLeft.
  4388. */
  4389. moveRedLeft_() {
  4390. let n = this.colorFlip_();
  4391. if (n.right.left.isRed_()) {
  4392. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4393. n = n.rotateLeft_();
  4394. n = n.colorFlip_();
  4395. }
  4396. return n;
  4397. }
  4398. /**
  4399. * @returns New tree, after moveRedRight.
  4400. */
  4401. moveRedRight_() {
  4402. let n = this.colorFlip_();
  4403. if (n.left.left.isRed_()) {
  4404. n = n.rotateRight_();
  4405. n = n.colorFlip_();
  4406. }
  4407. return n;
  4408. }
  4409. /**
  4410. * @returns New tree, after rotateLeft.
  4411. */
  4412. rotateLeft_() {
  4413. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4414. return this.right.copy(null, null, this.color, nl, null);
  4415. }
  4416. /**
  4417. * @returns New tree, after rotateRight.
  4418. */
  4419. rotateRight_() {
  4420. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4421. return this.left.copy(null, null, this.color, null, nr);
  4422. }
  4423. /**
  4424. * @returns Newt ree, after colorFlip.
  4425. */
  4426. colorFlip_() {
  4427. const left = this.left.copy(null, null, !this.left.color, null, null);
  4428. const right = this.right.copy(null, null, !this.right.color, null, null);
  4429. return this.copy(null, null, !this.color, left, right);
  4430. }
  4431. /**
  4432. * For testing.
  4433. *
  4434. * @returns True if all is well.
  4435. */
  4436. checkMaxDepth_() {
  4437. const blackDepth = this.check_();
  4438. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4439. }
  4440. check_() {
  4441. if (this.isRed_() && this.left.isRed_()) {
  4442. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4443. }
  4444. if (this.right.isRed_()) {
  4445. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4446. }
  4447. const blackDepth = this.left.check_();
  4448. if (blackDepth !== this.right.check_()) {
  4449. throw new Error('Black depths differ');
  4450. }
  4451. else {
  4452. return blackDepth + (this.isRed_() ? 0 : 1);
  4453. }
  4454. }
  4455. }
  4456. LLRBNode.RED = true;
  4457. LLRBNode.BLACK = false;
  4458. /**
  4459. * Represents an empty node (a leaf node in the Red-Black Tree).
  4460. */
  4461. class LLRBEmptyNode {
  4462. /**
  4463. * Returns a copy of the current node.
  4464. *
  4465. * @returns The node copy.
  4466. */
  4467. copy(key, value, color, left, right) {
  4468. return this;
  4469. }
  4470. /**
  4471. * Returns a copy of the tree, with the specified key/value added.
  4472. *
  4473. * @param key - Key to be added.
  4474. * @param value - Value to be added.
  4475. * @param comparator - Comparator.
  4476. * @returns New tree, with item added.
  4477. */
  4478. insert(key, value, comparator) {
  4479. return new LLRBNode(key, value, null);
  4480. }
  4481. /**
  4482. * Returns a copy of the tree, with the specified key removed.
  4483. *
  4484. * @param key - The key to remove.
  4485. * @param comparator - Comparator.
  4486. * @returns New tree, with item removed.
  4487. */
  4488. remove(key, comparator) {
  4489. return this;
  4490. }
  4491. /**
  4492. * @returns The total number of nodes in the tree.
  4493. */
  4494. count() {
  4495. return 0;
  4496. }
  4497. /**
  4498. * @returns True if the tree is empty.
  4499. */
  4500. isEmpty() {
  4501. return true;
  4502. }
  4503. /**
  4504. * Traverses the tree in key order and calls the specified action function
  4505. * for each node.
  4506. *
  4507. * @param action - Callback function to be called for each
  4508. * node. If it returns true, traversal is aborted.
  4509. * @returns True if traversal was aborted.
  4510. */
  4511. inorderTraversal(action) {
  4512. return false;
  4513. }
  4514. /**
  4515. * Traverses the tree in reverse key order and calls the specified action function
  4516. * for each node.
  4517. *
  4518. * @param action - Callback function to be called for each
  4519. * node. If it returns true, traversal is aborted.
  4520. * @returns True if traversal was aborted.
  4521. */
  4522. reverseTraversal(action) {
  4523. return false;
  4524. }
  4525. minKey() {
  4526. return null;
  4527. }
  4528. maxKey() {
  4529. return null;
  4530. }
  4531. check_() {
  4532. return 0;
  4533. }
  4534. /**
  4535. * @returns Whether this node is red.
  4536. */
  4537. isRed_() {
  4538. return false;
  4539. }
  4540. }
  4541. /**
  4542. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4543. * tree.
  4544. */
  4545. class SortedMap {
  4546. /**
  4547. * @param comparator_ - Key comparator.
  4548. * @param root_ - Optional root node for the map.
  4549. */
  4550. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4551. this.comparator_ = comparator_;
  4552. this.root_ = root_;
  4553. }
  4554. /**
  4555. * Returns a copy of the map, with the specified key/value added or replaced.
  4556. * (TODO: We should perhaps rename this method to 'put')
  4557. *
  4558. * @param key - Key to be added.
  4559. * @param value - Value to be added.
  4560. * @returns New map, with item added.
  4561. */
  4562. insert(key, value) {
  4563. return new SortedMap(this.comparator_, this.root_
  4564. .insert(key, value, this.comparator_)
  4565. .copy(null, null, LLRBNode.BLACK, null, null));
  4566. }
  4567. /**
  4568. * Returns a copy of the map, with the specified key removed.
  4569. *
  4570. * @param key - The key to remove.
  4571. * @returns New map, with item removed.
  4572. */
  4573. remove(key) {
  4574. return new SortedMap(this.comparator_, this.root_
  4575. .remove(key, this.comparator_)
  4576. .copy(null, null, LLRBNode.BLACK, null, null));
  4577. }
  4578. /**
  4579. * Returns the value of the node with the given key, or null.
  4580. *
  4581. * @param key - The key to look up.
  4582. * @returns The value of the node with the given key, or null if the
  4583. * key doesn't exist.
  4584. */
  4585. get(key) {
  4586. let cmp;
  4587. let node = this.root_;
  4588. while (!node.isEmpty()) {
  4589. cmp = this.comparator_(key, node.key);
  4590. if (cmp === 0) {
  4591. return node.value;
  4592. }
  4593. else if (cmp < 0) {
  4594. node = node.left;
  4595. }
  4596. else if (cmp > 0) {
  4597. node = node.right;
  4598. }
  4599. }
  4600. return null;
  4601. }
  4602. /**
  4603. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4604. * @param key - The key to find the predecessor of
  4605. * @returns The predecessor key.
  4606. */
  4607. getPredecessorKey(key) {
  4608. let cmp, node = this.root_, rightParent = null;
  4609. while (!node.isEmpty()) {
  4610. cmp = this.comparator_(key, node.key);
  4611. if (cmp === 0) {
  4612. if (!node.left.isEmpty()) {
  4613. node = node.left;
  4614. while (!node.right.isEmpty()) {
  4615. node = node.right;
  4616. }
  4617. return node.key;
  4618. }
  4619. else if (rightParent) {
  4620. return rightParent.key;
  4621. }
  4622. else {
  4623. return null; // first item.
  4624. }
  4625. }
  4626. else if (cmp < 0) {
  4627. node = node.left;
  4628. }
  4629. else if (cmp > 0) {
  4630. rightParent = node;
  4631. node = node.right;
  4632. }
  4633. }
  4634. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4635. }
  4636. /**
  4637. * @returns True if the map is empty.
  4638. */
  4639. isEmpty() {
  4640. return this.root_.isEmpty();
  4641. }
  4642. /**
  4643. * @returns The total number of nodes in the map.
  4644. */
  4645. count() {
  4646. return this.root_.count();
  4647. }
  4648. /**
  4649. * @returns The minimum key in the map.
  4650. */
  4651. minKey() {
  4652. return this.root_.minKey();
  4653. }
  4654. /**
  4655. * @returns The maximum key in the map.
  4656. */
  4657. maxKey() {
  4658. return this.root_.maxKey();
  4659. }
  4660. /**
  4661. * Traverses the map in key order and calls the specified action function
  4662. * for each key/value pair.
  4663. *
  4664. * @param action - Callback function to be called
  4665. * for each key/value pair. If action returns true, traversal is aborted.
  4666. * @returns The first truthy value returned by action, or the last falsey
  4667. * value returned by action
  4668. */
  4669. inorderTraversal(action) {
  4670. return this.root_.inorderTraversal(action);
  4671. }
  4672. /**
  4673. * Traverses the map in reverse key order and calls the specified action function
  4674. * for each key/value pair.
  4675. *
  4676. * @param action - Callback function to be called
  4677. * for each key/value pair. If action returns true, traversal is aborted.
  4678. * @returns True if the traversal was aborted.
  4679. */
  4680. reverseTraversal(action) {
  4681. return this.root_.reverseTraversal(action);
  4682. }
  4683. /**
  4684. * Returns an iterator over the SortedMap.
  4685. * @returns The iterator.
  4686. */
  4687. getIterator(resultGenerator) {
  4688. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4689. }
  4690. getIteratorFrom(key, resultGenerator) {
  4691. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4692. }
  4693. getReverseIteratorFrom(key, resultGenerator) {
  4694. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4695. }
  4696. getReverseIterator(resultGenerator) {
  4697. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4698. }
  4699. }
  4700. /**
  4701. * Always use the same empty node, to reduce memory.
  4702. */
  4703. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4704. /**
  4705. * @license
  4706. * Copyright 2017 Google LLC
  4707. *
  4708. * Licensed under the Apache License, Version 2.0 (the "License");
  4709. * you may not use this file except in compliance with the License.
  4710. * You may obtain a copy of the License at
  4711. *
  4712. * http://www.apache.org/licenses/LICENSE-2.0
  4713. *
  4714. * Unless required by applicable law or agreed to in writing, software
  4715. * distributed under the License is distributed on an "AS IS" BASIS,
  4716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4717. * See the License for the specific language governing permissions and
  4718. * limitations under the License.
  4719. */
  4720. function NAME_ONLY_COMPARATOR(left, right) {
  4721. return nameCompare(left.name, right.name);
  4722. }
  4723. function NAME_COMPARATOR(left, right) {
  4724. return nameCompare(left, right);
  4725. }
  4726. /**
  4727. * @license
  4728. * Copyright 2017 Google LLC
  4729. *
  4730. * Licensed under the Apache License, Version 2.0 (the "License");
  4731. * you may not use this file except in compliance with the License.
  4732. * You may obtain a copy of the License at
  4733. *
  4734. * http://www.apache.org/licenses/LICENSE-2.0
  4735. *
  4736. * Unless required by applicable law or agreed to in writing, software
  4737. * distributed under the License is distributed on an "AS IS" BASIS,
  4738. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4739. * See the License for the specific language governing permissions and
  4740. * limitations under the License.
  4741. */
  4742. let MAX_NODE$2;
  4743. function setMaxNode$1(val) {
  4744. MAX_NODE$2 = val;
  4745. }
  4746. const priorityHashText = function (priority) {
  4747. if (typeof priority === 'number') {
  4748. return 'number:' + doubleToIEEE754String(priority);
  4749. }
  4750. else {
  4751. return 'string:' + priority;
  4752. }
  4753. };
  4754. /**
  4755. * Validates that a priority snapshot Node is valid.
  4756. */
  4757. const validatePriorityNode = function (priorityNode) {
  4758. if (priorityNode.isLeafNode()) {
  4759. const val = priorityNode.val();
  4760. assert(typeof val === 'string' ||
  4761. typeof val === 'number' ||
  4762. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4763. }
  4764. else {
  4765. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4766. }
  4767. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4768. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4769. };
  4770. /**
  4771. * @license
  4772. * Copyright 2017 Google LLC
  4773. *
  4774. * Licensed under the Apache License, Version 2.0 (the "License");
  4775. * you may not use this file except in compliance with the License.
  4776. * You may obtain a copy of the License at
  4777. *
  4778. * http://www.apache.org/licenses/LICENSE-2.0
  4779. *
  4780. * Unless required by applicable law or agreed to in writing, software
  4781. * distributed under the License is distributed on an "AS IS" BASIS,
  4782. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4783. * See the License for the specific language governing permissions and
  4784. * limitations under the License.
  4785. */
  4786. let __childrenNodeConstructor;
  4787. /**
  4788. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4789. * implements Node and stores the value of the node (a string,
  4790. * number, or boolean) accessible via getValue().
  4791. */
  4792. class LeafNode {
  4793. /**
  4794. * @param value_ - The value to store in this leaf node. The object type is
  4795. * possible in the event of a deferred value
  4796. * @param priorityNode_ - The priority of this node.
  4797. */
  4798. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4799. this.value_ = value_;
  4800. this.priorityNode_ = priorityNode_;
  4801. this.lazyHash_ = null;
  4802. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4803. validatePriorityNode(this.priorityNode_);
  4804. }
  4805. static set __childrenNodeConstructor(val) {
  4806. __childrenNodeConstructor = val;
  4807. }
  4808. static get __childrenNodeConstructor() {
  4809. return __childrenNodeConstructor;
  4810. }
  4811. /** @inheritDoc */
  4812. isLeafNode() {
  4813. return true;
  4814. }
  4815. /** @inheritDoc */
  4816. getPriority() {
  4817. return this.priorityNode_;
  4818. }
  4819. /** @inheritDoc */
  4820. updatePriority(newPriorityNode) {
  4821. return new LeafNode(this.value_, newPriorityNode);
  4822. }
  4823. /** @inheritDoc */
  4824. getImmediateChild(childName) {
  4825. // Hack to treat priority as a regular child
  4826. if (childName === '.priority') {
  4827. return this.priorityNode_;
  4828. }
  4829. else {
  4830. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4831. }
  4832. }
  4833. /** @inheritDoc */
  4834. getChild(path) {
  4835. if (pathIsEmpty(path)) {
  4836. return this;
  4837. }
  4838. else if (pathGetFront(path) === '.priority') {
  4839. return this.priorityNode_;
  4840. }
  4841. else {
  4842. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4843. }
  4844. }
  4845. hasChild() {
  4846. return false;
  4847. }
  4848. /** @inheritDoc */
  4849. getPredecessorChildName(childName, childNode) {
  4850. return null;
  4851. }
  4852. /** @inheritDoc */
  4853. updateImmediateChild(childName, newChildNode) {
  4854. if (childName === '.priority') {
  4855. return this.updatePriority(newChildNode);
  4856. }
  4857. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4858. return this;
  4859. }
  4860. else {
  4861. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4862. }
  4863. }
  4864. /** @inheritDoc */
  4865. updateChild(path, newChildNode) {
  4866. const front = pathGetFront(path);
  4867. if (front === null) {
  4868. return newChildNode;
  4869. }
  4870. else if (newChildNode.isEmpty() && front !== '.priority') {
  4871. return this;
  4872. }
  4873. else {
  4874. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4875. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4876. }
  4877. }
  4878. /** @inheritDoc */
  4879. isEmpty() {
  4880. return false;
  4881. }
  4882. /** @inheritDoc */
  4883. numChildren() {
  4884. return 0;
  4885. }
  4886. /** @inheritDoc */
  4887. forEachChild(index, action) {
  4888. return false;
  4889. }
  4890. val(exportFormat) {
  4891. if (exportFormat && !this.getPriority().isEmpty()) {
  4892. return {
  4893. '.value': this.getValue(),
  4894. '.priority': this.getPriority().val()
  4895. };
  4896. }
  4897. else {
  4898. return this.getValue();
  4899. }
  4900. }
  4901. /** @inheritDoc */
  4902. hash() {
  4903. if (this.lazyHash_ === null) {
  4904. let toHash = '';
  4905. if (!this.priorityNode_.isEmpty()) {
  4906. toHash +=
  4907. 'priority:' +
  4908. priorityHashText(this.priorityNode_.val()) +
  4909. ':';
  4910. }
  4911. const type = typeof this.value_;
  4912. toHash += type + ':';
  4913. if (type === 'number') {
  4914. toHash += doubleToIEEE754String(this.value_);
  4915. }
  4916. else {
  4917. toHash += this.value_;
  4918. }
  4919. this.lazyHash_ = sha1(toHash);
  4920. }
  4921. return this.lazyHash_;
  4922. }
  4923. /**
  4924. * Returns the value of the leaf node.
  4925. * @returns The value of the node.
  4926. */
  4927. getValue() {
  4928. return this.value_;
  4929. }
  4930. compareTo(other) {
  4931. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4932. return 1;
  4933. }
  4934. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4935. return -1;
  4936. }
  4937. else {
  4938. assert(other.isLeafNode(), 'Unknown node type');
  4939. return this.compareToLeafNode_(other);
  4940. }
  4941. }
  4942. /**
  4943. * Comparison specifically for two leaf nodes
  4944. */
  4945. compareToLeafNode_(otherLeaf) {
  4946. const otherLeafType = typeof otherLeaf.value_;
  4947. const thisLeafType = typeof this.value_;
  4948. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4949. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4950. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4951. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4952. if (otherIndex === thisIndex) {
  4953. // Same type, compare values
  4954. if (thisLeafType === 'object') {
  4955. // Deferred value nodes are all equal, but we should also never get to this point...
  4956. return 0;
  4957. }
  4958. else {
  4959. // Note that this works because true > false, all others are number or string comparisons
  4960. if (this.value_ < otherLeaf.value_) {
  4961. return -1;
  4962. }
  4963. else if (this.value_ === otherLeaf.value_) {
  4964. return 0;
  4965. }
  4966. else {
  4967. return 1;
  4968. }
  4969. }
  4970. }
  4971. else {
  4972. return thisIndex - otherIndex;
  4973. }
  4974. }
  4975. withIndex() {
  4976. return this;
  4977. }
  4978. isIndexed() {
  4979. return true;
  4980. }
  4981. equals(other) {
  4982. if (other === this) {
  4983. return true;
  4984. }
  4985. else if (other.isLeafNode()) {
  4986. const otherLeaf = other;
  4987. return (this.value_ === otherLeaf.value_ &&
  4988. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4989. }
  4990. else {
  4991. return false;
  4992. }
  4993. }
  4994. }
  4995. /**
  4996. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  4997. * the same type, the comparison falls back to their value
  4998. */
  4999. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5000. /**
  5001. * @license
  5002. * Copyright 2017 Google LLC
  5003. *
  5004. * Licensed under the Apache License, Version 2.0 (the "License");
  5005. * you may not use this file except in compliance with the License.
  5006. * You may obtain a copy of the License at
  5007. *
  5008. * http://www.apache.org/licenses/LICENSE-2.0
  5009. *
  5010. * Unless required by applicable law or agreed to in writing, software
  5011. * distributed under the License is distributed on an "AS IS" BASIS,
  5012. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5013. * See the License for the specific language governing permissions and
  5014. * limitations under the License.
  5015. */
  5016. let nodeFromJSON$1;
  5017. let MAX_NODE$1;
  5018. function setNodeFromJSON(val) {
  5019. nodeFromJSON$1 = val;
  5020. }
  5021. function setMaxNode(val) {
  5022. MAX_NODE$1 = val;
  5023. }
  5024. class PriorityIndex extends Index {
  5025. compare(a, b) {
  5026. const aPriority = a.node.getPriority();
  5027. const bPriority = b.node.getPriority();
  5028. const indexCmp = aPriority.compareTo(bPriority);
  5029. if (indexCmp === 0) {
  5030. return nameCompare(a.name, b.name);
  5031. }
  5032. else {
  5033. return indexCmp;
  5034. }
  5035. }
  5036. isDefinedOn(node) {
  5037. return !node.getPriority().isEmpty();
  5038. }
  5039. indexedValueChanged(oldNode, newNode) {
  5040. return !oldNode.getPriority().equals(newNode.getPriority());
  5041. }
  5042. minPost() {
  5043. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5044. return NamedNode.MIN;
  5045. }
  5046. maxPost() {
  5047. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5048. }
  5049. makePost(indexValue, name) {
  5050. const priorityNode = nodeFromJSON$1(indexValue);
  5051. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5052. }
  5053. /**
  5054. * @returns String representation for inclusion in a query spec
  5055. */
  5056. toString() {
  5057. return '.priority';
  5058. }
  5059. }
  5060. const PRIORITY_INDEX = new PriorityIndex();
  5061. /**
  5062. * @license
  5063. * Copyright 2017 Google LLC
  5064. *
  5065. * Licensed under the Apache License, Version 2.0 (the "License");
  5066. * you may not use this file except in compliance with the License.
  5067. * You may obtain a copy of the License at
  5068. *
  5069. * http://www.apache.org/licenses/LICENSE-2.0
  5070. *
  5071. * Unless required by applicable law or agreed to in writing, software
  5072. * distributed under the License is distributed on an "AS IS" BASIS,
  5073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5074. * See the License for the specific language governing permissions and
  5075. * limitations under the License.
  5076. */
  5077. const LOG_2 = Math.log(2);
  5078. class Base12Num {
  5079. constructor(length) {
  5080. const logBase2 = (num) =>
  5081. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5082. parseInt((Math.log(num) / LOG_2), 10);
  5083. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5084. this.count = logBase2(length + 1);
  5085. this.current_ = this.count - 1;
  5086. const mask = bitMask(this.count);
  5087. this.bits_ = (length + 1) & mask;
  5088. }
  5089. nextBitIsOne() {
  5090. //noinspection JSBitwiseOperatorUsage
  5091. const result = !(this.bits_ & (0x1 << this.current_));
  5092. this.current_--;
  5093. return result;
  5094. }
  5095. }
  5096. /**
  5097. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5098. * function
  5099. *
  5100. * Uses the algorithm described in the paper linked here:
  5101. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5102. *
  5103. * @param childList - Unsorted list of children
  5104. * @param cmp - The comparison method to be used
  5105. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5106. * type is not NamedNode
  5107. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5108. */
  5109. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5110. childList.sort(cmp);
  5111. const buildBalancedTree = function (low, high) {
  5112. const length = high - low;
  5113. let namedNode;
  5114. let key;
  5115. if (length === 0) {
  5116. return null;
  5117. }
  5118. else if (length === 1) {
  5119. namedNode = childList[low];
  5120. key = keyFn ? keyFn(namedNode) : namedNode;
  5121. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5122. }
  5123. else {
  5124. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5125. const middle = parseInt((length / 2), 10) + low;
  5126. const left = buildBalancedTree(low, middle);
  5127. const right = buildBalancedTree(middle + 1, high);
  5128. namedNode = childList[middle];
  5129. key = keyFn ? keyFn(namedNode) : namedNode;
  5130. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5131. }
  5132. };
  5133. const buildFrom12Array = function (base12) {
  5134. let node = null;
  5135. let root = null;
  5136. let index = childList.length;
  5137. const buildPennant = function (chunkSize, color) {
  5138. const low = index - chunkSize;
  5139. const high = index;
  5140. index -= chunkSize;
  5141. const childTree = buildBalancedTree(low + 1, high);
  5142. const namedNode = childList[low];
  5143. const key = keyFn ? keyFn(namedNode) : namedNode;
  5144. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5145. };
  5146. const attachPennant = function (pennant) {
  5147. if (node) {
  5148. node.left = pennant;
  5149. node = pennant;
  5150. }
  5151. else {
  5152. root = pennant;
  5153. node = pennant;
  5154. }
  5155. };
  5156. for (let i = 0; i < base12.count; ++i) {
  5157. const isOne = base12.nextBitIsOne();
  5158. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5159. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5160. if (isOne) {
  5161. buildPennant(chunkSize, LLRBNode.BLACK);
  5162. }
  5163. else {
  5164. // current == 2
  5165. buildPennant(chunkSize, LLRBNode.BLACK);
  5166. buildPennant(chunkSize, LLRBNode.RED);
  5167. }
  5168. }
  5169. return root;
  5170. };
  5171. const base12 = new Base12Num(childList.length);
  5172. const root = buildFrom12Array(base12);
  5173. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5174. return new SortedMap(mapSortFn || cmp, root);
  5175. };
  5176. /**
  5177. * @license
  5178. * Copyright 2017 Google LLC
  5179. *
  5180. * Licensed under the Apache License, Version 2.0 (the "License");
  5181. * you may not use this file except in compliance with the License.
  5182. * You may obtain a copy of the License at
  5183. *
  5184. * http://www.apache.org/licenses/LICENSE-2.0
  5185. *
  5186. * Unless required by applicable law or agreed to in writing, software
  5187. * distributed under the License is distributed on an "AS IS" BASIS,
  5188. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5189. * See the License for the specific language governing permissions and
  5190. * limitations under the License.
  5191. */
  5192. let _defaultIndexMap;
  5193. const fallbackObject = {};
  5194. class IndexMap {
  5195. constructor(indexes_, indexSet_) {
  5196. this.indexes_ = indexes_;
  5197. this.indexSet_ = indexSet_;
  5198. }
  5199. /**
  5200. * The default IndexMap for nodes without a priority
  5201. */
  5202. static get Default() {
  5203. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5204. _defaultIndexMap =
  5205. _defaultIndexMap ||
  5206. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5207. return _defaultIndexMap;
  5208. }
  5209. get(indexKey) {
  5210. const sortedMap = safeGet(this.indexes_, indexKey);
  5211. if (!sortedMap) {
  5212. throw new Error('No index defined for ' + indexKey);
  5213. }
  5214. if (sortedMap instanceof SortedMap) {
  5215. return sortedMap;
  5216. }
  5217. else {
  5218. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5219. // regular child map
  5220. return null;
  5221. }
  5222. }
  5223. hasIndex(indexDefinition) {
  5224. return contains(this.indexSet_, indexDefinition.toString());
  5225. }
  5226. addIndex(indexDefinition, existingChildren) {
  5227. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5228. const childList = [];
  5229. let sawIndexedValue = false;
  5230. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5231. let next = iter.getNext();
  5232. while (next) {
  5233. sawIndexedValue =
  5234. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5235. childList.push(next);
  5236. next = iter.getNext();
  5237. }
  5238. let newIndex;
  5239. if (sawIndexedValue) {
  5240. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5241. }
  5242. else {
  5243. newIndex = fallbackObject;
  5244. }
  5245. const indexName = indexDefinition.toString();
  5246. const newIndexSet = Object.assign({}, this.indexSet_);
  5247. newIndexSet[indexName] = indexDefinition;
  5248. const newIndexes = Object.assign({}, this.indexes_);
  5249. newIndexes[indexName] = newIndex;
  5250. return new IndexMap(newIndexes, newIndexSet);
  5251. }
  5252. /**
  5253. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5254. */
  5255. addToIndexes(namedNode, existingChildren) {
  5256. const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
  5257. const index = safeGet(this.indexSet_, indexName);
  5258. assert(index, 'Missing index implementation for ' + indexName);
  5259. if (indexedChildren === fallbackObject) {
  5260. // Check to see if we need to index everything
  5261. if (index.isDefinedOn(namedNode.node)) {
  5262. // We need to build this index
  5263. const childList = [];
  5264. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5265. let next = iter.getNext();
  5266. while (next) {
  5267. if (next.name !== namedNode.name) {
  5268. childList.push(next);
  5269. }
  5270. next = iter.getNext();
  5271. }
  5272. childList.push(namedNode);
  5273. return buildChildSet(childList, index.getCompare());
  5274. }
  5275. else {
  5276. // No change, this remains a fallback
  5277. return fallbackObject;
  5278. }
  5279. }
  5280. else {
  5281. const existingSnap = existingChildren.get(namedNode.name);
  5282. let newChildren = indexedChildren;
  5283. if (existingSnap) {
  5284. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5285. }
  5286. return newChildren.insert(namedNode, namedNode.node);
  5287. }
  5288. });
  5289. return new IndexMap(newIndexes, this.indexSet_);
  5290. }
  5291. /**
  5292. * Create a new IndexMap instance with the given value removed
  5293. */
  5294. removeFromIndexes(namedNode, existingChildren) {
  5295. const newIndexes = map(this.indexes_, (indexedChildren) => {
  5296. if (indexedChildren === fallbackObject) {
  5297. // This is the fallback. Just return it, nothing to do in this case
  5298. return indexedChildren;
  5299. }
  5300. else {
  5301. const existingSnap = existingChildren.get(namedNode.name);
  5302. if (existingSnap) {
  5303. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5304. }
  5305. else {
  5306. // No record of this child
  5307. return indexedChildren;
  5308. }
  5309. }
  5310. });
  5311. return new IndexMap(newIndexes, this.indexSet_);
  5312. }
  5313. }
  5314. /**
  5315. * @license
  5316. * Copyright 2017 Google LLC
  5317. *
  5318. * Licensed under the Apache License, Version 2.0 (the "License");
  5319. * you may not use this file except in compliance with the License.
  5320. * You may obtain a copy of the License at
  5321. *
  5322. * http://www.apache.org/licenses/LICENSE-2.0
  5323. *
  5324. * Unless required by applicable law or agreed to in writing, software
  5325. * distributed under the License is distributed on an "AS IS" BASIS,
  5326. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5327. * See the License for the specific language governing permissions and
  5328. * limitations under the License.
  5329. */
  5330. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5331. let EMPTY_NODE;
  5332. /**
  5333. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5334. * (i.e. nodes with children). It implements Node and stores the
  5335. * list of children in the children property, sorted by child name.
  5336. */
  5337. class ChildrenNode {
  5338. /**
  5339. * @param children_ - List of children of this node..
  5340. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5341. */
  5342. constructor(children_, priorityNode_, indexMap_) {
  5343. this.children_ = children_;
  5344. this.priorityNode_ = priorityNode_;
  5345. this.indexMap_ = indexMap_;
  5346. this.lazyHash_ = null;
  5347. /**
  5348. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5349. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5350. * class instead of an empty ChildrenNode.
  5351. */
  5352. if (this.priorityNode_) {
  5353. validatePriorityNode(this.priorityNode_);
  5354. }
  5355. if (this.children_.isEmpty()) {
  5356. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5357. }
  5358. }
  5359. static get EMPTY_NODE() {
  5360. return (EMPTY_NODE ||
  5361. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5362. }
  5363. /** @inheritDoc */
  5364. isLeafNode() {
  5365. return false;
  5366. }
  5367. /** @inheritDoc */
  5368. getPriority() {
  5369. return this.priorityNode_ || EMPTY_NODE;
  5370. }
  5371. /** @inheritDoc */
  5372. updatePriority(newPriorityNode) {
  5373. if (this.children_.isEmpty()) {
  5374. // Don't allow priorities on empty nodes
  5375. return this;
  5376. }
  5377. else {
  5378. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5379. }
  5380. }
  5381. /** @inheritDoc */
  5382. getImmediateChild(childName) {
  5383. // Hack to treat priority as a regular child
  5384. if (childName === '.priority') {
  5385. return this.getPriority();
  5386. }
  5387. else {
  5388. const child = this.children_.get(childName);
  5389. return child === null ? EMPTY_NODE : child;
  5390. }
  5391. }
  5392. /** @inheritDoc */
  5393. getChild(path) {
  5394. const front = pathGetFront(path);
  5395. if (front === null) {
  5396. return this;
  5397. }
  5398. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5399. }
  5400. /** @inheritDoc */
  5401. hasChild(childName) {
  5402. return this.children_.get(childName) !== null;
  5403. }
  5404. /** @inheritDoc */
  5405. updateImmediateChild(childName, newChildNode) {
  5406. assert(newChildNode, 'We should always be passing snapshot nodes');
  5407. if (childName === '.priority') {
  5408. return this.updatePriority(newChildNode);
  5409. }
  5410. else {
  5411. const namedNode = new NamedNode(childName, newChildNode);
  5412. let newChildren, newIndexMap;
  5413. if (newChildNode.isEmpty()) {
  5414. newChildren = this.children_.remove(childName);
  5415. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5416. }
  5417. else {
  5418. newChildren = this.children_.insert(childName, newChildNode);
  5419. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5420. }
  5421. const newPriority = newChildren.isEmpty()
  5422. ? EMPTY_NODE
  5423. : this.priorityNode_;
  5424. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5425. }
  5426. }
  5427. /** @inheritDoc */
  5428. updateChild(path, newChildNode) {
  5429. const front = pathGetFront(path);
  5430. if (front === null) {
  5431. return newChildNode;
  5432. }
  5433. else {
  5434. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5435. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5436. return this.updateImmediateChild(front, newImmediateChild);
  5437. }
  5438. }
  5439. /** @inheritDoc */
  5440. isEmpty() {
  5441. return this.children_.isEmpty();
  5442. }
  5443. /** @inheritDoc */
  5444. numChildren() {
  5445. return this.children_.count();
  5446. }
  5447. /** @inheritDoc */
  5448. val(exportFormat) {
  5449. if (this.isEmpty()) {
  5450. return null;
  5451. }
  5452. const obj = {};
  5453. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5454. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5455. obj[key] = childNode.val(exportFormat);
  5456. numKeys++;
  5457. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5458. maxKey = Math.max(maxKey, Number(key));
  5459. }
  5460. else {
  5461. allIntegerKeys = false;
  5462. }
  5463. });
  5464. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5465. // convert to array.
  5466. const array = [];
  5467. // eslint-disable-next-line guard-for-in
  5468. for (const key in obj) {
  5469. array[key] = obj[key];
  5470. }
  5471. return array;
  5472. }
  5473. else {
  5474. if (exportFormat && !this.getPriority().isEmpty()) {
  5475. obj['.priority'] = this.getPriority().val();
  5476. }
  5477. return obj;
  5478. }
  5479. }
  5480. /** @inheritDoc */
  5481. hash() {
  5482. if (this.lazyHash_ === null) {
  5483. let toHash = '';
  5484. if (!this.getPriority().isEmpty()) {
  5485. toHash +=
  5486. 'priority:' +
  5487. priorityHashText(this.getPriority().val()) +
  5488. ':';
  5489. }
  5490. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5491. const childHash = childNode.hash();
  5492. if (childHash !== '') {
  5493. toHash += ':' + key + ':' + childHash;
  5494. }
  5495. });
  5496. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5497. }
  5498. return this.lazyHash_;
  5499. }
  5500. /** @inheritDoc */
  5501. getPredecessorChildName(childName, childNode, index) {
  5502. const idx = this.resolveIndex_(index);
  5503. if (idx) {
  5504. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5505. return predecessor ? predecessor.name : null;
  5506. }
  5507. else {
  5508. return this.children_.getPredecessorKey(childName);
  5509. }
  5510. }
  5511. getFirstChildName(indexDefinition) {
  5512. const idx = this.resolveIndex_(indexDefinition);
  5513. if (idx) {
  5514. const minKey = idx.minKey();
  5515. return minKey && minKey.name;
  5516. }
  5517. else {
  5518. return this.children_.minKey();
  5519. }
  5520. }
  5521. getFirstChild(indexDefinition) {
  5522. const minKey = this.getFirstChildName(indexDefinition);
  5523. if (minKey) {
  5524. return new NamedNode(minKey, this.children_.get(minKey));
  5525. }
  5526. else {
  5527. return null;
  5528. }
  5529. }
  5530. /**
  5531. * Given an index, return the key name of the largest value we have, according to that index
  5532. */
  5533. getLastChildName(indexDefinition) {
  5534. const idx = this.resolveIndex_(indexDefinition);
  5535. if (idx) {
  5536. const maxKey = idx.maxKey();
  5537. return maxKey && maxKey.name;
  5538. }
  5539. else {
  5540. return this.children_.maxKey();
  5541. }
  5542. }
  5543. getLastChild(indexDefinition) {
  5544. const maxKey = this.getLastChildName(indexDefinition);
  5545. if (maxKey) {
  5546. return new NamedNode(maxKey, this.children_.get(maxKey));
  5547. }
  5548. else {
  5549. return null;
  5550. }
  5551. }
  5552. forEachChild(index, action) {
  5553. const idx = this.resolveIndex_(index);
  5554. if (idx) {
  5555. return idx.inorderTraversal(wrappedNode => {
  5556. return action(wrappedNode.name, wrappedNode.node);
  5557. });
  5558. }
  5559. else {
  5560. return this.children_.inorderTraversal(action);
  5561. }
  5562. }
  5563. getIterator(indexDefinition) {
  5564. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5565. }
  5566. getIteratorFrom(startPost, indexDefinition) {
  5567. const idx = this.resolveIndex_(indexDefinition);
  5568. if (idx) {
  5569. return idx.getIteratorFrom(startPost, key => key);
  5570. }
  5571. else {
  5572. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5573. let next = iterator.peek();
  5574. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5575. iterator.getNext();
  5576. next = iterator.peek();
  5577. }
  5578. return iterator;
  5579. }
  5580. }
  5581. getReverseIterator(indexDefinition) {
  5582. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5583. }
  5584. getReverseIteratorFrom(endPost, indexDefinition) {
  5585. const idx = this.resolveIndex_(indexDefinition);
  5586. if (idx) {
  5587. return idx.getReverseIteratorFrom(endPost, key => {
  5588. return key;
  5589. });
  5590. }
  5591. else {
  5592. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5593. let next = iterator.peek();
  5594. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5595. iterator.getNext();
  5596. next = iterator.peek();
  5597. }
  5598. return iterator;
  5599. }
  5600. }
  5601. compareTo(other) {
  5602. if (this.isEmpty()) {
  5603. if (other.isEmpty()) {
  5604. return 0;
  5605. }
  5606. else {
  5607. return -1;
  5608. }
  5609. }
  5610. else if (other.isLeafNode() || other.isEmpty()) {
  5611. return 1;
  5612. }
  5613. else if (other === MAX_NODE) {
  5614. return -1;
  5615. }
  5616. else {
  5617. // Must be another node with children.
  5618. return 0;
  5619. }
  5620. }
  5621. withIndex(indexDefinition) {
  5622. if (indexDefinition === KEY_INDEX ||
  5623. this.indexMap_.hasIndex(indexDefinition)) {
  5624. return this;
  5625. }
  5626. else {
  5627. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5628. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5629. }
  5630. }
  5631. isIndexed(index) {
  5632. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5633. }
  5634. equals(other) {
  5635. if (other === this) {
  5636. return true;
  5637. }
  5638. else if (other.isLeafNode()) {
  5639. return false;
  5640. }
  5641. else {
  5642. const otherChildrenNode = other;
  5643. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5644. return false;
  5645. }
  5646. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5647. const thisIter = this.getIterator(PRIORITY_INDEX);
  5648. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5649. let thisCurrent = thisIter.getNext();
  5650. let otherCurrent = otherIter.getNext();
  5651. while (thisCurrent && otherCurrent) {
  5652. if (thisCurrent.name !== otherCurrent.name ||
  5653. !thisCurrent.node.equals(otherCurrent.node)) {
  5654. return false;
  5655. }
  5656. thisCurrent = thisIter.getNext();
  5657. otherCurrent = otherIter.getNext();
  5658. }
  5659. return thisCurrent === null && otherCurrent === null;
  5660. }
  5661. else {
  5662. return false;
  5663. }
  5664. }
  5665. }
  5666. /**
  5667. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5668. * instead.
  5669. *
  5670. */
  5671. resolveIndex_(indexDefinition) {
  5672. if (indexDefinition === KEY_INDEX) {
  5673. return null;
  5674. }
  5675. else {
  5676. return this.indexMap_.get(indexDefinition.toString());
  5677. }
  5678. }
  5679. }
  5680. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5681. class MaxNode extends ChildrenNode {
  5682. constructor() {
  5683. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5684. }
  5685. compareTo(other) {
  5686. if (other === this) {
  5687. return 0;
  5688. }
  5689. else {
  5690. return 1;
  5691. }
  5692. }
  5693. equals(other) {
  5694. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5695. return other === this;
  5696. }
  5697. getPriority() {
  5698. return this;
  5699. }
  5700. getImmediateChild(childName) {
  5701. return ChildrenNode.EMPTY_NODE;
  5702. }
  5703. isEmpty() {
  5704. return false;
  5705. }
  5706. }
  5707. /**
  5708. * Marker that will sort higher than any other snapshot.
  5709. */
  5710. const MAX_NODE = new MaxNode();
  5711. Object.defineProperties(NamedNode, {
  5712. MIN: {
  5713. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5714. },
  5715. MAX: {
  5716. value: new NamedNode(MAX_NAME, MAX_NODE)
  5717. }
  5718. });
  5719. /**
  5720. * Reference Extensions
  5721. */
  5722. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5723. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5724. setMaxNode$1(MAX_NODE);
  5725. setMaxNode(MAX_NODE);
  5726. /**
  5727. * @license
  5728. * Copyright 2017 Google LLC
  5729. *
  5730. * Licensed under the Apache License, Version 2.0 (the "License");
  5731. * you may not use this file except in compliance with the License.
  5732. * You may obtain a copy of the License at
  5733. *
  5734. * http://www.apache.org/licenses/LICENSE-2.0
  5735. *
  5736. * Unless required by applicable law or agreed to in writing, software
  5737. * distributed under the License is distributed on an "AS IS" BASIS,
  5738. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5739. * See the License for the specific language governing permissions and
  5740. * limitations under the License.
  5741. */
  5742. const USE_HINZE = true;
  5743. /**
  5744. * Constructs a snapshot node representing the passed JSON and returns it.
  5745. * @param json - JSON to create a node for.
  5746. * @param priority - Optional priority to use. This will be ignored if the
  5747. * passed JSON contains a .priority property.
  5748. */
  5749. function nodeFromJSON(json, priority = null) {
  5750. if (json === null) {
  5751. return ChildrenNode.EMPTY_NODE;
  5752. }
  5753. if (typeof json === 'object' && '.priority' in json) {
  5754. priority = json['.priority'];
  5755. }
  5756. assert(priority === null ||
  5757. typeof priority === 'string' ||
  5758. typeof priority === 'number' ||
  5759. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5760. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5761. json = json['.value'];
  5762. }
  5763. // Valid leaf nodes include non-objects or server-value wrapper objects
  5764. if (typeof json !== 'object' || '.sv' in json) {
  5765. const jsonLeaf = json;
  5766. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5767. }
  5768. if (!(json instanceof Array) && USE_HINZE) {
  5769. const children = [];
  5770. let childrenHavePriority = false;
  5771. const hinzeJsonObj = json;
  5772. each(hinzeJsonObj, (key, child) => {
  5773. if (key.substring(0, 1) !== '.') {
  5774. // Ignore metadata nodes
  5775. const childNode = nodeFromJSON(child);
  5776. if (!childNode.isEmpty()) {
  5777. childrenHavePriority =
  5778. childrenHavePriority || !childNode.getPriority().isEmpty();
  5779. children.push(new NamedNode(key, childNode));
  5780. }
  5781. }
  5782. });
  5783. if (children.length === 0) {
  5784. return ChildrenNode.EMPTY_NODE;
  5785. }
  5786. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5787. if (childrenHavePriority) {
  5788. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5789. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5790. }
  5791. else {
  5792. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5793. }
  5794. }
  5795. else {
  5796. let node = ChildrenNode.EMPTY_NODE;
  5797. each(json, (key, childData) => {
  5798. if (contains(json, key)) {
  5799. if (key.substring(0, 1) !== '.') {
  5800. // ignore metadata nodes.
  5801. const childNode = nodeFromJSON(childData);
  5802. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5803. node = node.updateImmediateChild(key, childNode);
  5804. }
  5805. }
  5806. }
  5807. });
  5808. return node.updatePriority(nodeFromJSON(priority));
  5809. }
  5810. }
  5811. setNodeFromJSON(nodeFromJSON);
  5812. /**
  5813. * @license
  5814. * Copyright 2017 Google LLC
  5815. *
  5816. * Licensed under the Apache License, Version 2.0 (the "License");
  5817. * you may not use this file except in compliance with the License.
  5818. * You may obtain a copy of the License at
  5819. *
  5820. * http://www.apache.org/licenses/LICENSE-2.0
  5821. *
  5822. * Unless required by applicable law or agreed to in writing, software
  5823. * distributed under the License is distributed on an "AS IS" BASIS,
  5824. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5825. * See the License for the specific language governing permissions and
  5826. * limitations under the License.
  5827. */
  5828. class PathIndex extends Index {
  5829. constructor(indexPath_) {
  5830. super();
  5831. this.indexPath_ = indexPath_;
  5832. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5833. }
  5834. extractChild(snap) {
  5835. return snap.getChild(this.indexPath_);
  5836. }
  5837. isDefinedOn(node) {
  5838. return !node.getChild(this.indexPath_).isEmpty();
  5839. }
  5840. compare(a, b) {
  5841. const aChild = this.extractChild(a.node);
  5842. const bChild = this.extractChild(b.node);
  5843. const indexCmp = aChild.compareTo(bChild);
  5844. if (indexCmp === 0) {
  5845. return nameCompare(a.name, b.name);
  5846. }
  5847. else {
  5848. return indexCmp;
  5849. }
  5850. }
  5851. makePost(indexValue, name) {
  5852. const valueNode = nodeFromJSON(indexValue);
  5853. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5854. return new NamedNode(name, node);
  5855. }
  5856. maxPost() {
  5857. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5858. return new NamedNode(MAX_NAME, node);
  5859. }
  5860. toString() {
  5861. return pathSlice(this.indexPath_, 0).join('/');
  5862. }
  5863. }
  5864. /**
  5865. * @license
  5866. * Copyright 2017 Google LLC
  5867. *
  5868. * Licensed under the Apache License, Version 2.0 (the "License");
  5869. * you may not use this file except in compliance with the License.
  5870. * You may obtain a copy of the License at
  5871. *
  5872. * http://www.apache.org/licenses/LICENSE-2.0
  5873. *
  5874. * Unless required by applicable law or agreed to in writing, software
  5875. * distributed under the License is distributed on an "AS IS" BASIS,
  5876. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5877. * See the License for the specific language governing permissions and
  5878. * limitations under the License.
  5879. */
  5880. class ValueIndex extends Index {
  5881. compare(a, b) {
  5882. const indexCmp = a.node.compareTo(b.node);
  5883. if (indexCmp === 0) {
  5884. return nameCompare(a.name, b.name);
  5885. }
  5886. else {
  5887. return indexCmp;
  5888. }
  5889. }
  5890. isDefinedOn(node) {
  5891. return true;
  5892. }
  5893. indexedValueChanged(oldNode, newNode) {
  5894. return !oldNode.equals(newNode);
  5895. }
  5896. minPost() {
  5897. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5898. return NamedNode.MIN;
  5899. }
  5900. maxPost() {
  5901. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5902. return NamedNode.MAX;
  5903. }
  5904. makePost(indexValue, name) {
  5905. const valueNode = nodeFromJSON(indexValue);
  5906. return new NamedNode(name, valueNode);
  5907. }
  5908. /**
  5909. * @returns String representation for inclusion in a query spec
  5910. */
  5911. toString() {
  5912. return '.value';
  5913. }
  5914. }
  5915. const VALUE_INDEX = new ValueIndex();
  5916. /**
  5917. * @license
  5918. * Copyright 2017 Google LLC
  5919. *
  5920. * Licensed under the Apache License, Version 2.0 (the "License");
  5921. * you may not use this file except in compliance with the License.
  5922. * You may obtain a copy of the License at
  5923. *
  5924. * http://www.apache.org/licenses/LICENSE-2.0
  5925. *
  5926. * Unless required by applicable law or agreed to in writing, software
  5927. * distributed under the License is distributed on an "AS IS" BASIS,
  5928. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5929. * See the License for the specific language governing permissions and
  5930. * limitations under the License.
  5931. */
  5932. function changeValue(snapshotNode) {
  5933. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5934. }
  5935. function changeChildAdded(childName, snapshotNode) {
  5936. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5937. }
  5938. function changeChildRemoved(childName, snapshotNode) {
  5939. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5940. }
  5941. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5942. return {
  5943. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5944. snapshotNode,
  5945. childName,
  5946. oldSnap
  5947. };
  5948. }
  5949. function changeChildMoved(childName, snapshotNode) {
  5950. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5951. }
  5952. /**
  5953. * @license
  5954. * Copyright 2017 Google LLC
  5955. *
  5956. * Licensed under the Apache License, Version 2.0 (the "License");
  5957. * you may not use this file except in compliance with the License.
  5958. * You may obtain a copy of the License at
  5959. *
  5960. * http://www.apache.org/licenses/LICENSE-2.0
  5961. *
  5962. * Unless required by applicable law or agreed to in writing, software
  5963. * distributed under the License is distributed on an "AS IS" BASIS,
  5964. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5965. * See the License for the specific language governing permissions and
  5966. * limitations under the License.
  5967. */
  5968. /**
  5969. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5970. */
  5971. class IndexedFilter {
  5972. constructor(index_) {
  5973. this.index_ = index_;
  5974. }
  5975. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5976. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5977. const oldChild = snap.getImmediateChild(key);
  5978. // Check if anything actually changed.
  5979. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5980. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5981. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5982. // to avoid treating these cases as "nothing changed."
  5983. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5984. // Nothing changed.
  5985. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5986. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5987. return snap;
  5988. }
  5989. }
  5990. if (optChangeAccumulator != null) {
  5991. if (newChild.isEmpty()) {
  5992. if (snap.hasChild(key)) {
  5993. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  5994. }
  5995. else {
  5996. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  5997. }
  5998. }
  5999. else if (oldChild.isEmpty()) {
  6000. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6001. }
  6002. else {
  6003. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6004. }
  6005. }
  6006. if (snap.isLeafNode() && newChild.isEmpty()) {
  6007. return snap;
  6008. }
  6009. else {
  6010. // Make sure the node is indexed
  6011. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6012. }
  6013. }
  6014. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6015. if (optChangeAccumulator != null) {
  6016. if (!oldSnap.isLeafNode()) {
  6017. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6018. if (!newSnap.hasChild(key)) {
  6019. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6020. }
  6021. });
  6022. }
  6023. if (!newSnap.isLeafNode()) {
  6024. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6025. if (oldSnap.hasChild(key)) {
  6026. const oldChild = oldSnap.getImmediateChild(key);
  6027. if (!oldChild.equals(childNode)) {
  6028. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6029. }
  6030. }
  6031. else {
  6032. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6033. }
  6034. });
  6035. }
  6036. }
  6037. return newSnap.withIndex(this.index_);
  6038. }
  6039. updatePriority(oldSnap, newPriority) {
  6040. if (oldSnap.isEmpty()) {
  6041. return ChildrenNode.EMPTY_NODE;
  6042. }
  6043. else {
  6044. return oldSnap.updatePriority(newPriority);
  6045. }
  6046. }
  6047. filtersNodes() {
  6048. return false;
  6049. }
  6050. getIndexedFilter() {
  6051. return this;
  6052. }
  6053. getIndex() {
  6054. return this.index_;
  6055. }
  6056. }
  6057. /**
  6058. * @license
  6059. * Copyright 2017 Google LLC
  6060. *
  6061. * Licensed under the Apache License, Version 2.0 (the "License");
  6062. * you may not use this file except in compliance with the License.
  6063. * You may obtain a copy of the License at
  6064. *
  6065. * http://www.apache.org/licenses/LICENSE-2.0
  6066. *
  6067. * Unless required by applicable law or agreed to in writing, software
  6068. * distributed under the License is distributed on an "AS IS" BASIS,
  6069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6070. * See the License for the specific language governing permissions and
  6071. * limitations under the License.
  6072. */
  6073. /**
  6074. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6075. */
  6076. class RangedFilter {
  6077. constructor(params) {
  6078. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6079. this.index_ = params.getIndex();
  6080. this.startPost_ = RangedFilter.getStartPost_(params);
  6081. this.endPost_ = RangedFilter.getEndPost_(params);
  6082. this.startIsInclusive_ = !params.startAfterSet_;
  6083. this.endIsInclusive_ = !params.endBeforeSet_;
  6084. }
  6085. getStartPost() {
  6086. return this.startPost_;
  6087. }
  6088. getEndPost() {
  6089. return this.endPost_;
  6090. }
  6091. matches(node) {
  6092. const isWithinStart = this.startIsInclusive_
  6093. ? this.index_.compare(this.getStartPost(), node) <= 0
  6094. : this.index_.compare(this.getStartPost(), node) < 0;
  6095. const isWithinEnd = this.endIsInclusive_
  6096. ? this.index_.compare(node, this.getEndPost()) <= 0
  6097. : this.index_.compare(node, this.getEndPost()) < 0;
  6098. return isWithinStart && isWithinEnd;
  6099. }
  6100. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6101. if (!this.matches(new NamedNode(key, newChild))) {
  6102. newChild = ChildrenNode.EMPTY_NODE;
  6103. }
  6104. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6105. }
  6106. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6107. if (newSnap.isLeafNode()) {
  6108. // Make sure we have a children node with the correct index, not a leaf node;
  6109. newSnap = ChildrenNode.EMPTY_NODE;
  6110. }
  6111. let filtered = newSnap.withIndex(this.index_);
  6112. // Don't support priorities on queries
  6113. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6114. const self = this;
  6115. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6116. if (!self.matches(new NamedNode(key, childNode))) {
  6117. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6118. }
  6119. });
  6120. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6121. }
  6122. updatePriority(oldSnap, newPriority) {
  6123. // Don't support priorities on queries
  6124. return oldSnap;
  6125. }
  6126. filtersNodes() {
  6127. return true;
  6128. }
  6129. getIndexedFilter() {
  6130. return this.indexedFilter_;
  6131. }
  6132. getIndex() {
  6133. return this.index_;
  6134. }
  6135. static getStartPost_(params) {
  6136. if (params.hasStart()) {
  6137. const startName = params.getIndexStartName();
  6138. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6139. }
  6140. else {
  6141. return params.getIndex().minPost();
  6142. }
  6143. }
  6144. static getEndPost_(params) {
  6145. if (params.hasEnd()) {
  6146. const endName = params.getIndexEndName();
  6147. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6148. }
  6149. else {
  6150. return params.getIndex().maxPost();
  6151. }
  6152. }
  6153. }
  6154. /**
  6155. * @license
  6156. * Copyright 2017 Google LLC
  6157. *
  6158. * Licensed under the Apache License, Version 2.0 (the "License");
  6159. * you may not use this file except in compliance with the License.
  6160. * You may obtain a copy of the License at
  6161. *
  6162. * http://www.apache.org/licenses/LICENSE-2.0
  6163. *
  6164. * Unless required by applicable law or agreed to in writing, software
  6165. * distributed under the License is distributed on an "AS IS" BASIS,
  6166. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6167. * See the License for the specific language governing permissions and
  6168. * limitations under the License.
  6169. */
  6170. /**
  6171. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6172. */
  6173. class LimitedFilter {
  6174. constructor(params) {
  6175. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6176. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6177. this.withinStartPost = (node) => {
  6178. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6179. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6180. };
  6181. this.withinEndPost = (node) => {
  6182. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6183. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6184. };
  6185. this.rangedFilter_ = new RangedFilter(params);
  6186. this.index_ = params.getIndex();
  6187. this.limit_ = params.getLimit();
  6188. this.reverse_ = !params.isViewFromLeft();
  6189. this.startIsInclusive_ = !params.startAfterSet_;
  6190. this.endIsInclusive_ = !params.endBeforeSet_;
  6191. }
  6192. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6193. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6194. newChild = ChildrenNode.EMPTY_NODE;
  6195. }
  6196. if (snap.getImmediateChild(key).equals(newChild)) {
  6197. // No change
  6198. return snap;
  6199. }
  6200. else if (snap.numChildren() < this.limit_) {
  6201. return this.rangedFilter_
  6202. .getIndexedFilter()
  6203. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6204. }
  6205. else {
  6206. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6207. }
  6208. }
  6209. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6210. let filtered;
  6211. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6212. // Make sure we have a children node with the correct index, not a leaf node;
  6213. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6214. }
  6215. else {
  6216. if (this.limit_ * 2 < newSnap.numChildren() &&
  6217. newSnap.isIndexed(this.index_)) {
  6218. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6219. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6220. // anchor to the startPost, endPost, or last element as appropriate
  6221. let iterator;
  6222. if (this.reverse_) {
  6223. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6224. }
  6225. else {
  6226. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6227. }
  6228. let count = 0;
  6229. while (iterator.hasNext() && count < this.limit_) {
  6230. const next = iterator.getNext();
  6231. if (!this.withinDirectionalStart(next)) {
  6232. // if we have not reached the start, skip to the next element
  6233. continue;
  6234. }
  6235. else if (!this.withinDirectionalEnd(next)) {
  6236. // if we have reached the end, stop adding elements
  6237. break;
  6238. }
  6239. else {
  6240. filtered = filtered.updateImmediateChild(next.name, next.node);
  6241. count++;
  6242. }
  6243. }
  6244. }
  6245. else {
  6246. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6247. filtered = newSnap.withIndex(this.index_);
  6248. // Don't support priorities on queries
  6249. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6250. let iterator;
  6251. if (this.reverse_) {
  6252. iterator = filtered.getReverseIterator(this.index_);
  6253. }
  6254. else {
  6255. iterator = filtered.getIterator(this.index_);
  6256. }
  6257. let count = 0;
  6258. while (iterator.hasNext()) {
  6259. const next = iterator.getNext();
  6260. const inRange = count < this.limit_ &&
  6261. this.withinDirectionalStart(next) &&
  6262. this.withinDirectionalEnd(next);
  6263. if (inRange) {
  6264. count++;
  6265. }
  6266. else {
  6267. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6268. }
  6269. }
  6270. }
  6271. }
  6272. return this.rangedFilter_
  6273. .getIndexedFilter()
  6274. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6275. }
  6276. updatePriority(oldSnap, newPriority) {
  6277. // Don't support priorities on queries
  6278. return oldSnap;
  6279. }
  6280. filtersNodes() {
  6281. return true;
  6282. }
  6283. getIndexedFilter() {
  6284. return this.rangedFilter_.getIndexedFilter();
  6285. }
  6286. getIndex() {
  6287. return this.index_;
  6288. }
  6289. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6290. // TODO: rename all cache stuff etc to general snap terminology
  6291. let cmp;
  6292. if (this.reverse_) {
  6293. const indexCmp = this.index_.getCompare();
  6294. cmp = (a, b) => indexCmp(b, a);
  6295. }
  6296. else {
  6297. cmp = this.index_.getCompare();
  6298. }
  6299. const oldEventCache = snap;
  6300. assert(oldEventCache.numChildren() === this.limit_, '');
  6301. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6302. const windowBoundary = this.reverse_
  6303. ? oldEventCache.getFirstChild(this.index_)
  6304. : oldEventCache.getLastChild(this.index_);
  6305. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6306. if (oldEventCache.hasChild(childKey)) {
  6307. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6308. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6309. while (nextChild != null &&
  6310. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6311. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6312. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6313. // the limited filter...
  6314. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6315. }
  6316. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6317. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6318. if (remainsInWindow) {
  6319. if (changeAccumulator != null) {
  6320. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6321. }
  6322. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6323. }
  6324. else {
  6325. if (changeAccumulator != null) {
  6326. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6327. }
  6328. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6329. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6330. if (nextChildInRange) {
  6331. if (changeAccumulator != null) {
  6332. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6333. }
  6334. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6335. }
  6336. else {
  6337. return newEventCache;
  6338. }
  6339. }
  6340. }
  6341. else if (childSnap.isEmpty()) {
  6342. // we're deleting a node, but it was not in the window, so ignore it
  6343. return snap;
  6344. }
  6345. else if (inRange) {
  6346. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6347. if (changeAccumulator != null) {
  6348. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6349. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6350. }
  6351. return oldEventCache
  6352. .updateImmediateChild(childKey, childSnap)
  6353. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6354. }
  6355. else {
  6356. return snap;
  6357. }
  6358. }
  6359. else {
  6360. return snap;
  6361. }
  6362. }
  6363. }
  6364. /**
  6365. * @license
  6366. * Copyright 2017 Google LLC
  6367. *
  6368. * Licensed under the Apache License, Version 2.0 (the "License");
  6369. * you may not use this file except in compliance with the License.
  6370. * You may obtain a copy of the License at
  6371. *
  6372. * http://www.apache.org/licenses/LICENSE-2.0
  6373. *
  6374. * Unless required by applicable law or agreed to in writing, software
  6375. * distributed under the License is distributed on an "AS IS" BASIS,
  6376. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6377. * See the License for the specific language governing permissions and
  6378. * limitations under the License.
  6379. */
  6380. /**
  6381. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6382. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6383. * user-facing API level, so it is not done here.
  6384. *
  6385. * @internal
  6386. */
  6387. class QueryParams {
  6388. constructor() {
  6389. this.limitSet_ = false;
  6390. this.startSet_ = false;
  6391. this.startNameSet_ = false;
  6392. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6393. this.endSet_ = false;
  6394. this.endNameSet_ = false;
  6395. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6396. this.limit_ = 0;
  6397. this.viewFrom_ = '';
  6398. this.indexStartValue_ = null;
  6399. this.indexStartName_ = '';
  6400. this.indexEndValue_ = null;
  6401. this.indexEndName_ = '';
  6402. this.index_ = PRIORITY_INDEX;
  6403. }
  6404. hasStart() {
  6405. return this.startSet_;
  6406. }
  6407. /**
  6408. * @returns True if it would return from left.
  6409. */
  6410. isViewFromLeft() {
  6411. if (this.viewFrom_ === '') {
  6412. // limit(), rather than limitToFirst or limitToLast was called.
  6413. // This means that only one of startSet_ and endSet_ is true. Use them
  6414. // to calculate which side of the view to anchor to. If neither is set,
  6415. // anchor to the end.
  6416. return this.startSet_;
  6417. }
  6418. else {
  6419. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6420. }
  6421. }
  6422. /**
  6423. * Only valid to call if hasStart() returns true
  6424. */
  6425. getIndexStartValue() {
  6426. assert(this.startSet_, 'Only valid if start has been set');
  6427. return this.indexStartValue_;
  6428. }
  6429. /**
  6430. * Only valid to call if hasStart() returns true.
  6431. * Returns the starting key name for the range defined by these query parameters
  6432. */
  6433. getIndexStartName() {
  6434. assert(this.startSet_, 'Only valid if start has been set');
  6435. if (this.startNameSet_) {
  6436. return this.indexStartName_;
  6437. }
  6438. else {
  6439. return MIN_NAME;
  6440. }
  6441. }
  6442. hasEnd() {
  6443. return this.endSet_;
  6444. }
  6445. /**
  6446. * Only valid to call if hasEnd() returns true.
  6447. */
  6448. getIndexEndValue() {
  6449. assert(this.endSet_, 'Only valid if end has been set');
  6450. return this.indexEndValue_;
  6451. }
  6452. /**
  6453. * Only valid to call if hasEnd() returns true.
  6454. * Returns the end key name for the range defined by these query parameters
  6455. */
  6456. getIndexEndName() {
  6457. assert(this.endSet_, 'Only valid if end has been set');
  6458. if (this.endNameSet_) {
  6459. return this.indexEndName_;
  6460. }
  6461. else {
  6462. return MAX_NAME;
  6463. }
  6464. }
  6465. hasLimit() {
  6466. return this.limitSet_;
  6467. }
  6468. /**
  6469. * @returns True if a limit has been set and it has been explicitly anchored
  6470. */
  6471. hasAnchoredLimit() {
  6472. return this.limitSet_ && this.viewFrom_ !== '';
  6473. }
  6474. /**
  6475. * Only valid to call if hasLimit() returns true
  6476. */
  6477. getLimit() {
  6478. assert(this.limitSet_, 'Only valid if limit has been set');
  6479. return this.limit_;
  6480. }
  6481. getIndex() {
  6482. return this.index_;
  6483. }
  6484. loadsAllData() {
  6485. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6486. }
  6487. isDefault() {
  6488. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6489. }
  6490. copy() {
  6491. const copy = new QueryParams();
  6492. copy.limitSet_ = this.limitSet_;
  6493. copy.limit_ = this.limit_;
  6494. copy.startSet_ = this.startSet_;
  6495. copy.startAfterSet_ = this.startAfterSet_;
  6496. copy.indexStartValue_ = this.indexStartValue_;
  6497. copy.startNameSet_ = this.startNameSet_;
  6498. copy.indexStartName_ = this.indexStartName_;
  6499. copy.endSet_ = this.endSet_;
  6500. copy.endBeforeSet_ = this.endBeforeSet_;
  6501. copy.indexEndValue_ = this.indexEndValue_;
  6502. copy.endNameSet_ = this.endNameSet_;
  6503. copy.indexEndName_ = this.indexEndName_;
  6504. copy.index_ = this.index_;
  6505. copy.viewFrom_ = this.viewFrom_;
  6506. return copy;
  6507. }
  6508. }
  6509. function queryParamsGetNodeFilter(queryParams) {
  6510. if (queryParams.loadsAllData()) {
  6511. return new IndexedFilter(queryParams.getIndex());
  6512. }
  6513. else if (queryParams.hasLimit()) {
  6514. return new LimitedFilter(queryParams);
  6515. }
  6516. else {
  6517. return new RangedFilter(queryParams);
  6518. }
  6519. }
  6520. function queryParamsLimitToFirst(queryParams, newLimit) {
  6521. const newParams = queryParams.copy();
  6522. newParams.limitSet_ = true;
  6523. newParams.limit_ = newLimit;
  6524. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6525. return newParams;
  6526. }
  6527. function queryParamsLimitToLast(queryParams, newLimit) {
  6528. const newParams = queryParams.copy();
  6529. newParams.limitSet_ = true;
  6530. newParams.limit_ = newLimit;
  6531. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6532. return newParams;
  6533. }
  6534. function queryParamsStartAt(queryParams, indexValue, key) {
  6535. const newParams = queryParams.copy();
  6536. newParams.startSet_ = true;
  6537. if (indexValue === undefined) {
  6538. indexValue = null;
  6539. }
  6540. newParams.indexStartValue_ = indexValue;
  6541. if (key != null) {
  6542. newParams.startNameSet_ = true;
  6543. newParams.indexStartName_ = key;
  6544. }
  6545. else {
  6546. newParams.startNameSet_ = false;
  6547. newParams.indexStartName_ = '';
  6548. }
  6549. return newParams;
  6550. }
  6551. function queryParamsStartAfter(queryParams, indexValue, key) {
  6552. let params;
  6553. if (queryParams.index_ === KEY_INDEX || !!key) {
  6554. params = queryParamsStartAt(queryParams, indexValue, key);
  6555. }
  6556. else {
  6557. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6558. }
  6559. params.startAfterSet_ = true;
  6560. return params;
  6561. }
  6562. function queryParamsEndAt(queryParams, indexValue, key) {
  6563. const newParams = queryParams.copy();
  6564. newParams.endSet_ = true;
  6565. if (indexValue === undefined) {
  6566. indexValue = null;
  6567. }
  6568. newParams.indexEndValue_ = indexValue;
  6569. if (key !== undefined) {
  6570. newParams.endNameSet_ = true;
  6571. newParams.indexEndName_ = key;
  6572. }
  6573. else {
  6574. newParams.endNameSet_ = false;
  6575. newParams.indexEndName_ = '';
  6576. }
  6577. return newParams;
  6578. }
  6579. function queryParamsEndBefore(queryParams, indexValue, key) {
  6580. let params;
  6581. if (queryParams.index_ === KEY_INDEX || !!key) {
  6582. params = queryParamsEndAt(queryParams, indexValue, key);
  6583. }
  6584. else {
  6585. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6586. }
  6587. params.endBeforeSet_ = true;
  6588. return params;
  6589. }
  6590. function queryParamsOrderBy(queryParams, index) {
  6591. const newParams = queryParams.copy();
  6592. newParams.index_ = index;
  6593. return newParams;
  6594. }
  6595. /**
  6596. * Returns a set of REST query string parameters representing this query.
  6597. *
  6598. * @returns query string parameters
  6599. */
  6600. function queryParamsToRestQueryStringParameters(queryParams) {
  6601. const qs = {};
  6602. if (queryParams.isDefault()) {
  6603. return qs;
  6604. }
  6605. let orderBy;
  6606. if (queryParams.index_ === PRIORITY_INDEX) {
  6607. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6608. }
  6609. else if (queryParams.index_ === VALUE_INDEX) {
  6610. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6611. }
  6612. else if (queryParams.index_ === KEY_INDEX) {
  6613. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6614. }
  6615. else {
  6616. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6617. orderBy = queryParams.index_.toString();
  6618. }
  6619. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6620. if (queryParams.startSet_) {
  6621. const startParam = queryParams.startAfterSet_
  6622. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6623. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6624. qs[startParam] = stringify(queryParams.indexStartValue_);
  6625. if (queryParams.startNameSet_) {
  6626. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6627. }
  6628. }
  6629. if (queryParams.endSet_) {
  6630. const endParam = queryParams.endBeforeSet_
  6631. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6632. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6633. qs[endParam] = stringify(queryParams.indexEndValue_);
  6634. if (queryParams.endNameSet_) {
  6635. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6636. }
  6637. }
  6638. if (queryParams.limitSet_) {
  6639. if (queryParams.isViewFromLeft()) {
  6640. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6641. }
  6642. else {
  6643. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6644. }
  6645. }
  6646. return qs;
  6647. }
  6648. function queryParamsGetQueryObject(queryParams) {
  6649. const obj = {};
  6650. if (queryParams.startSet_) {
  6651. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6652. queryParams.indexStartValue_;
  6653. if (queryParams.startNameSet_) {
  6654. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6655. queryParams.indexStartName_;
  6656. }
  6657. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6658. !queryParams.startAfterSet_;
  6659. }
  6660. if (queryParams.endSet_) {
  6661. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6662. if (queryParams.endNameSet_) {
  6663. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6664. }
  6665. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6666. !queryParams.endBeforeSet_;
  6667. }
  6668. if (queryParams.limitSet_) {
  6669. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6670. let viewFrom = queryParams.viewFrom_;
  6671. if (viewFrom === '') {
  6672. if (queryParams.isViewFromLeft()) {
  6673. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6674. }
  6675. else {
  6676. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6677. }
  6678. }
  6679. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6680. }
  6681. // For now, priority index is the default, so we only specify if it's some other index
  6682. if (queryParams.index_ !== PRIORITY_INDEX) {
  6683. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6684. }
  6685. return obj;
  6686. }
  6687. /**
  6688. * @license
  6689. * Copyright 2017 Google LLC
  6690. *
  6691. * Licensed under the Apache License, Version 2.0 (the "License");
  6692. * you may not use this file except in compliance with the License.
  6693. * You may obtain a copy of the License at
  6694. *
  6695. * http://www.apache.org/licenses/LICENSE-2.0
  6696. *
  6697. * Unless required by applicable law or agreed to in writing, software
  6698. * distributed under the License is distributed on an "AS IS" BASIS,
  6699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6700. * See the License for the specific language governing permissions and
  6701. * limitations under the License.
  6702. */
  6703. /**
  6704. * An implementation of ServerActions that communicates with the server via REST requests.
  6705. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6706. * persistent connection (using WebSockets or long-polling)
  6707. */
  6708. class ReadonlyRestClient extends ServerActions {
  6709. /**
  6710. * @param repoInfo_ - Data about the namespace we are connecting to
  6711. * @param onDataUpdate_ - A callback for new data from the server
  6712. */
  6713. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6714. super();
  6715. this.repoInfo_ = repoInfo_;
  6716. this.onDataUpdate_ = onDataUpdate_;
  6717. this.authTokenProvider_ = authTokenProvider_;
  6718. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6719. /** @private {function(...[*])} */
  6720. this.log_ = logWrapper('p:rest:');
  6721. /**
  6722. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6723. * that's been removed. :-/
  6724. */
  6725. this.listens_ = {};
  6726. }
  6727. reportStats(stats) {
  6728. throw new Error('Method not implemented.');
  6729. }
  6730. static getListenId_(query, tag) {
  6731. if (tag !== undefined) {
  6732. return 'tag$' + tag;
  6733. }
  6734. else {
  6735. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6736. return query._path.toString();
  6737. }
  6738. }
  6739. /** @inheritDoc */
  6740. listen(query, currentHashFn, tag, onComplete) {
  6741. const pathString = query._path.toString();
  6742. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6743. // Mark this listener so we can tell if it's removed.
  6744. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6745. const thisListen = {};
  6746. this.listens_[listenId] = thisListen;
  6747. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6748. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6749. let data = result;
  6750. if (error === 404) {
  6751. data = null;
  6752. error = null;
  6753. }
  6754. if (error === null) {
  6755. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6756. }
  6757. if (safeGet(this.listens_, listenId) === thisListen) {
  6758. let status;
  6759. if (!error) {
  6760. status = 'ok';
  6761. }
  6762. else if (error === 401) {
  6763. status = 'permission_denied';
  6764. }
  6765. else {
  6766. status = 'rest_error:' + error;
  6767. }
  6768. onComplete(status, null);
  6769. }
  6770. });
  6771. }
  6772. /** @inheritDoc */
  6773. unlisten(query, tag) {
  6774. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6775. delete this.listens_[listenId];
  6776. }
  6777. get(query) {
  6778. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6779. const pathString = query._path.toString();
  6780. const deferred = new Deferred();
  6781. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6782. let data = result;
  6783. if (error === 404) {
  6784. data = null;
  6785. error = null;
  6786. }
  6787. if (error === null) {
  6788. this.onDataUpdate_(pathString, data,
  6789. /*isMerge=*/ false,
  6790. /*tag=*/ null);
  6791. deferred.resolve(data);
  6792. }
  6793. else {
  6794. deferred.reject(new Error(data));
  6795. }
  6796. });
  6797. return deferred.promise;
  6798. }
  6799. /** @inheritDoc */
  6800. refreshAuthToken(token) {
  6801. // no-op since we just always call getToken.
  6802. }
  6803. /**
  6804. * Performs a REST request to the given path, with the provided query string parameters,
  6805. * and any auth credentials we have.
  6806. */
  6807. restRequest_(pathString, queryStringParameters = {}, callback) {
  6808. queryStringParameters['format'] = 'export';
  6809. return Promise.all([
  6810. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6811. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6812. ]).then(([authToken, appCheckToken]) => {
  6813. if (authToken && authToken.accessToken) {
  6814. queryStringParameters['auth'] = authToken.accessToken;
  6815. }
  6816. if (appCheckToken && appCheckToken.token) {
  6817. queryStringParameters['ac'] = appCheckToken.token;
  6818. }
  6819. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6820. this.repoInfo_.host +
  6821. pathString +
  6822. '?' +
  6823. 'ns=' +
  6824. this.repoInfo_.namespace +
  6825. querystring(queryStringParameters);
  6826. this.log_('Sending REST request for ' + url);
  6827. const xhr = new XMLHttpRequest();
  6828. xhr.onreadystatechange = () => {
  6829. if (callback && xhr.readyState === 4) {
  6830. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6831. let res = null;
  6832. if (xhr.status >= 200 && xhr.status < 300) {
  6833. try {
  6834. res = jsonEval(xhr.responseText);
  6835. }
  6836. catch (e) {
  6837. warn('Failed to parse JSON response for ' +
  6838. url +
  6839. ': ' +
  6840. xhr.responseText);
  6841. }
  6842. callback(null, res);
  6843. }
  6844. else {
  6845. // 401 and 404 are expected.
  6846. if (xhr.status !== 401 && xhr.status !== 404) {
  6847. warn('Got unsuccessful REST response for ' +
  6848. url +
  6849. ' Status: ' +
  6850. xhr.status);
  6851. }
  6852. callback(xhr.status);
  6853. }
  6854. callback = null;
  6855. }
  6856. };
  6857. xhr.open('GET', url, /*asynchronous=*/ true);
  6858. xhr.send();
  6859. });
  6860. }
  6861. }
  6862. /**
  6863. * @license
  6864. * Copyright 2017 Google LLC
  6865. *
  6866. * Licensed under the Apache License, Version 2.0 (the "License");
  6867. * you may not use this file except in compliance with the License.
  6868. * You may obtain a copy of the License at
  6869. *
  6870. * http://www.apache.org/licenses/LICENSE-2.0
  6871. *
  6872. * Unless required by applicable law or agreed to in writing, software
  6873. * distributed under the License is distributed on an "AS IS" BASIS,
  6874. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6875. * See the License for the specific language governing permissions and
  6876. * limitations under the License.
  6877. */
  6878. /**
  6879. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6880. */
  6881. class SnapshotHolder {
  6882. constructor() {
  6883. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6884. }
  6885. getNode(path) {
  6886. return this.rootNode_.getChild(path);
  6887. }
  6888. updateSnapshot(path, newSnapshotNode) {
  6889. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6890. }
  6891. }
  6892. /**
  6893. * @license
  6894. * Copyright 2017 Google LLC
  6895. *
  6896. * Licensed under the Apache License, Version 2.0 (the "License");
  6897. * you may not use this file except in compliance with the License.
  6898. * You may obtain a copy of the License at
  6899. *
  6900. * http://www.apache.org/licenses/LICENSE-2.0
  6901. *
  6902. * Unless required by applicable law or agreed to in writing, software
  6903. * distributed under the License is distributed on an "AS IS" BASIS,
  6904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6905. * See the License for the specific language governing permissions and
  6906. * limitations under the License.
  6907. */
  6908. function newSparseSnapshotTree() {
  6909. return {
  6910. value: null,
  6911. children: new Map()
  6912. };
  6913. }
  6914. /**
  6915. * Stores the given node at the specified path. If there is already a node
  6916. * at a shallower path, it merges the new data into that snapshot node.
  6917. *
  6918. * @param path - Path to look up snapshot for.
  6919. * @param data - The new data, or null.
  6920. */
  6921. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6922. if (pathIsEmpty(path)) {
  6923. sparseSnapshotTree.value = data;
  6924. sparseSnapshotTree.children.clear();
  6925. }
  6926. else if (sparseSnapshotTree.value !== null) {
  6927. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6928. }
  6929. else {
  6930. const childKey = pathGetFront(path);
  6931. if (!sparseSnapshotTree.children.has(childKey)) {
  6932. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6933. }
  6934. const child = sparseSnapshotTree.children.get(childKey);
  6935. path = pathPopFront(path);
  6936. sparseSnapshotTreeRemember(child, path, data);
  6937. }
  6938. }
  6939. /**
  6940. * Purge the data at path from the cache.
  6941. *
  6942. * @param path - Path to look up snapshot for.
  6943. * @returns True if this node should now be removed.
  6944. */
  6945. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6946. if (pathIsEmpty(path)) {
  6947. sparseSnapshotTree.value = null;
  6948. sparseSnapshotTree.children.clear();
  6949. return true;
  6950. }
  6951. else {
  6952. if (sparseSnapshotTree.value !== null) {
  6953. if (sparseSnapshotTree.value.isLeafNode()) {
  6954. // We're trying to forget a node that doesn't exist
  6955. return false;
  6956. }
  6957. else {
  6958. const value = sparseSnapshotTree.value;
  6959. sparseSnapshotTree.value = null;
  6960. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6961. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6962. });
  6963. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6964. }
  6965. }
  6966. else if (sparseSnapshotTree.children.size > 0) {
  6967. const childKey = pathGetFront(path);
  6968. path = pathPopFront(path);
  6969. if (sparseSnapshotTree.children.has(childKey)) {
  6970. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6971. if (safeToRemove) {
  6972. sparseSnapshotTree.children.delete(childKey);
  6973. }
  6974. }
  6975. return sparseSnapshotTree.children.size === 0;
  6976. }
  6977. else {
  6978. return true;
  6979. }
  6980. }
  6981. }
  6982. /**
  6983. * Recursively iterates through all of the stored tree and calls the
  6984. * callback on each one.
  6985. *
  6986. * @param prefixPath - Path to look up node for.
  6987. * @param func - The function to invoke for each tree.
  6988. */
  6989. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  6990. if (sparseSnapshotTree.value !== null) {
  6991. func(prefixPath, sparseSnapshotTree.value);
  6992. }
  6993. else {
  6994. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  6995. const path = new Path(prefixPath.toString() + '/' + key);
  6996. sparseSnapshotTreeForEachTree(tree, path, func);
  6997. });
  6998. }
  6999. }
  7000. /**
  7001. * Iterates through each immediate child and triggers the callback.
  7002. * Only seems to be used in tests.
  7003. *
  7004. * @param func - The function to invoke for each child.
  7005. */
  7006. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7007. sparseSnapshotTree.children.forEach((tree, key) => {
  7008. func(key, tree);
  7009. });
  7010. }
  7011. /**
  7012. * @license
  7013. * Copyright 2017 Google LLC
  7014. *
  7015. * Licensed under the Apache License, Version 2.0 (the "License");
  7016. * you may not use this file except in compliance with the License.
  7017. * You may obtain a copy of the License at
  7018. *
  7019. * http://www.apache.org/licenses/LICENSE-2.0
  7020. *
  7021. * Unless required by applicable law or agreed to in writing, software
  7022. * distributed under the License is distributed on an "AS IS" BASIS,
  7023. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7024. * See the License for the specific language governing permissions and
  7025. * limitations under the License.
  7026. */
  7027. /**
  7028. * Returns the delta from the previous call to get stats.
  7029. *
  7030. * @param collection_ - The collection to "listen" to.
  7031. */
  7032. class StatsListener {
  7033. constructor(collection_) {
  7034. this.collection_ = collection_;
  7035. this.last_ = null;
  7036. }
  7037. get() {
  7038. const newStats = this.collection_.get();
  7039. const delta = Object.assign({}, newStats);
  7040. if (this.last_) {
  7041. each(this.last_, (stat, value) => {
  7042. delta[stat] = delta[stat] - value;
  7043. });
  7044. }
  7045. this.last_ = newStats;
  7046. return delta;
  7047. }
  7048. }
  7049. /**
  7050. * @license
  7051. * Copyright 2017 Google LLC
  7052. *
  7053. * Licensed under the Apache License, Version 2.0 (the "License");
  7054. * you may not use this file except in compliance with the License.
  7055. * You may obtain a copy of the License at
  7056. *
  7057. * http://www.apache.org/licenses/LICENSE-2.0
  7058. *
  7059. * Unless required by applicable law or agreed to in writing, software
  7060. * distributed under the License is distributed on an "AS IS" BASIS,
  7061. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7062. * See the License for the specific language governing permissions and
  7063. * limitations under the License.
  7064. */
  7065. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7066. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7067. // seconds to try to ensure the Firebase connection is established / settled.
  7068. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7069. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7070. // We'll continue to report stats on average every 5 minutes.
  7071. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7072. class StatsReporter {
  7073. constructor(collection, server_) {
  7074. this.server_ = server_;
  7075. this.statsToReport_ = {};
  7076. this.statsListener_ = new StatsListener(collection);
  7077. const timeout = FIRST_STATS_MIN_TIME +
  7078. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7079. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7080. }
  7081. reportStats_() {
  7082. const stats = this.statsListener_.get();
  7083. const reportedStats = {};
  7084. let haveStatsToReport = false;
  7085. each(stats, (stat, value) => {
  7086. if (value > 0 && contains(this.statsToReport_, stat)) {
  7087. reportedStats[stat] = value;
  7088. haveStatsToReport = true;
  7089. }
  7090. });
  7091. if (haveStatsToReport) {
  7092. this.server_.reportStats(reportedStats);
  7093. }
  7094. // queue our next run.
  7095. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7096. }
  7097. }
  7098. /**
  7099. * @license
  7100. * Copyright 2017 Google LLC
  7101. *
  7102. * Licensed under the Apache License, Version 2.0 (the "License");
  7103. * you may not use this file except in compliance with the License.
  7104. * You may obtain a copy of the License at
  7105. *
  7106. * http://www.apache.org/licenses/LICENSE-2.0
  7107. *
  7108. * Unless required by applicable law or agreed to in writing, software
  7109. * distributed under the License is distributed on an "AS IS" BASIS,
  7110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7111. * See the License for the specific language governing permissions and
  7112. * limitations under the License.
  7113. */
  7114. /**
  7115. *
  7116. * @enum
  7117. */
  7118. var OperationType;
  7119. (function (OperationType) {
  7120. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7121. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7122. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7123. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7124. })(OperationType || (OperationType = {}));
  7125. function newOperationSourceUser() {
  7126. return {
  7127. fromUser: true,
  7128. fromServer: false,
  7129. queryId: null,
  7130. tagged: false
  7131. };
  7132. }
  7133. function newOperationSourceServer() {
  7134. return {
  7135. fromUser: false,
  7136. fromServer: true,
  7137. queryId: null,
  7138. tagged: false
  7139. };
  7140. }
  7141. function newOperationSourceServerTaggedQuery(queryId) {
  7142. return {
  7143. fromUser: false,
  7144. fromServer: true,
  7145. queryId,
  7146. tagged: true
  7147. };
  7148. }
  7149. /**
  7150. * @license
  7151. * Copyright 2017 Google LLC
  7152. *
  7153. * Licensed under the Apache License, Version 2.0 (the "License");
  7154. * you may not use this file except in compliance with the License.
  7155. * You may obtain a copy of the License at
  7156. *
  7157. * http://www.apache.org/licenses/LICENSE-2.0
  7158. *
  7159. * Unless required by applicable law or agreed to in writing, software
  7160. * distributed under the License is distributed on an "AS IS" BASIS,
  7161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7162. * See the License for the specific language governing permissions and
  7163. * limitations under the License.
  7164. */
  7165. class AckUserWrite {
  7166. /**
  7167. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7168. */
  7169. constructor(
  7170. /** @inheritDoc */ path,
  7171. /** @inheritDoc */ affectedTree,
  7172. /** @inheritDoc */ revert) {
  7173. this.path = path;
  7174. this.affectedTree = affectedTree;
  7175. this.revert = revert;
  7176. /** @inheritDoc */
  7177. this.type = OperationType.ACK_USER_WRITE;
  7178. /** @inheritDoc */
  7179. this.source = newOperationSourceUser();
  7180. }
  7181. operationForChild(childName) {
  7182. if (!pathIsEmpty(this.path)) {
  7183. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7184. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7185. }
  7186. else if (this.affectedTree.value != null) {
  7187. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7188. // All child locations are affected as well; just return same operation.
  7189. return this;
  7190. }
  7191. else {
  7192. const childTree = this.affectedTree.subtree(new Path(childName));
  7193. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7194. }
  7195. }
  7196. }
  7197. /**
  7198. * @license
  7199. * Copyright 2017 Google LLC
  7200. *
  7201. * Licensed under the Apache License, Version 2.0 (the "License");
  7202. * you may not use this file except in compliance with the License.
  7203. * You may obtain a copy of the License at
  7204. *
  7205. * http://www.apache.org/licenses/LICENSE-2.0
  7206. *
  7207. * Unless required by applicable law or agreed to in writing, software
  7208. * distributed under the License is distributed on an "AS IS" BASIS,
  7209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7210. * See the License for the specific language governing permissions and
  7211. * limitations under the License.
  7212. */
  7213. class ListenComplete {
  7214. constructor(source, path) {
  7215. this.source = source;
  7216. this.path = path;
  7217. /** @inheritDoc */
  7218. this.type = OperationType.LISTEN_COMPLETE;
  7219. }
  7220. operationForChild(childName) {
  7221. if (pathIsEmpty(this.path)) {
  7222. return new ListenComplete(this.source, newEmptyPath());
  7223. }
  7224. else {
  7225. return new ListenComplete(this.source, pathPopFront(this.path));
  7226. }
  7227. }
  7228. }
  7229. /**
  7230. * @license
  7231. * Copyright 2017 Google LLC
  7232. *
  7233. * Licensed under the Apache License, Version 2.0 (the "License");
  7234. * you may not use this file except in compliance with the License.
  7235. * You may obtain a copy of the License at
  7236. *
  7237. * http://www.apache.org/licenses/LICENSE-2.0
  7238. *
  7239. * Unless required by applicable law or agreed to in writing, software
  7240. * distributed under the License is distributed on an "AS IS" BASIS,
  7241. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7242. * See the License for the specific language governing permissions and
  7243. * limitations under the License.
  7244. */
  7245. class Overwrite {
  7246. constructor(source, path, snap) {
  7247. this.source = source;
  7248. this.path = path;
  7249. this.snap = snap;
  7250. /** @inheritDoc */
  7251. this.type = OperationType.OVERWRITE;
  7252. }
  7253. operationForChild(childName) {
  7254. if (pathIsEmpty(this.path)) {
  7255. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7256. }
  7257. else {
  7258. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7259. }
  7260. }
  7261. }
  7262. /**
  7263. * @license
  7264. * Copyright 2017 Google LLC
  7265. *
  7266. * Licensed under the Apache License, Version 2.0 (the "License");
  7267. * you may not use this file except in compliance with the License.
  7268. * You may obtain a copy of the License at
  7269. *
  7270. * http://www.apache.org/licenses/LICENSE-2.0
  7271. *
  7272. * Unless required by applicable law or agreed to in writing, software
  7273. * distributed under the License is distributed on an "AS IS" BASIS,
  7274. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7275. * See the License for the specific language governing permissions and
  7276. * limitations under the License.
  7277. */
  7278. class Merge {
  7279. constructor(
  7280. /** @inheritDoc */ source,
  7281. /** @inheritDoc */ path,
  7282. /** @inheritDoc */ children) {
  7283. this.source = source;
  7284. this.path = path;
  7285. this.children = children;
  7286. /** @inheritDoc */
  7287. this.type = OperationType.MERGE;
  7288. }
  7289. operationForChild(childName) {
  7290. if (pathIsEmpty(this.path)) {
  7291. const childTree = this.children.subtree(new Path(childName));
  7292. if (childTree.isEmpty()) {
  7293. // This child is unaffected
  7294. return null;
  7295. }
  7296. else if (childTree.value) {
  7297. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7298. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7299. }
  7300. else {
  7301. // This is a merge at a deeper level
  7302. return new Merge(this.source, newEmptyPath(), childTree);
  7303. }
  7304. }
  7305. else {
  7306. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7307. return new Merge(this.source, pathPopFront(this.path), this.children);
  7308. }
  7309. }
  7310. toString() {
  7311. return ('Operation(' +
  7312. this.path +
  7313. ': ' +
  7314. this.source.toString() +
  7315. ' merge: ' +
  7316. this.children.toString() +
  7317. ')');
  7318. }
  7319. }
  7320. /**
  7321. * @license
  7322. * Copyright 2017 Google LLC
  7323. *
  7324. * Licensed under the Apache License, Version 2.0 (the "License");
  7325. * you may not use this file except in compliance with the License.
  7326. * You may obtain a copy of the License at
  7327. *
  7328. * http://www.apache.org/licenses/LICENSE-2.0
  7329. *
  7330. * Unless required by applicable law or agreed to in writing, software
  7331. * distributed under the License is distributed on an "AS IS" BASIS,
  7332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7333. * See the License for the specific language governing permissions and
  7334. * limitations under the License.
  7335. */
  7336. /**
  7337. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7338. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7339. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7340. * whether a node potentially had children removed due to a filter.
  7341. */
  7342. class CacheNode {
  7343. constructor(node_, fullyInitialized_, filtered_) {
  7344. this.node_ = node_;
  7345. this.fullyInitialized_ = fullyInitialized_;
  7346. this.filtered_ = filtered_;
  7347. }
  7348. /**
  7349. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7350. */
  7351. isFullyInitialized() {
  7352. return this.fullyInitialized_;
  7353. }
  7354. /**
  7355. * Returns whether this node is potentially missing children due to a filter applied to the node
  7356. */
  7357. isFiltered() {
  7358. return this.filtered_;
  7359. }
  7360. isCompleteForPath(path) {
  7361. if (pathIsEmpty(path)) {
  7362. return this.isFullyInitialized() && !this.filtered_;
  7363. }
  7364. const childKey = pathGetFront(path);
  7365. return this.isCompleteForChild(childKey);
  7366. }
  7367. isCompleteForChild(key) {
  7368. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7369. }
  7370. getNode() {
  7371. return this.node_;
  7372. }
  7373. }
  7374. /**
  7375. * @license
  7376. * Copyright 2017 Google LLC
  7377. *
  7378. * Licensed under the Apache License, Version 2.0 (the "License");
  7379. * you may not use this file except in compliance with the License.
  7380. * You may obtain a copy of the License at
  7381. *
  7382. * http://www.apache.org/licenses/LICENSE-2.0
  7383. *
  7384. * Unless required by applicable law or agreed to in writing, software
  7385. * distributed under the License is distributed on an "AS IS" BASIS,
  7386. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7387. * See the License for the specific language governing permissions and
  7388. * limitations under the License.
  7389. */
  7390. /**
  7391. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7392. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7393. * for details.
  7394. *
  7395. */
  7396. class EventGenerator {
  7397. constructor(query_) {
  7398. this.query_ = query_;
  7399. this.index_ = this.query_._queryParams.getIndex();
  7400. }
  7401. }
  7402. /**
  7403. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7404. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7405. *
  7406. * Notes:
  7407. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7408. * our index.
  7409. * - prevName will be calculated based on the index ordering.
  7410. */
  7411. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7412. const events = [];
  7413. const moves = [];
  7414. changes.forEach(change => {
  7415. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7416. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7417. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7418. }
  7419. });
  7420. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7421. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7422. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7423. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7424. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7425. return events;
  7426. }
  7427. /**
  7428. * Given changes of a single change type, generate the corresponding events.
  7429. */
  7430. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7431. const filteredChanges = changes.filter(change => change.type === eventType);
  7432. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7433. filteredChanges.forEach(change => {
  7434. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7435. registrations.forEach(registration => {
  7436. if (registration.respondsTo(change.type)) {
  7437. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7438. }
  7439. });
  7440. });
  7441. }
  7442. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7443. if (change.type === 'value' || change.type === 'child_removed') {
  7444. return change;
  7445. }
  7446. else {
  7447. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7448. return change;
  7449. }
  7450. }
  7451. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7452. if (a.childName == null || b.childName == null) {
  7453. throw assertionError('Should only compare child_ events.');
  7454. }
  7455. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7456. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7457. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7458. }
  7459. /**
  7460. * @license
  7461. * Copyright 2017 Google LLC
  7462. *
  7463. * Licensed under the Apache License, Version 2.0 (the "License");
  7464. * you may not use this file except in compliance with the License.
  7465. * You may obtain a copy of the License at
  7466. *
  7467. * http://www.apache.org/licenses/LICENSE-2.0
  7468. *
  7469. * Unless required by applicable law or agreed to in writing, software
  7470. * distributed under the License is distributed on an "AS IS" BASIS,
  7471. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7472. * See the License for the specific language governing permissions and
  7473. * limitations under the License.
  7474. */
  7475. function newViewCache(eventCache, serverCache) {
  7476. return { eventCache, serverCache };
  7477. }
  7478. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7479. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7480. }
  7481. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7482. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7483. }
  7484. function viewCacheGetCompleteEventSnap(viewCache) {
  7485. return viewCache.eventCache.isFullyInitialized()
  7486. ? viewCache.eventCache.getNode()
  7487. : null;
  7488. }
  7489. function viewCacheGetCompleteServerSnap(viewCache) {
  7490. return viewCache.serverCache.isFullyInitialized()
  7491. ? viewCache.serverCache.getNode()
  7492. : null;
  7493. }
  7494. /**
  7495. * @license
  7496. * Copyright 2017 Google LLC
  7497. *
  7498. * Licensed under the Apache License, Version 2.0 (the "License");
  7499. * you may not use this file except in compliance with the License.
  7500. * You may obtain a copy of the License at
  7501. *
  7502. * http://www.apache.org/licenses/LICENSE-2.0
  7503. *
  7504. * Unless required by applicable law or agreed to in writing, software
  7505. * distributed under the License is distributed on an "AS IS" BASIS,
  7506. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7507. * See the License for the specific language governing permissions and
  7508. * limitations under the License.
  7509. */
  7510. let emptyChildrenSingleton;
  7511. /**
  7512. * Singleton empty children collection.
  7513. *
  7514. */
  7515. const EmptyChildren = () => {
  7516. if (!emptyChildrenSingleton) {
  7517. emptyChildrenSingleton = new SortedMap(stringCompare);
  7518. }
  7519. return emptyChildrenSingleton;
  7520. };
  7521. /**
  7522. * A tree with immutable elements.
  7523. */
  7524. class ImmutableTree {
  7525. constructor(value, children = EmptyChildren()) {
  7526. this.value = value;
  7527. this.children = children;
  7528. }
  7529. static fromObject(obj) {
  7530. let tree = new ImmutableTree(null);
  7531. each(obj, (childPath, childSnap) => {
  7532. tree = tree.set(new Path(childPath), childSnap);
  7533. });
  7534. return tree;
  7535. }
  7536. /**
  7537. * True if the value is empty and there are no children
  7538. */
  7539. isEmpty() {
  7540. return this.value === null && this.children.isEmpty();
  7541. }
  7542. /**
  7543. * Given a path and predicate, return the first node and the path to that node
  7544. * where the predicate returns true.
  7545. *
  7546. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7547. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7548. *
  7549. * @param relativePath - The remainder of the path
  7550. * @param predicate - The predicate to satisfy to return a node
  7551. */
  7552. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7553. if (this.value != null && predicate(this.value)) {
  7554. return { path: newEmptyPath(), value: this.value };
  7555. }
  7556. else {
  7557. if (pathIsEmpty(relativePath)) {
  7558. return null;
  7559. }
  7560. else {
  7561. const front = pathGetFront(relativePath);
  7562. const child = this.children.get(front);
  7563. if (child !== null) {
  7564. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7565. if (childExistingPathAndValue != null) {
  7566. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7567. return { path: fullPath, value: childExistingPathAndValue.value };
  7568. }
  7569. else {
  7570. return null;
  7571. }
  7572. }
  7573. else {
  7574. return null;
  7575. }
  7576. }
  7577. }
  7578. }
  7579. /**
  7580. * Find, if it exists, the shortest subpath of the given path that points a defined
  7581. * value in the tree
  7582. */
  7583. findRootMostValueAndPath(relativePath) {
  7584. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7585. }
  7586. /**
  7587. * @returns The subtree at the given path
  7588. */
  7589. subtree(relativePath) {
  7590. if (pathIsEmpty(relativePath)) {
  7591. return this;
  7592. }
  7593. else {
  7594. const front = pathGetFront(relativePath);
  7595. const childTree = this.children.get(front);
  7596. if (childTree !== null) {
  7597. return childTree.subtree(pathPopFront(relativePath));
  7598. }
  7599. else {
  7600. return new ImmutableTree(null);
  7601. }
  7602. }
  7603. }
  7604. /**
  7605. * Sets a value at the specified path.
  7606. *
  7607. * @param relativePath - Path to set value at.
  7608. * @param toSet - Value to set.
  7609. * @returns Resulting tree.
  7610. */
  7611. set(relativePath, toSet) {
  7612. if (pathIsEmpty(relativePath)) {
  7613. return new ImmutableTree(toSet, this.children);
  7614. }
  7615. else {
  7616. const front = pathGetFront(relativePath);
  7617. const child = this.children.get(front) || new ImmutableTree(null);
  7618. const newChild = child.set(pathPopFront(relativePath), toSet);
  7619. const newChildren = this.children.insert(front, newChild);
  7620. return new ImmutableTree(this.value, newChildren);
  7621. }
  7622. }
  7623. /**
  7624. * Removes the value at the specified path.
  7625. *
  7626. * @param relativePath - Path to value to remove.
  7627. * @returns Resulting tree.
  7628. */
  7629. remove(relativePath) {
  7630. if (pathIsEmpty(relativePath)) {
  7631. if (this.children.isEmpty()) {
  7632. return new ImmutableTree(null);
  7633. }
  7634. else {
  7635. return new ImmutableTree(null, this.children);
  7636. }
  7637. }
  7638. else {
  7639. const front = pathGetFront(relativePath);
  7640. const child = this.children.get(front);
  7641. if (child) {
  7642. const newChild = child.remove(pathPopFront(relativePath));
  7643. let newChildren;
  7644. if (newChild.isEmpty()) {
  7645. newChildren = this.children.remove(front);
  7646. }
  7647. else {
  7648. newChildren = this.children.insert(front, newChild);
  7649. }
  7650. if (this.value === null && newChildren.isEmpty()) {
  7651. return new ImmutableTree(null);
  7652. }
  7653. else {
  7654. return new ImmutableTree(this.value, newChildren);
  7655. }
  7656. }
  7657. else {
  7658. return this;
  7659. }
  7660. }
  7661. }
  7662. /**
  7663. * Gets a value from the tree.
  7664. *
  7665. * @param relativePath - Path to get value for.
  7666. * @returns Value at path, or null.
  7667. */
  7668. get(relativePath) {
  7669. if (pathIsEmpty(relativePath)) {
  7670. return this.value;
  7671. }
  7672. else {
  7673. const front = pathGetFront(relativePath);
  7674. const child = this.children.get(front);
  7675. if (child) {
  7676. return child.get(pathPopFront(relativePath));
  7677. }
  7678. else {
  7679. return null;
  7680. }
  7681. }
  7682. }
  7683. /**
  7684. * Replace the subtree at the specified path with the given new tree.
  7685. *
  7686. * @param relativePath - Path to replace subtree for.
  7687. * @param newTree - New tree.
  7688. * @returns Resulting tree.
  7689. */
  7690. setTree(relativePath, newTree) {
  7691. if (pathIsEmpty(relativePath)) {
  7692. return newTree;
  7693. }
  7694. else {
  7695. const front = pathGetFront(relativePath);
  7696. const child = this.children.get(front) || new ImmutableTree(null);
  7697. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7698. let newChildren;
  7699. if (newChild.isEmpty()) {
  7700. newChildren = this.children.remove(front);
  7701. }
  7702. else {
  7703. newChildren = this.children.insert(front, newChild);
  7704. }
  7705. return new ImmutableTree(this.value, newChildren);
  7706. }
  7707. }
  7708. /**
  7709. * Performs a depth first fold on this tree. Transforms a tree into a single
  7710. * value, given a function that operates on the path to a node, an optional
  7711. * current value, and a map of child names to folded subtrees
  7712. */
  7713. fold(fn) {
  7714. return this.fold_(newEmptyPath(), fn);
  7715. }
  7716. /**
  7717. * Recursive helper for public-facing fold() method
  7718. */
  7719. fold_(pathSoFar, fn) {
  7720. const accum = {};
  7721. this.children.inorderTraversal((childKey, childTree) => {
  7722. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7723. });
  7724. return fn(pathSoFar, this.value, accum);
  7725. }
  7726. /**
  7727. * Find the first matching value on the given path. Return the result of applying f to it.
  7728. */
  7729. findOnPath(path, f) {
  7730. return this.findOnPath_(path, newEmptyPath(), f);
  7731. }
  7732. findOnPath_(pathToFollow, pathSoFar, f) {
  7733. const result = this.value ? f(pathSoFar, this.value) : false;
  7734. if (result) {
  7735. return result;
  7736. }
  7737. else {
  7738. if (pathIsEmpty(pathToFollow)) {
  7739. return null;
  7740. }
  7741. else {
  7742. const front = pathGetFront(pathToFollow);
  7743. const nextChild = this.children.get(front);
  7744. if (nextChild) {
  7745. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7746. }
  7747. else {
  7748. return null;
  7749. }
  7750. }
  7751. }
  7752. }
  7753. foreachOnPath(path, f) {
  7754. return this.foreachOnPath_(path, newEmptyPath(), f);
  7755. }
  7756. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7757. if (pathIsEmpty(pathToFollow)) {
  7758. return this;
  7759. }
  7760. else {
  7761. if (this.value) {
  7762. f(currentRelativePath, this.value);
  7763. }
  7764. const front = pathGetFront(pathToFollow);
  7765. const nextChild = this.children.get(front);
  7766. if (nextChild) {
  7767. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7768. }
  7769. else {
  7770. return new ImmutableTree(null);
  7771. }
  7772. }
  7773. }
  7774. /**
  7775. * Calls the given function for each node in the tree that has a value.
  7776. *
  7777. * @param f - A function to be called with the path from the root of the tree to
  7778. * a node, and the value at that node. Called in depth-first order.
  7779. */
  7780. foreach(f) {
  7781. this.foreach_(newEmptyPath(), f);
  7782. }
  7783. foreach_(currentRelativePath, f) {
  7784. this.children.inorderTraversal((childName, childTree) => {
  7785. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7786. });
  7787. if (this.value) {
  7788. f(currentRelativePath, this.value);
  7789. }
  7790. }
  7791. foreachChild(f) {
  7792. this.children.inorderTraversal((childName, childTree) => {
  7793. if (childTree.value) {
  7794. f(childName, childTree.value);
  7795. }
  7796. });
  7797. }
  7798. }
  7799. /**
  7800. * @license
  7801. * Copyright 2017 Google LLC
  7802. *
  7803. * Licensed under the Apache License, Version 2.0 (the "License");
  7804. * you may not use this file except in compliance with the License.
  7805. * You may obtain a copy of the License at
  7806. *
  7807. * http://www.apache.org/licenses/LICENSE-2.0
  7808. *
  7809. * Unless required by applicable law or agreed to in writing, software
  7810. * distributed under the License is distributed on an "AS IS" BASIS,
  7811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7812. * See the License for the specific language governing permissions and
  7813. * limitations under the License.
  7814. */
  7815. /**
  7816. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7817. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7818. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7819. * to reflect the write added.
  7820. */
  7821. class CompoundWrite {
  7822. constructor(writeTree_) {
  7823. this.writeTree_ = writeTree_;
  7824. }
  7825. static empty() {
  7826. return new CompoundWrite(new ImmutableTree(null));
  7827. }
  7828. }
  7829. function compoundWriteAddWrite(compoundWrite, path, node) {
  7830. if (pathIsEmpty(path)) {
  7831. return new CompoundWrite(new ImmutableTree(node));
  7832. }
  7833. else {
  7834. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7835. if (rootmost != null) {
  7836. const rootMostPath = rootmost.path;
  7837. let value = rootmost.value;
  7838. const relativePath = newRelativePath(rootMostPath, path);
  7839. value = value.updateChild(relativePath, node);
  7840. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7841. }
  7842. else {
  7843. const subtree = new ImmutableTree(node);
  7844. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7845. return new CompoundWrite(newWriteTree);
  7846. }
  7847. }
  7848. }
  7849. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7850. let newWrite = compoundWrite;
  7851. each(updates, (childKey, node) => {
  7852. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7853. });
  7854. return newWrite;
  7855. }
  7856. /**
  7857. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7858. * location, which must be removed by calling this method with that path.
  7859. *
  7860. * @param compoundWrite - The CompoundWrite to remove.
  7861. * @param path - The path at which a write and all deeper writes should be removed
  7862. * @returns The new CompoundWrite with the removed path
  7863. */
  7864. function compoundWriteRemoveWrite(compoundWrite, path) {
  7865. if (pathIsEmpty(path)) {
  7866. return CompoundWrite.empty();
  7867. }
  7868. else {
  7869. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7870. return new CompoundWrite(newWriteTree);
  7871. }
  7872. }
  7873. /**
  7874. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7875. * considered "complete".
  7876. *
  7877. * @param compoundWrite - The CompoundWrite to check.
  7878. * @param path - The path to check for
  7879. * @returns Whether there is a complete write at that path
  7880. */
  7881. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7882. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7883. }
  7884. /**
  7885. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7886. * writes from deeper paths, but will return child nodes from a more shallow path.
  7887. *
  7888. * @param compoundWrite - The CompoundWrite to get the node from.
  7889. * @param path - The path to get a complete write
  7890. * @returns The node if complete at that path, or null otherwise.
  7891. */
  7892. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7893. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7894. if (rootmost != null) {
  7895. return compoundWrite.writeTree_
  7896. .get(rootmost.path)
  7897. .getChild(newRelativePath(rootmost.path, path));
  7898. }
  7899. else {
  7900. return null;
  7901. }
  7902. }
  7903. /**
  7904. * Returns all children that are guaranteed to be a complete overwrite.
  7905. *
  7906. * @param compoundWrite - The CompoundWrite to get children from.
  7907. * @returns A list of all complete children.
  7908. */
  7909. function compoundWriteGetCompleteChildren(compoundWrite) {
  7910. const children = [];
  7911. const node = compoundWrite.writeTree_.value;
  7912. if (node != null) {
  7913. // If it's a leaf node, it has no children; so nothing to do.
  7914. if (!node.isLeafNode()) {
  7915. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7916. children.push(new NamedNode(childName, childNode));
  7917. });
  7918. }
  7919. }
  7920. else {
  7921. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7922. if (childTree.value != null) {
  7923. children.push(new NamedNode(childName, childTree.value));
  7924. }
  7925. });
  7926. }
  7927. return children;
  7928. }
  7929. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7930. if (pathIsEmpty(path)) {
  7931. return compoundWrite;
  7932. }
  7933. else {
  7934. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7935. if (shadowingNode != null) {
  7936. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7937. }
  7938. else {
  7939. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7940. }
  7941. }
  7942. }
  7943. /**
  7944. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7945. * @returns Whether this CompoundWrite is empty
  7946. */
  7947. function compoundWriteIsEmpty(compoundWrite) {
  7948. return compoundWrite.writeTree_.isEmpty();
  7949. }
  7950. /**
  7951. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7952. * node
  7953. * @param node - The node to apply this CompoundWrite to
  7954. * @returns The node with all writes applied
  7955. */
  7956. function compoundWriteApply(compoundWrite, node) {
  7957. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7958. }
  7959. function applySubtreeWrite(relativePath, writeTree, node) {
  7960. if (writeTree.value != null) {
  7961. // Since there a write is always a leaf, we're done here
  7962. return node.updateChild(relativePath, writeTree.value);
  7963. }
  7964. else {
  7965. let priorityWrite = null;
  7966. writeTree.children.inorderTraversal((childKey, childTree) => {
  7967. if (childKey === '.priority') {
  7968. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7969. // to apply priorities to empty nodes that are later filled
  7970. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7971. priorityWrite = childTree.value;
  7972. }
  7973. else {
  7974. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7975. }
  7976. });
  7977. // If there was a priority write, we only apply it if the node is not empty
  7978. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7979. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7980. }
  7981. return node;
  7982. }
  7983. }
  7984. /**
  7985. * @license
  7986. * Copyright 2017 Google LLC
  7987. *
  7988. * Licensed under the Apache License, Version 2.0 (the "License");
  7989. * you may not use this file except in compliance with the License.
  7990. * You may obtain a copy of the License at
  7991. *
  7992. * http://www.apache.org/licenses/LICENSE-2.0
  7993. *
  7994. * Unless required by applicable law or agreed to in writing, software
  7995. * distributed under the License is distributed on an "AS IS" BASIS,
  7996. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7997. * See the License for the specific language governing permissions and
  7998. * limitations under the License.
  7999. */
  8000. /**
  8001. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8002. *
  8003. */
  8004. function writeTreeChildWrites(writeTree, path) {
  8005. return newWriteTreeRef(path, writeTree);
  8006. }
  8007. /**
  8008. * Record a new overwrite from user code.
  8009. *
  8010. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8011. */
  8012. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8013. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8014. if (visible === undefined) {
  8015. visible = true;
  8016. }
  8017. writeTree.allWrites.push({
  8018. path,
  8019. snap,
  8020. writeId,
  8021. visible
  8022. });
  8023. if (visible) {
  8024. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8025. }
  8026. writeTree.lastWriteId = writeId;
  8027. }
  8028. /**
  8029. * Record a new merge from user code.
  8030. */
  8031. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8032. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8033. writeTree.allWrites.push({
  8034. path,
  8035. children: changedChildren,
  8036. writeId,
  8037. visible: true
  8038. });
  8039. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8040. writeTree.lastWriteId = writeId;
  8041. }
  8042. function writeTreeGetWrite(writeTree, writeId) {
  8043. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8044. const record = writeTree.allWrites[i];
  8045. if (record.writeId === writeId) {
  8046. return record;
  8047. }
  8048. }
  8049. return null;
  8050. }
  8051. /**
  8052. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8053. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8054. *
  8055. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8056. * events as a result).
  8057. */
  8058. function writeTreeRemoveWrite(writeTree, writeId) {
  8059. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8060. // out of order.
  8061. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8062. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8063. const idx = writeTree.allWrites.findIndex(s => {
  8064. return s.writeId === writeId;
  8065. });
  8066. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8067. const writeToRemove = writeTree.allWrites[idx];
  8068. writeTree.allWrites.splice(idx, 1);
  8069. let removedWriteWasVisible = writeToRemove.visible;
  8070. let removedWriteOverlapsWithOtherWrites = false;
  8071. let i = writeTree.allWrites.length - 1;
  8072. while (removedWriteWasVisible && i >= 0) {
  8073. const currentWrite = writeTree.allWrites[i];
  8074. if (currentWrite.visible) {
  8075. if (i >= idx &&
  8076. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8077. // The removed write was completely shadowed by a subsequent write.
  8078. removedWriteWasVisible = false;
  8079. }
  8080. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8081. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8082. removedWriteOverlapsWithOtherWrites = true;
  8083. }
  8084. }
  8085. i--;
  8086. }
  8087. if (!removedWriteWasVisible) {
  8088. return false;
  8089. }
  8090. else if (removedWriteOverlapsWithOtherWrites) {
  8091. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8092. writeTreeResetTree_(writeTree);
  8093. return true;
  8094. }
  8095. else {
  8096. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8097. if (writeToRemove.snap) {
  8098. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8099. }
  8100. else {
  8101. const children = writeToRemove.children;
  8102. each(children, (childName) => {
  8103. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8104. });
  8105. }
  8106. return true;
  8107. }
  8108. }
  8109. function writeTreeRecordContainsPath_(writeRecord, path) {
  8110. if (writeRecord.snap) {
  8111. return pathContains(writeRecord.path, path);
  8112. }
  8113. else {
  8114. for (const childName in writeRecord.children) {
  8115. if (writeRecord.children.hasOwnProperty(childName) &&
  8116. pathContains(pathChild(writeRecord.path, childName), path)) {
  8117. return true;
  8118. }
  8119. }
  8120. return false;
  8121. }
  8122. }
  8123. /**
  8124. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8125. */
  8126. function writeTreeResetTree_(writeTree) {
  8127. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8128. if (writeTree.allWrites.length > 0) {
  8129. writeTree.lastWriteId =
  8130. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8131. }
  8132. else {
  8133. writeTree.lastWriteId = -1;
  8134. }
  8135. }
  8136. /**
  8137. * The default filter used when constructing the tree. Keep everything that's visible.
  8138. */
  8139. function writeTreeDefaultFilter_(write) {
  8140. return write.visible;
  8141. }
  8142. /**
  8143. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8144. * event data at that path.
  8145. */
  8146. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8147. let compoundWrite = CompoundWrite.empty();
  8148. for (let i = 0; i < writes.length; ++i) {
  8149. const write = writes[i];
  8150. // Theory, a later set will either:
  8151. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8152. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8153. if (filter(write)) {
  8154. const writePath = write.path;
  8155. let relativePath;
  8156. if (write.snap) {
  8157. if (pathContains(treeRoot, writePath)) {
  8158. relativePath = newRelativePath(treeRoot, writePath);
  8159. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8160. }
  8161. else if (pathContains(writePath, treeRoot)) {
  8162. relativePath = newRelativePath(writePath, treeRoot);
  8163. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8164. }
  8165. else ;
  8166. }
  8167. else if (write.children) {
  8168. if (pathContains(treeRoot, writePath)) {
  8169. relativePath = newRelativePath(treeRoot, writePath);
  8170. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8171. }
  8172. else if (pathContains(writePath, treeRoot)) {
  8173. relativePath = newRelativePath(writePath, treeRoot);
  8174. if (pathIsEmpty(relativePath)) {
  8175. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8176. }
  8177. else {
  8178. const child = safeGet(write.children, pathGetFront(relativePath));
  8179. if (child) {
  8180. // There exists a child in this node that matches the root path
  8181. const deepNode = child.getChild(pathPopFront(relativePath));
  8182. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8183. }
  8184. }
  8185. }
  8186. else ;
  8187. }
  8188. else {
  8189. throw assertionError('WriteRecord should have .snap or .children');
  8190. }
  8191. }
  8192. }
  8193. return compoundWrite;
  8194. }
  8195. /**
  8196. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8197. * writes), attempt to calculate a complete snapshot for the given path
  8198. *
  8199. * @param writeIdsToExclude - An optional set to be excluded
  8200. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8201. */
  8202. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8203. if (!writeIdsToExclude && !includeHiddenWrites) {
  8204. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8205. if (shadowingNode != null) {
  8206. return shadowingNode;
  8207. }
  8208. else {
  8209. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8210. if (compoundWriteIsEmpty(subMerge)) {
  8211. return completeServerCache;
  8212. }
  8213. else if (completeServerCache == null &&
  8214. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8215. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8216. return null;
  8217. }
  8218. else {
  8219. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8220. return compoundWriteApply(subMerge, layeredCache);
  8221. }
  8222. }
  8223. }
  8224. else {
  8225. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8226. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8227. return completeServerCache;
  8228. }
  8229. else {
  8230. // If the server cache is null, and we don't have a complete cache, we need to return null
  8231. if (!includeHiddenWrites &&
  8232. completeServerCache == null &&
  8233. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8234. return null;
  8235. }
  8236. else {
  8237. const filter = function (write) {
  8238. return ((write.visible || includeHiddenWrites) &&
  8239. (!writeIdsToExclude ||
  8240. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8241. (pathContains(write.path, treePath) ||
  8242. pathContains(treePath, write.path)));
  8243. };
  8244. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8245. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8246. return compoundWriteApply(mergeAtPath, layeredCache);
  8247. }
  8248. }
  8249. }
  8250. }
  8251. /**
  8252. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8253. * Used when creating new views, to pre-fill their complete event children snapshot.
  8254. */
  8255. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8256. let completeChildren = ChildrenNode.EMPTY_NODE;
  8257. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8258. if (topLevelSet) {
  8259. if (!topLevelSet.isLeafNode()) {
  8260. // we're shadowing everything. Return the children.
  8261. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8262. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8263. });
  8264. }
  8265. return completeChildren;
  8266. }
  8267. else if (completeServerChildren) {
  8268. // Layer any children we have on top of this
  8269. // We know we don't have a top-level set, so just enumerate existing children
  8270. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8271. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8272. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8273. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8274. });
  8275. // Add any complete children we have from the set
  8276. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8277. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8278. });
  8279. return completeChildren;
  8280. }
  8281. else {
  8282. // We don't have anything to layer on top of. Layer on any children we have
  8283. // Note that we can return an empty snap if we have a defined delete
  8284. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8285. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8286. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8287. });
  8288. return completeChildren;
  8289. }
  8290. }
  8291. /**
  8292. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8293. * applied to the event cache.
  8294. *
  8295. * Possibilities:
  8296. *
  8297. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8298. *
  8299. * 2. Some write is completely shadowing. No events to be raised
  8300. *
  8301. * 3. Is partially shadowed. Events
  8302. *
  8303. * Either existingEventSnap or existingServerSnap must exist
  8304. */
  8305. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8306. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8307. const path = pathChild(treePath, childPath);
  8308. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8309. // At this point we can probably guarantee that we're in case 2, meaning no events
  8310. // May need to check visibility while doing the findRootMostValueAndPath call
  8311. return null;
  8312. }
  8313. else {
  8314. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8315. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8316. if (compoundWriteIsEmpty(childMerge)) {
  8317. // We're not shadowing at all. Case 1
  8318. return existingServerSnap.getChild(childPath);
  8319. }
  8320. else {
  8321. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8322. // However this is tricky to find out, since user updates don't necessary change the server
  8323. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8324. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8325. // only check if the updates change the serverNode.
  8326. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8327. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8328. }
  8329. }
  8330. }
  8331. /**
  8332. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8333. * complete child for this ChildKey.
  8334. */
  8335. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8336. const path = pathChild(treePath, childKey);
  8337. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8338. if (shadowingNode != null) {
  8339. return shadowingNode;
  8340. }
  8341. else {
  8342. if (existingServerSnap.isCompleteForChild(childKey)) {
  8343. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8344. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8345. }
  8346. else {
  8347. return null;
  8348. }
  8349. }
  8350. }
  8351. /**
  8352. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8353. * a higher path, this will return the child of that write relative to the write and this path.
  8354. * Returns null if there is no write at this path.
  8355. */
  8356. function writeTreeShadowingWrite(writeTree, path) {
  8357. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8358. }
  8359. /**
  8360. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8361. * the window, but may now be in the window.
  8362. */
  8363. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8364. let toIterate;
  8365. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8366. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8367. if (shadowingNode != null) {
  8368. toIterate = shadowingNode;
  8369. }
  8370. else if (completeServerData != null) {
  8371. toIterate = compoundWriteApply(merge, completeServerData);
  8372. }
  8373. else {
  8374. // no children to iterate on
  8375. return [];
  8376. }
  8377. toIterate = toIterate.withIndex(index);
  8378. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8379. const nodes = [];
  8380. const cmp = index.getCompare();
  8381. const iter = reverse
  8382. ? toIterate.getReverseIteratorFrom(startPost, index)
  8383. : toIterate.getIteratorFrom(startPost, index);
  8384. let next = iter.getNext();
  8385. while (next && nodes.length < count) {
  8386. if (cmp(next, startPost) !== 0) {
  8387. nodes.push(next);
  8388. }
  8389. next = iter.getNext();
  8390. }
  8391. return nodes;
  8392. }
  8393. else {
  8394. return [];
  8395. }
  8396. }
  8397. function newWriteTree() {
  8398. return {
  8399. visibleWrites: CompoundWrite.empty(),
  8400. allWrites: [],
  8401. lastWriteId: -1
  8402. };
  8403. }
  8404. /**
  8405. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8406. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8407. * can lead to a more expensive calculation.
  8408. *
  8409. * @param writeIdsToExclude - Optional writes to exclude.
  8410. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8411. */
  8412. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8413. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8414. }
  8415. /**
  8416. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8417. * mix of the given server data and write data.
  8418. *
  8419. */
  8420. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8421. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8422. }
  8423. /**
  8424. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8425. * if anything, needs to be applied to the event cache.
  8426. *
  8427. * Possibilities:
  8428. *
  8429. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8430. *
  8431. * 2. Some write is completely shadowing. No events to be raised
  8432. *
  8433. * 3. Is partially shadowed. Events should be raised
  8434. *
  8435. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8436. *
  8437. *
  8438. */
  8439. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8440. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8441. }
  8442. /**
  8443. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8444. * a higher path, this will return the child of that write relative to the write and this path.
  8445. * Returns null if there is no write at this path.
  8446. *
  8447. */
  8448. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8449. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8450. }
  8451. /**
  8452. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8453. * the window, but may now be in the window
  8454. */
  8455. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8456. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8457. }
  8458. /**
  8459. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8460. * complete child for this ChildKey.
  8461. */
  8462. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8463. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8464. }
  8465. /**
  8466. * Return a WriteTreeRef for a child.
  8467. */
  8468. function writeTreeRefChild(writeTreeRef, childName) {
  8469. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8470. }
  8471. function newWriteTreeRef(path, writeTree) {
  8472. return {
  8473. treePath: path,
  8474. writeTree
  8475. };
  8476. }
  8477. /**
  8478. * @license
  8479. * Copyright 2017 Google LLC
  8480. *
  8481. * Licensed under the Apache License, Version 2.0 (the "License");
  8482. * you may not use this file except in compliance with the License.
  8483. * You may obtain a copy of the License at
  8484. *
  8485. * http://www.apache.org/licenses/LICENSE-2.0
  8486. *
  8487. * Unless required by applicable law or agreed to in writing, software
  8488. * distributed under the License is distributed on an "AS IS" BASIS,
  8489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8490. * See the License for the specific language governing permissions and
  8491. * limitations under the License.
  8492. */
  8493. class ChildChangeAccumulator {
  8494. constructor() {
  8495. this.changeMap = new Map();
  8496. }
  8497. trackChildChange(change) {
  8498. const type = change.type;
  8499. const childKey = change.childName;
  8500. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8501. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8502. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8503. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8504. const oldChange = this.changeMap.get(childKey);
  8505. if (oldChange) {
  8506. const oldType = oldChange.type;
  8507. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8508. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8509. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8510. }
  8511. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8512. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8513. this.changeMap.delete(childKey);
  8514. }
  8515. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8516. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8517. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8518. }
  8519. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8520. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8521. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8522. }
  8523. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8524. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8525. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8526. }
  8527. else {
  8528. throw assertionError('Illegal combination of changes: ' +
  8529. change +
  8530. ' occurred after ' +
  8531. oldChange);
  8532. }
  8533. }
  8534. else {
  8535. this.changeMap.set(childKey, change);
  8536. }
  8537. }
  8538. getChanges() {
  8539. return Array.from(this.changeMap.values());
  8540. }
  8541. }
  8542. /**
  8543. * @license
  8544. * Copyright 2017 Google LLC
  8545. *
  8546. * Licensed under the Apache License, Version 2.0 (the "License");
  8547. * you may not use this file except in compliance with the License.
  8548. * You may obtain a copy of the License at
  8549. *
  8550. * http://www.apache.org/licenses/LICENSE-2.0
  8551. *
  8552. * Unless required by applicable law or agreed to in writing, software
  8553. * distributed under the License is distributed on an "AS IS" BASIS,
  8554. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8555. * See the License for the specific language governing permissions and
  8556. * limitations under the License.
  8557. */
  8558. /**
  8559. * An implementation of CompleteChildSource that never returns any additional children
  8560. */
  8561. // eslint-disable-next-line @typescript-eslint/naming-convention
  8562. class NoCompleteChildSource_ {
  8563. getCompleteChild(childKey) {
  8564. return null;
  8565. }
  8566. getChildAfterChild(index, child, reverse) {
  8567. return null;
  8568. }
  8569. }
  8570. /**
  8571. * Singleton instance.
  8572. */
  8573. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8574. /**
  8575. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8576. * old event caches available to calculate complete children.
  8577. */
  8578. class WriteTreeCompleteChildSource {
  8579. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8580. this.writes_ = writes_;
  8581. this.viewCache_ = viewCache_;
  8582. this.optCompleteServerCache_ = optCompleteServerCache_;
  8583. }
  8584. getCompleteChild(childKey) {
  8585. const node = this.viewCache_.eventCache;
  8586. if (node.isCompleteForChild(childKey)) {
  8587. return node.getNode().getImmediateChild(childKey);
  8588. }
  8589. else {
  8590. const serverNode = this.optCompleteServerCache_ != null
  8591. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8592. : this.viewCache_.serverCache;
  8593. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8594. }
  8595. }
  8596. getChildAfterChild(index, child, reverse) {
  8597. const completeServerData = this.optCompleteServerCache_ != null
  8598. ? this.optCompleteServerCache_
  8599. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8600. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8601. if (nodes.length === 0) {
  8602. return null;
  8603. }
  8604. else {
  8605. return nodes[0];
  8606. }
  8607. }
  8608. }
  8609. /**
  8610. * @license
  8611. * Copyright 2017 Google LLC
  8612. *
  8613. * Licensed under the Apache License, Version 2.0 (the "License");
  8614. * you may not use this file except in compliance with the License.
  8615. * You may obtain a copy of the License at
  8616. *
  8617. * http://www.apache.org/licenses/LICENSE-2.0
  8618. *
  8619. * Unless required by applicable law or agreed to in writing, software
  8620. * distributed under the License is distributed on an "AS IS" BASIS,
  8621. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8622. * See the License for the specific language governing permissions and
  8623. * limitations under the License.
  8624. */
  8625. function newViewProcessor(filter) {
  8626. return { filter };
  8627. }
  8628. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8629. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8630. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8631. }
  8632. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8633. const accumulator = new ChildChangeAccumulator();
  8634. let newViewCache, filterServerNode;
  8635. if (operation.type === OperationType.OVERWRITE) {
  8636. const overwrite = operation;
  8637. if (overwrite.source.fromUser) {
  8638. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8639. }
  8640. else {
  8641. assert(overwrite.source.fromServer, 'Unknown source.');
  8642. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8643. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8644. // again
  8645. filterServerNode =
  8646. overwrite.source.tagged ||
  8647. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8648. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8649. }
  8650. }
  8651. else if (operation.type === OperationType.MERGE) {
  8652. const merge = operation;
  8653. if (merge.source.fromUser) {
  8654. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8655. }
  8656. else {
  8657. assert(merge.source.fromServer, 'Unknown source.');
  8658. // We filter the node if it's a tagged update or the node has been previously filtered
  8659. filterServerNode =
  8660. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8661. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8662. }
  8663. }
  8664. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8665. const ackUserWrite = operation;
  8666. if (!ackUserWrite.revert) {
  8667. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8668. }
  8669. else {
  8670. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8671. }
  8672. }
  8673. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8674. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8675. }
  8676. else {
  8677. throw assertionError('Unknown operation type: ' + operation.type);
  8678. }
  8679. const changes = accumulator.getChanges();
  8680. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8681. return { viewCache: newViewCache, changes };
  8682. }
  8683. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8684. const eventSnap = newViewCache.eventCache;
  8685. if (eventSnap.isFullyInitialized()) {
  8686. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8687. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8688. if (accumulator.length > 0 ||
  8689. !oldViewCache.eventCache.isFullyInitialized() ||
  8690. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8691. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8692. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8693. }
  8694. }
  8695. }
  8696. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8697. const oldEventSnap = viewCache.eventCache;
  8698. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8699. // we have a shadowing write, ignore changes
  8700. return viewCache;
  8701. }
  8702. else {
  8703. let newEventCache, serverNode;
  8704. if (pathIsEmpty(changePath)) {
  8705. // TODO: figure out how this plays with "sliding ack windows"
  8706. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8707. if (viewCache.serverCache.isFiltered()) {
  8708. // We need to special case this, because we need to only apply writes to complete children, or
  8709. // we might end up raising events for incomplete children. If the server data is filtered deep
  8710. // writes cannot be guaranteed to be complete
  8711. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8712. const completeChildren = serverCache instanceof ChildrenNode
  8713. ? serverCache
  8714. : ChildrenNode.EMPTY_NODE;
  8715. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8716. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8717. }
  8718. else {
  8719. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8720. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8721. }
  8722. }
  8723. else {
  8724. const childKey = pathGetFront(changePath);
  8725. if (childKey === '.priority') {
  8726. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8727. const oldEventNode = oldEventSnap.getNode();
  8728. serverNode = viewCache.serverCache.getNode();
  8729. // we might have overwrites for this priority
  8730. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8731. if (updatedPriority != null) {
  8732. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8733. }
  8734. else {
  8735. // priority didn't change, keep old node
  8736. newEventCache = oldEventSnap.getNode();
  8737. }
  8738. }
  8739. else {
  8740. const childChangePath = pathPopFront(changePath);
  8741. // update child
  8742. let newEventChild;
  8743. if (oldEventSnap.isCompleteForChild(childKey)) {
  8744. serverNode = viewCache.serverCache.getNode();
  8745. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8746. if (eventChildUpdate != null) {
  8747. newEventChild = oldEventSnap
  8748. .getNode()
  8749. .getImmediateChild(childKey)
  8750. .updateChild(childChangePath, eventChildUpdate);
  8751. }
  8752. else {
  8753. // Nothing changed, just keep the old child
  8754. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8755. }
  8756. }
  8757. else {
  8758. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8759. }
  8760. if (newEventChild != null) {
  8761. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8762. }
  8763. else {
  8764. // no complete child available or no change
  8765. newEventCache = oldEventSnap.getNode();
  8766. }
  8767. }
  8768. }
  8769. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8770. }
  8771. }
  8772. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8773. const oldServerSnap = oldViewCache.serverCache;
  8774. let newServerCache;
  8775. const serverFilter = filterServerNode
  8776. ? viewProcessor.filter
  8777. : viewProcessor.filter.getIndexedFilter();
  8778. if (pathIsEmpty(changePath)) {
  8779. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8780. }
  8781. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8782. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8783. const newServerNode = oldServerSnap
  8784. .getNode()
  8785. .updateChild(changePath, changedSnap);
  8786. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8787. }
  8788. else {
  8789. const childKey = pathGetFront(changePath);
  8790. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8791. pathGetLength(changePath) > 1) {
  8792. // We don't update incomplete nodes with updates intended for other listeners
  8793. return oldViewCache;
  8794. }
  8795. const childChangePath = pathPopFront(changePath);
  8796. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8797. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8798. if (childKey === '.priority') {
  8799. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8800. }
  8801. else {
  8802. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8803. }
  8804. }
  8805. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8806. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8807. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8808. }
  8809. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8810. const oldEventSnap = oldViewCache.eventCache;
  8811. let newViewCache, newEventCache;
  8812. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8813. if (pathIsEmpty(changePath)) {
  8814. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8815. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8816. }
  8817. else {
  8818. const childKey = pathGetFront(changePath);
  8819. if (childKey === '.priority') {
  8820. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8821. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8822. }
  8823. else {
  8824. const childChangePath = pathPopFront(changePath);
  8825. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8826. let newChild;
  8827. if (pathIsEmpty(childChangePath)) {
  8828. // Child overwrite, we can replace the child
  8829. newChild = changedSnap;
  8830. }
  8831. else {
  8832. const childNode = source.getCompleteChild(childKey);
  8833. if (childNode != null) {
  8834. if (pathGetBack(childChangePath) === '.priority' &&
  8835. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8836. // This is a priority update on an empty node. If this node exists on the server, the
  8837. // server will send down the priority in the update, so ignore for now
  8838. newChild = childNode;
  8839. }
  8840. else {
  8841. newChild = childNode.updateChild(childChangePath, changedSnap);
  8842. }
  8843. }
  8844. else {
  8845. // There is no complete child node available
  8846. newChild = ChildrenNode.EMPTY_NODE;
  8847. }
  8848. }
  8849. if (!oldChild.equals(newChild)) {
  8850. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8851. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8852. }
  8853. else {
  8854. newViewCache = oldViewCache;
  8855. }
  8856. }
  8857. }
  8858. return newViewCache;
  8859. }
  8860. function viewProcessorCacheHasChild(viewCache, childKey) {
  8861. return viewCache.eventCache.isCompleteForChild(childKey);
  8862. }
  8863. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8864. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8865. // window leaving room for new items. It's important we process these changes first, so we
  8866. // iterate the changes twice, first processing any that affect items currently in view.
  8867. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8868. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8869. // not the other.
  8870. let curViewCache = viewCache;
  8871. changedChildren.foreach((relativePath, childNode) => {
  8872. const writePath = pathChild(path, relativePath);
  8873. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8874. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8875. }
  8876. });
  8877. changedChildren.foreach((relativePath, childNode) => {
  8878. const writePath = pathChild(path, relativePath);
  8879. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8880. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8881. }
  8882. });
  8883. return curViewCache;
  8884. }
  8885. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8886. merge.foreach((relativePath, childNode) => {
  8887. node = node.updateChild(relativePath, childNode);
  8888. });
  8889. return node;
  8890. }
  8891. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8892. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8893. // wait for the complete data update coming soon.
  8894. if (viewCache.serverCache.getNode().isEmpty() &&
  8895. !viewCache.serverCache.isFullyInitialized()) {
  8896. return viewCache;
  8897. }
  8898. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8899. // window leaving room for new items. It's important we process these changes first, so we
  8900. // iterate the changes twice, first processing any that affect items currently in view.
  8901. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8902. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8903. // not the other.
  8904. let curViewCache = viewCache;
  8905. let viewMergeTree;
  8906. if (pathIsEmpty(path)) {
  8907. viewMergeTree = changedChildren;
  8908. }
  8909. else {
  8910. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8911. }
  8912. const serverNode = viewCache.serverCache.getNode();
  8913. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8914. if (serverNode.hasChild(childKey)) {
  8915. const serverChild = viewCache.serverCache
  8916. .getNode()
  8917. .getImmediateChild(childKey);
  8918. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8919. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8920. }
  8921. });
  8922. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8923. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8924. childMergeTree.value === null;
  8925. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8926. const serverChild = viewCache.serverCache
  8927. .getNode()
  8928. .getImmediateChild(childKey);
  8929. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8930. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8931. }
  8932. });
  8933. return curViewCache;
  8934. }
  8935. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8936. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8937. return viewCache;
  8938. }
  8939. // Only filter server node if it is currently filtered
  8940. const filterServerNode = viewCache.serverCache.isFiltered();
  8941. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8942. // now that it won't be shadowed.
  8943. const serverCache = viewCache.serverCache;
  8944. if (affectedTree.value != null) {
  8945. // This is an overwrite.
  8946. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8947. serverCache.isCompleteForPath(ackPath)) {
  8948. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8949. }
  8950. else if (pathIsEmpty(ackPath)) {
  8951. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8952. // should just re-apply whatever we have in our cache as a merge.
  8953. let changedChildren = new ImmutableTree(null);
  8954. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8955. changedChildren = changedChildren.set(new Path(name), node);
  8956. });
  8957. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8958. }
  8959. else {
  8960. return viewCache;
  8961. }
  8962. }
  8963. else {
  8964. // This is a merge.
  8965. let changedChildren = new ImmutableTree(null);
  8966. affectedTree.foreach((mergePath, value) => {
  8967. const serverCachePath = pathChild(ackPath, mergePath);
  8968. if (serverCache.isCompleteForPath(serverCachePath)) {
  8969. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8970. }
  8971. });
  8972. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8973. }
  8974. }
  8975. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8976. const oldServerNode = viewCache.serverCache;
  8977. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8978. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8979. }
  8980. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8981. let complete;
  8982. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8983. return viewCache;
  8984. }
  8985. else {
  8986. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8987. const oldEventCache = viewCache.eventCache.getNode();
  8988. let newEventCache;
  8989. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  8990. let newNode;
  8991. if (viewCache.serverCache.isFullyInitialized()) {
  8992. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8993. }
  8994. else {
  8995. const serverChildren = viewCache.serverCache.getNode();
  8996. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  8997. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  8998. }
  8999. newNode = newNode;
  9000. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9001. }
  9002. else {
  9003. const childKey = pathGetFront(path);
  9004. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9005. if (newChild == null &&
  9006. viewCache.serverCache.isCompleteForChild(childKey)) {
  9007. newChild = oldEventCache.getImmediateChild(childKey);
  9008. }
  9009. if (newChild != null) {
  9010. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9011. }
  9012. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9013. // No complete child available, delete the existing one, if any
  9014. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9015. }
  9016. else {
  9017. newEventCache = oldEventCache;
  9018. }
  9019. if (newEventCache.isEmpty() &&
  9020. viewCache.serverCache.isFullyInitialized()) {
  9021. // We might have reverted all child writes. Maybe the old event was a leaf node
  9022. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9023. if (complete.isLeafNode()) {
  9024. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9025. }
  9026. }
  9027. }
  9028. complete =
  9029. viewCache.serverCache.isFullyInitialized() ||
  9030. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9031. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9032. }
  9033. }
  9034. /**
  9035. * @license
  9036. * Copyright 2017 Google LLC
  9037. *
  9038. * Licensed under the Apache License, Version 2.0 (the "License");
  9039. * you may not use this file except in compliance with the License.
  9040. * You may obtain a copy of the License at
  9041. *
  9042. * http://www.apache.org/licenses/LICENSE-2.0
  9043. *
  9044. * Unless required by applicable law or agreed to in writing, software
  9045. * distributed under the License is distributed on an "AS IS" BASIS,
  9046. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9047. * See the License for the specific language governing permissions and
  9048. * limitations under the License.
  9049. */
  9050. /**
  9051. * A view represents a specific location and query that has 1 or more event registrations.
  9052. *
  9053. * It does several things:
  9054. * - Maintains the list of event registrations for this location/query.
  9055. * - Maintains a cache of the data visible for this location/query.
  9056. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9057. * registrations returns the set of events to be raised.
  9058. */
  9059. class View {
  9060. constructor(query_, initialViewCache) {
  9061. this.query_ = query_;
  9062. this.eventRegistrations_ = [];
  9063. const params = this.query_._queryParams;
  9064. const indexFilter = new IndexedFilter(params.getIndex());
  9065. const filter = queryParamsGetNodeFilter(params);
  9066. this.processor_ = newViewProcessor(filter);
  9067. const initialServerCache = initialViewCache.serverCache;
  9068. const initialEventCache = initialViewCache.eventCache;
  9069. // Don't filter server node with other filter than index, wait for tagged listen
  9070. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9071. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9072. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9073. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9074. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9075. this.eventGenerator_ = new EventGenerator(this.query_);
  9076. }
  9077. get query() {
  9078. return this.query_;
  9079. }
  9080. }
  9081. function viewGetServerCache(view) {
  9082. return view.viewCache_.serverCache.getNode();
  9083. }
  9084. function viewGetCompleteNode(view) {
  9085. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9086. }
  9087. function viewGetCompleteServerCache(view, path) {
  9088. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9089. if (cache) {
  9090. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9091. // we need to see if it contains the child we're interested in.
  9092. if (view.query._queryParams.loadsAllData() ||
  9093. (!pathIsEmpty(path) &&
  9094. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9095. return cache.getChild(path);
  9096. }
  9097. }
  9098. return null;
  9099. }
  9100. function viewIsEmpty(view) {
  9101. return view.eventRegistrations_.length === 0;
  9102. }
  9103. function viewAddEventRegistration(view, eventRegistration) {
  9104. view.eventRegistrations_.push(eventRegistration);
  9105. }
  9106. /**
  9107. * @param eventRegistration - If null, remove all callbacks.
  9108. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9109. * @returns Cancel events, if cancelError was provided.
  9110. */
  9111. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9112. const cancelEvents = [];
  9113. if (cancelError) {
  9114. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9115. const path = view.query._path;
  9116. view.eventRegistrations_.forEach(registration => {
  9117. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9118. if (maybeEvent) {
  9119. cancelEvents.push(maybeEvent);
  9120. }
  9121. });
  9122. }
  9123. if (eventRegistration) {
  9124. let remaining = [];
  9125. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9126. const existing = view.eventRegistrations_[i];
  9127. if (!existing.matches(eventRegistration)) {
  9128. remaining.push(existing);
  9129. }
  9130. else if (eventRegistration.hasAnyCallback()) {
  9131. // We're removing just this one
  9132. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9133. break;
  9134. }
  9135. }
  9136. view.eventRegistrations_ = remaining;
  9137. }
  9138. else {
  9139. view.eventRegistrations_ = [];
  9140. }
  9141. return cancelEvents;
  9142. }
  9143. /**
  9144. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9145. */
  9146. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9147. if (operation.type === OperationType.MERGE &&
  9148. operation.source.queryId !== null) {
  9149. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9150. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9151. }
  9152. const oldViewCache = view.viewCache_;
  9153. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9154. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9155. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9156. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9157. view.viewCache_ = result.viewCache;
  9158. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9159. }
  9160. function viewGetInitialEvents(view, registration) {
  9161. const eventSnap = view.viewCache_.eventCache;
  9162. const initialChanges = [];
  9163. if (!eventSnap.getNode().isLeafNode()) {
  9164. const eventNode = eventSnap.getNode();
  9165. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9166. initialChanges.push(changeChildAdded(key, childNode));
  9167. });
  9168. }
  9169. if (eventSnap.isFullyInitialized()) {
  9170. initialChanges.push(changeValue(eventSnap.getNode()));
  9171. }
  9172. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9173. }
  9174. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9175. const registrations = eventRegistration
  9176. ? [eventRegistration]
  9177. : view.eventRegistrations_;
  9178. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9179. }
  9180. /**
  9181. * @license
  9182. * Copyright 2017 Google LLC
  9183. *
  9184. * Licensed under the Apache License, Version 2.0 (the "License");
  9185. * you may not use this file except in compliance with the License.
  9186. * You may obtain a copy of the License at
  9187. *
  9188. * http://www.apache.org/licenses/LICENSE-2.0
  9189. *
  9190. * Unless required by applicable law or agreed to in writing, software
  9191. * distributed under the License is distributed on an "AS IS" BASIS,
  9192. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9193. * See the License for the specific language governing permissions and
  9194. * limitations under the License.
  9195. */
  9196. let referenceConstructor$1;
  9197. /**
  9198. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9199. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9200. * and user writes (set, transaction, update).
  9201. *
  9202. * It's responsible for:
  9203. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9204. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9205. * applyUserOverwrite, etc.)
  9206. */
  9207. class SyncPoint {
  9208. constructor() {
  9209. /**
  9210. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9211. * queryId and the value is the View for that query.
  9212. *
  9213. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9214. */
  9215. this.views = new Map();
  9216. }
  9217. }
  9218. function syncPointSetReferenceConstructor(val) {
  9219. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9220. referenceConstructor$1 = val;
  9221. }
  9222. function syncPointGetReferenceConstructor() {
  9223. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9224. return referenceConstructor$1;
  9225. }
  9226. function syncPointIsEmpty(syncPoint) {
  9227. return syncPoint.views.size === 0;
  9228. }
  9229. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9230. const queryId = operation.source.queryId;
  9231. if (queryId !== null) {
  9232. const view = syncPoint.views.get(queryId);
  9233. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9234. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9235. }
  9236. else {
  9237. let events = [];
  9238. for (const view of syncPoint.views.values()) {
  9239. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9240. }
  9241. return events;
  9242. }
  9243. }
  9244. /**
  9245. * Get a view for the specified query.
  9246. *
  9247. * @param query - The query to return a view for
  9248. * @param writesCache
  9249. * @param serverCache
  9250. * @param serverCacheComplete
  9251. * @returns Events to raise.
  9252. */
  9253. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9254. const queryId = query._queryIdentifier;
  9255. const view = syncPoint.views.get(queryId);
  9256. if (!view) {
  9257. // TODO: make writesCache take flag for complete server node
  9258. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9259. let eventCacheComplete = false;
  9260. if (eventCache) {
  9261. eventCacheComplete = true;
  9262. }
  9263. else if (serverCache instanceof ChildrenNode) {
  9264. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9265. eventCacheComplete = false;
  9266. }
  9267. else {
  9268. eventCache = ChildrenNode.EMPTY_NODE;
  9269. eventCacheComplete = false;
  9270. }
  9271. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9272. return new View(query, viewCache);
  9273. }
  9274. return view;
  9275. }
  9276. /**
  9277. * Add an event callback for the specified query.
  9278. *
  9279. * @param query
  9280. * @param eventRegistration
  9281. * @param writesCache
  9282. * @param serverCache - Complete server cache, if we have it.
  9283. * @param serverCacheComplete
  9284. * @returns Events to raise.
  9285. */
  9286. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9287. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9288. if (!syncPoint.views.has(query._queryIdentifier)) {
  9289. syncPoint.views.set(query._queryIdentifier, view);
  9290. }
  9291. // This is guaranteed to exist now, we just created anything that was missing
  9292. viewAddEventRegistration(view, eventRegistration);
  9293. return viewGetInitialEvents(view, eventRegistration);
  9294. }
  9295. /**
  9296. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9297. *
  9298. * If query is the default query, we'll check all views for the specified eventRegistration.
  9299. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9300. *
  9301. * @param eventRegistration - If null, remove all callbacks.
  9302. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9303. * @returns removed queries and any cancel events
  9304. */
  9305. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9306. const queryId = query._queryIdentifier;
  9307. const removed = [];
  9308. let cancelEvents = [];
  9309. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9310. if (queryId === 'default') {
  9311. // When you do ref.off(...), we search all views for the registration to remove.
  9312. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9313. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9314. if (viewIsEmpty(view)) {
  9315. syncPoint.views.delete(viewQueryId);
  9316. // We'll deal with complete views later.
  9317. if (!view.query._queryParams.loadsAllData()) {
  9318. removed.push(view.query);
  9319. }
  9320. }
  9321. }
  9322. }
  9323. else {
  9324. // remove the callback from the specific view.
  9325. const view = syncPoint.views.get(queryId);
  9326. if (view) {
  9327. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9328. if (viewIsEmpty(view)) {
  9329. syncPoint.views.delete(queryId);
  9330. // We'll deal with complete views later.
  9331. if (!view.query._queryParams.loadsAllData()) {
  9332. removed.push(view.query);
  9333. }
  9334. }
  9335. }
  9336. }
  9337. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9338. // We removed our last complete view.
  9339. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9340. }
  9341. return { removed, events: cancelEvents };
  9342. }
  9343. function syncPointGetQueryViews(syncPoint) {
  9344. const result = [];
  9345. for (const view of syncPoint.views.values()) {
  9346. if (!view.query._queryParams.loadsAllData()) {
  9347. result.push(view);
  9348. }
  9349. }
  9350. return result;
  9351. }
  9352. /**
  9353. * @param path - The path to the desired complete snapshot
  9354. * @returns A complete cache, if it exists
  9355. */
  9356. function syncPointGetCompleteServerCache(syncPoint, path) {
  9357. let serverCache = null;
  9358. for (const view of syncPoint.views.values()) {
  9359. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9360. }
  9361. return serverCache;
  9362. }
  9363. function syncPointViewForQuery(syncPoint, query) {
  9364. const params = query._queryParams;
  9365. if (params.loadsAllData()) {
  9366. return syncPointGetCompleteView(syncPoint);
  9367. }
  9368. else {
  9369. const queryId = query._queryIdentifier;
  9370. return syncPoint.views.get(queryId);
  9371. }
  9372. }
  9373. function syncPointViewExistsForQuery(syncPoint, query) {
  9374. return syncPointViewForQuery(syncPoint, query) != null;
  9375. }
  9376. function syncPointHasCompleteView(syncPoint) {
  9377. return syncPointGetCompleteView(syncPoint) != null;
  9378. }
  9379. function syncPointGetCompleteView(syncPoint) {
  9380. for (const view of syncPoint.views.values()) {
  9381. if (view.query._queryParams.loadsAllData()) {
  9382. return view;
  9383. }
  9384. }
  9385. return null;
  9386. }
  9387. /**
  9388. * @license
  9389. * Copyright 2017 Google LLC
  9390. *
  9391. * Licensed under the Apache License, Version 2.0 (the "License");
  9392. * you may not use this file except in compliance with the License.
  9393. * You may obtain a copy of the License at
  9394. *
  9395. * http://www.apache.org/licenses/LICENSE-2.0
  9396. *
  9397. * Unless required by applicable law or agreed to in writing, software
  9398. * distributed under the License is distributed on an "AS IS" BASIS,
  9399. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9400. * See the License for the specific language governing permissions and
  9401. * limitations under the License.
  9402. */
  9403. let referenceConstructor;
  9404. function syncTreeSetReferenceConstructor(val) {
  9405. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9406. referenceConstructor = val;
  9407. }
  9408. function syncTreeGetReferenceConstructor() {
  9409. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9410. return referenceConstructor;
  9411. }
  9412. /**
  9413. * Static tracker for next query tag.
  9414. */
  9415. let syncTreeNextQueryTag_ = 1;
  9416. /**
  9417. * SyncTree is the central class for managing event callback registration, data caching, views
  9418. * (query processing), and event generation. There are typically two SyncTree instances for
  9419. * each Repo, one for the normal Firebase data, and one for the .info data.
  9420. *
  9421. * It has a number of responsibilities, including:
  9422. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9423. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9424. * (applyUserOverwrite(), applyUserMerge()).
  9425. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9426. * applyServerMerge()).
  9427. * - Generating user-facing events for server and user changes (all of the apply* methods
  9428. * return the set of events that need to be raised as a result).
  9429. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9430. * to the correct set of paths and queries to satisfy the current set of user event
  9431. * callbacks (listens are started/stopped using the provided listenProvider).
  9432. *
  9433. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9434. * events are returned to the caller rather than raised synchronously.
  9435. *
  9436. */
  9437. class SyncTree {
  9438. /**
  9439. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9440. * to server data.
  9441. */
  9442. constructor(listenProvider_) {
  9443. this.listenProvider_ = listenProvider_;
  9444. /**
  9445. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9446. */
  9447. this.syncPointTree_ = new ImmutableTree(null);
  9448. /**
  9449. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9450. */
  9451. this.pendingWriteTree_ = newWriteTree();
  9452. this.tagToQueryMap = new Map();
  9453. this.queryToTagMap = new Map();
  9454. }
  9455. }
  9456. /**
  9457. * Apply the data changes for a user-generated set() or transaction() call.
  9458. *
  9459. * @returns Events to raise.
  9460. */
  9461. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9462. // Record pending write.
  9463. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9464. if (!visible) {
  9465. return [];
  9466. }
  9467. else {
  9468. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9469. }
  9470. }
  9471. /**
  9472. * Apply the data from a user-generated update() call
  9473. *
  9474. * @returns Events to raise.
  9475. */
  9476. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9477. // Record pending merge.
  9478. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9479. const changeTree = ImmutableTree.fromObject(changedChildren);
  9480. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9481. }
  9482. /**
  9483. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9484. *
  9485. * @param revert - True if the given write failed and needs to be reverted
  9486. * @returns Events to raise.
  9487. */
  9488. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9489. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9490. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9491. if (!needToReevaluate) {
  9492. return [];
  9493. }
  9494. else {
  9495. let affectedTree = new ImmutableTree(null);
  9496. if (write.snap != null) {
  9497. // overwrite
  9498. affectedTree = affectedTree.set(newEmptyPath(), true);
  9499. }
  9500. else {
  9501. each(write.children, (pathString) => {
  9502. affectedTree = affectedTree.set(new Path(pathString), true);
  9503. });
  9504. }
  9505. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9506. }
  9507. }
  9508. /**
  9509. * Apply new server data for the specified path..
  9510. *
  9511. * @returns Events to raise.
  9512. */
  9513. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9514. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9515. }
  9516. /**
  9517. * Apply new server data to be merged in at the specified path.
  9518. *
  9519. * @returns Events to raise.
  9520. */
  9521. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9522. const changeTree = ImmutableTree.fromObject(changedChildren);
  9523. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9524. }
  9525. /**
  9526. * Apply a listen complete for a query
  9527. *
  9528. * @returns Events to raise.
  9529. */
  9530. function syncTreeApplyListenComplete(syncTree, path) {
  9531. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9532. }
  9533. /**
  9534. * Apply a listen complete for a tagged query
  9535. *
  9536. * @returns Events to raise.
  9537. */
  9538. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9539. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9540. if (queryKey) {
  9541. const r = syncTreeParseQueryKey_(queryKey);
  9542. const queryPath = r.path, queryId = r.queryId;
  9543. const relativePath = newRelativePath(queryPath, path);
  9544. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9545. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9546. }
  9547. else {
  9548. // We've already removed the query. No big deal, ignore the update
  9549. return [];
  9550. }
  9551. }
  9552. /**
  9553. * Remove event callback(s).
  9554. *
  9555. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9556. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9557. *
  9558. * @param eventRegistration - If null, all callbacks are removed.
  9559. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9560. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9561. * deduping needs to take place. This flag allows toggling of that behavior
  9562. * @returns Cancel events, if cancelError was provided.
  9563. */
  9564. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9565. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9566. const path = query._path;
  9567. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9568. let cancelEvents = [];
  9569. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9570. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9571. // not loadsAllData().
  9572. if (maybeSyncPoint &&
  9573. (query._queryIdentifier === 'default' ||
  9574. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9575. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9576. if (syncPointIsEmpty(maybeSyncPoint)) {
  9577. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9578. }
  9579. const removed = removedAndEvents.removed;
  9580. cancelEvents = removedAndEvents.events;
  9581. if (!skipListenerDedup) {
  9582. /**
  9583. * We may have just removed one of many listeners and can short-circuit this whole process
  9584. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9585. * properly set up.
  9586. */
  9587. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9588. // queryId === 'default'
  9589. const removingDefault = -1 !==
  9590. removed.findIndex(query => {
  9591. return query._queryParams.loadsAllData();
  9592. });
  9593. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9594. if (removingDefault && !covered) {
  9595. const subtree = syncTree.syncPointTree_.subtree(path);
  9596. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9597. // removal
  9598. if (!subtree.isEmpty()) {
  9599. // We need to fold over our subtree and collect the listeners to send
  9600. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9601. // Ok, we've collected all the listens we need. Set them up.
  9602. for (let i = 0; i < newViews.length; ++i) {
  9603. const view = newViews[i], newQuery = view.query;
  9604. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9605. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9606. }
  9607. }
  9608. // Otherwise there's nothing below us, so nothing we need to start listening on
  9609. }
  9610. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9611. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9612. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9613. if (!covered && removed.length > 0 && !cancelError) {
  9614. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9615. // default. Otherwise, we need to iterate through and cancel each individual query
  9616. if (removingDefault) {
  9617. // We don't tag default listeners
  9618. const defaultTag = null;
  9619. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9620. }
  9621. else {
  9622. removed.forEach((queryToRemove) => {
  9623. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9624. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9625. });
  9626. }
  9627. }
  9628. }
  9629. // Now, clear all of the tags we're tracking for the removed listens
  9630. syncTreeRemoveTags_(syncTree, removed);
  9631. }
  9632. return cancelEvents;
  9633. }
  9634. /**
  9635. * Apply new server data for the specified tagged query.
  9636. *
  9637. * @returns Events to raise.
  9638. */
  9639. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9640. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9641. if (queryKey != null) {
  9642. const r = syncTreeParseQueryKey_(queryKey);
  9643. const queryPath = r.path, queryId = r.queryId;
  9644. const relativePath = newRelativePath(queryPath, path);
  9645. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9646. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9647. }
  9648. else {
  9649. // Query must have been removed already
  9650. return [];
  9651. }
  9652. }
  9653. /**
  9654. * Apply server data to be merged in for the specified tagged query.
  9655. *
  9656. * @returns Events to raise.
  9657. */
  9658. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9659. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9660. if (queryKey) {
  9661. const r = syncTreeParseQueryKey_(queryKey);
  9662. const queryPath = r.path, queryId = r.queryId;
  9663. const relativePath = newRelativePath(queryPath, path);
  9664. const changeTree = ImmutableTree.fromObject(changedChildren);
  9665. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9666. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9667. }
  9668. else {
  9669. // We've already removed the query. No big deal, ignore the update
  9670. return [];
  9671. }
  9672. }
  9673. /**
  9674. * Add an event callback for the specified query.
  9675. *
  9676. * @returns Events to raise.
  9677. */
  9678. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9679. const path = query._path;
  9680. let serverCache = null;
  9681. let foundAncestorDefaultView = false;
  9682. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9683. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9684. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9685. const relativePath = newRelativePath(pathToSyncPoint, path);
  9686. serverCache =
  9687. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9688. foundAncestorDefaultView =
  9689. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9690. });
  9691. let syncPoint = syncTree.syncPointTree_.get(path);
  9692. if (!syncPoint) {
  9693. syncPoint = new SyncPoint();
  9694. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9695. }
  9696. else {
  9697. foundAncestorDefaultView =
  9698. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9699. serverCache =
  9700. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9701. }
  9702. let serverCacheComplete;
  9703. if (serverCache != null) {
  9704. serverCacheComplete = true;
  9705. }
  9706. else {
  9707. serverCacheComplete = false;
  9708. serverCache = ChildrenNode.EMPTY_NODE;
  9709. const subtree = syncTree.syncPointTree_.subtree(path);
  9710. subtree.foreachChild((childName, childSyncPoint) => {
  9711. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9712. if (completeCache) {
  9713. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9714. }
  9715. });
  9716. }
  9717. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9718. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9719. // We need to track a tag for this query
  9720. const queryKey = syncTreeMakeQueryKey_(query);
  9721. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9722. const tag = syncTreeGetNextQueryTag_();
  9723. syncTree.queryToTagMap.set(queryKey, tag);
  9724. syncTree.tagToQueryMap.set(tag, queryKey);
  9725. }
  9726. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9727. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9728. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9729. const view = syncPointViewForQuery(syncPoint, query);
  9730. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9731. }
  9732. return events;
  9733. }
  9734. /**
  9735. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9736. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9737. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9738. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9739. *
  9740. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9741. *
  9742. * @param path - The path to the data we want
  9743. * @param writeIdsToExclude - A specific set to be excluded
  9744. */
  9745. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9746. const includeHiddenSets = true;
  9747. const writeTree = syncTree.pendingWriteTree_;
  9748. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9749. const relativePath = newRelativePath(pathSoFar, path);
  9750. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9751. if (serverCache) {
  9752. return serverCache;
  9753. }
  9754. });
  9755. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9756. }
  9757. function syncTreeGetServerValue(syncTree, query) {
  9758. const path = query._path;
  9759. let serverCache = null;
  9760. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9761. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9762. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9763. const relativePath = newRelativePath(pathToSyncPoint, path);
  9764. serverCache =
  9765. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9766. });
  9767. let syncPoint = syncTree.syncPointTree_.get(path);
  9768. if (!syncPoint) {
  9769. syncPoint = new SyncPoint();
  9770. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9771. }
  9772. else {
  9773. serverCache =
  9774. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9775. }
  9776. const serverCacheComplete = serverCache != null;
  9777. const serverCacheNode = serverCacheComplete
  9778. ? new CacheNode(serverCache, true, false)
  9779. : null;
  9780. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9781. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9782. return viewGetCompleteNode(view);
  9783. }
  9784. /**
  9785. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9786. *
  9787. * NOTES:
  9788. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9789. *
  9790. * - We call applyOperation() on each SyncPoint passing three things:
  9791. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9792. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9793. * 3. A snapshot Node with cached server data, if we have it.
  9794. *
  9795. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9796. */
  9797. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9798. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9799. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9800. }
  9801. /**
  9802. * Recursive helper for applyOperationToSyncPoints_
  9803. */
  9804. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9805. if (pathIsEmpty(operation.path)) {
  9806. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9807. }
  9808. else {
  9809. const syncPoint = syncPointTree.get(newEmptyPath());
  9810. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9811. if (serverCache == null && syncPoint != null) {
  9812. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9813. }
  9814. let events = [];
  9815. const childName = pathGetFront(operation.path);
  9816. const childOperation = operation.operationForChild(childName);
  9817. const childTree = syncPointTree.children.get(childName);
  9818. if (childTree && childOperation) {
  9819. const childServerCache = serverCache
  9820. ? serverCache.getImmediateChild(childName)
  9821. : null;
  9822. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9823. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9824. }
  9825. if (syncPoint) {
  9826. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9827. }
  9828. return events;
  9829. }
  9830. }
  9831. /**
  9832. * Recursive helper for applyOperationToSyncPoints_
  9833. */
  9834. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9835. const syncPoint = syncPointTree.get(newEmptyPath());
  9836. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9837. if (serverCache == null && syncPoint != null) {
  9838. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9839. }
  9840. let events = [];
  9841. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9842. const childServerCache = serverCache
  9843. ? serverCache.getImmediateChild(childName)
  9844. : null;
  9845. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9846. const childOperation = operation.operationForChild(childName);
  9847. if (childOperation) {
  9848. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9849. }
  9850. });
  9851. if (syncPoint) {
  9852. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9853. }
  9854. return events;
  9855. }
  9856. function syncTreeCreateListenerForView_(syncTree, view) {
  9857. const query = view.query;
  9858. const tag = syncTreeTagForQuery(syncTree, query);
  9859. return {
  9860. hashFn: () => {
  9861. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9862. return cache.hash();
  9863. },
  9864. onComplete: (status) => {
  9865. if (status === 'ok') {
  9866. if (tag) {
  9867. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9868. }
  9869. else {
  9870. return syncTreeApplyListenComplete(syncTree, query._path);
  9871. }
  9872. }
  9873. else {
  9874. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9875. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9876. const error = errorForServerCode(status, query);
  9877. return syncTreeRemoveEventRegistration(syncTree, query,
  9878. /*eventRegistration*/ null, error);
  9879. }
  9880. }
  9881. };
  9882. }
  9883. /**
  9884. * Return the tag associated with the given query.
  9885. */
  9886. function syncTreeTagForQuery(syncTree, query) {
  9887. const queryKey = syncTreeMakeQueryKey_(query);
  9888. return syncTree.queryToTagMap.get(queryKey);
  9889. }
  9890. /**
  9891. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9892. */
  9893. function syncTreeMakeQueryKey_(query) {
  9894. return query._path.toString() + '$' + query._queryIdentifier;
  9895. }
  9896. /**
  9897. * Return the query associated with the given tag, if we have one
  9898. */
  9899. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9900. return syncTree.tagToQueryMap.get(tag);
  9901. }
  9902. /**
  9903. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9904. */
  9905. function syncTreeParseQueryKey_(queryKey) {
  9906. const splitIndex = queryKey.indexOf('$');
  9907. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9908. return {
  9909. queryId: queryKey.substr(splitIndex + 1),
  9910. path: new Path(queryKey.substr(0, splitIndex))
  9911. };
  9912. }
  9913. /**
  9914. * A helper method to apply tagged operations
  9915. */
  9916. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9917. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9918. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9919. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9920. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9921. }
  9922. /**
  9923. * This collapses multiple unfiltered views into a single view, since we only need a single
  9924. * listener for them.
  9925. */
  9926. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9927. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9928. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9929. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9930. return [completeView];
  9931. }
  9932. else {
  9933. // No complete view here, flatten any deeper listens into an array
  9934. let views = [];
  9935. if (maybeChildSyncPoint) {
  9936. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9937. }
  9938. each(childMap, (_key, childViews) => {
  9939. views = views.concat(childViews);
  9940. });
  9941. return views;
  9942. }
  9943. });
  9944. }
  9945. /**
  9946. * Normalizes a query to a query we send the server for listening
  9947. *
  9948. * @returns The normalized query
  9949. */
  9950. function syncTreeQueryForListening_(query) {
  9951. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9952. // We treat queries that load all data as default queries
  9953. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9954. // from Query
  9955. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9956. }
  9957. else {
  9958. return query;
  9959. }
  9960. }
  9961. function syncTreeRemoveTags_(syncTree, queries) {
  9962. for (let j = 0; j < queries.length; ++j) {
  9963. const removedQuery = queries[j];
  9964. if (!removedQuery._queryParams.loadsAllData()) {
  9965. // We should have a tag for this
  9966. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9967. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9968. syncTree.queryToTagMap.delete(removedQueryKey);
  9969. syncTree.tagToQueryMap.delete(removedQueryTag);
  9970. }
  9971. }
  9972. }
  9973. /**
  9974. * Static accessor for query tags.
  9975. */
  9976. function syncTreeGetNextQueryTag_() {
  9977. return syncTreeNextQueryTag_++;
  9978. }
  9979. /**
  9980. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9981. *
  9982. * @returns This method can return events to support synchronous data sources
  9983. */
  9984. function syncTreeSetupListener_(syncTree, query, view) {
  9985. const path = query._path;
  9986. const tag = syncTreeTagForQuery(syncTree, query);
  9987. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9988. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9989. const subtree = syncTree.syncPointTree_.subtree(path);
  9990. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  9991. // may need to shadow other listens as well.
  9992. if (tag) {
  9993. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  9994. }
  9995. else {
  9996. // Shadow everything at or below this location, this is a default listener.
  9997. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9998. if (!pathIsEmpty(relativePath) &&
  9999. maybeChildSyncPoint &&
  10000. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10001. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10002. }
  10003. else {
  10004. // No default listener here, flatten any deeper queries into an array
  10005. let queries = [];
  10006. if (maybeChildSyncPoint) {
  10007. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10008. }
  10009. each(childMap, (_key, childQueries) => {
  10010. queries = queries.concat(childQueries);
  10011. });
  10012. return queries;
  10013. }
  10014. });
  10015. for (let i = 0; i < queriesToStop.length; ++i) {
  10016. const queryToStop = queriesToStop[i];
  10017. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10018. }
  10019. }
  10020. return events;
  10021. }
  10022. /**
  10023. * @license
  10024. * Copyright 2017 Google LLC
  10025. *
  10026. * Licensed under the Apache License, Version 2.0 (the "License");
  10027. * you may not use this file except in compliance with the License.
  10028. * You may obtain a copy of the License at
  10029. *
  10030. * http://www.apache.org/licenses/LICENSE-2.0
  10031. *
  10032. * Unless required by applicable law or agreed to in writing, software
  10033. * distributed under the License is distributed on an "AS IS" BASIS,
  10034. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10035. * See the License for the specific language governing permissions and
  10036. * limitations under the License.
  10037. */
  10038. class ExistingValueProvider {
  10039. constructor(node_) {
  10040. this.node_ = node_;
  10041. }
  10042. getImmediateChild(childName) {
  10043. const child = this.node_.getImmediateChild(childName);
  10044. return new ExistingValueProvider(child);
  10045. }
  10046. node() {
  10047. return this.node_;
  10048. }
  10049. }
  10050. class DeferredValueProvider {
  10051. constructor(syncTree, path) {
  10052. this.syncTree_ = syncTree;
  10053. this.path_ = path;
  10054. }
  10055. getImmediateChild(childName) {
  10056. const childPath = pathChild(this.path_, childName);
  10057. return new DeferredValueProvider(this.syncTree_, childPath);
  10058. }
  10059. node() {
  10060. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10061. }
  10062. }
  10063. /**
  10064. * Generate placeholders for deferred values.
  10065. */
  10066. const generateWithValues = function (values) {
  10067. values = values || {};
  10068. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10069. return values;
  10070. };
  10071. /**
  10072. * Value to use when firing local events. When writing server values, fire
  10073. * local events with an approximate value, otherwise return value as-is.
  10074. */
  10075. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10076. if (!value || typeof value !== 'object') {
  10077. return value;
  10078. }
  10079. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10080. if (typeof value['.sv'] === 'string') {
  10081. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10082. }
  10083. else if (typeof value['.sv'] === 'object') {
  10084. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10085. }
  10086. else {
  10087. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10088. }
  10089. };
  10090. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10091. switch (op) {
  10092. case 'timestamp':
  10093. return serverValues['timestamp'];
  10094. default:
  10095. assert(false, 'Unexpected server value: ' + op);
  10096. }
  10097. };
  10098. const resolveComplexDeferredValue = function (op, existing, unused) {
  10099. if (!op.hasOwnProperty('increment')) {
  10100. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10101. }
  10102. const delta = op['increment'];
  10103. if (typeof delta !== 'number') {
  10104. assert(false, 'Unexpected increment value: ' + delta);
  10105. }
  10106. const existingNode = existing.node();
  10107. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10108. // Incrementing a non-number sets the value to the incremented amount
  10109. if (!existingNode.isLeafNode()) {
  10110. return delta;
  10111. }
  10112. const leaf = existingNode;
  10113. const existingVal = leaf.getValue();
  10114. if (typeof existingVal !== 'number') {
  10115. return delta;
  10116. }
  10117. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10118. return existingVal + delta;
  10119. };
  10120. /**
  10121. * Recursively replace all deferred values and priorities in the tree with the
  10122. * specified generated replacement values.
  10123. * @param path - path to which write is relative
  10124. * @param node - new data written at path
  10125. * @param syncTree - current data
  10126. */
  10127. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10128. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10129. };
  10130. /**
  10131. * Recursively replace all deferred values and priorities in the node with the
  10132. * specified generated replacement values. If there are no server values in the node,
  10133. * it'll be returned as-is.
  10134. */
  10135. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10136. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10137. };
  10138. function resolveDeferredValue(node, existingVal, serverValues) {
  10139. const rawPri = node.getPriority().val();
  10140. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10141. let newNode;
  10142. if (node.isLeafNode()) {
  10143. const leafNode = node;
  10144. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10145. if (value !== leafNode.getValue() ||
  10146. priority !== leafNode.getPriority().val()) {
  10147. return new LeafNode(value, nodeFromJSON(priority));
  10148. }
  10149. else {
  10150. return node;
  10151. }
  10152. }
  10153. else {
  10154. const childrenNode = node;
  10155. newNode = childrenNode;
  10156. if (priority !== childrenNode.getPriority().val()) {
  10157. newNode = newNode.updatePriority(new LeafNode(priority));
  10158. }
  10159. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10160. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10161. if (newChildNode !== childNode) {
  10162. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10163. }
  10164. });
  10165. return newNode;
  10166. }
  10167. }
  10168. /**
  10169. * @license
  10170. * Copyright 2017 Google LLC
  10171. *
  10172. * Licensed under the Apache License, Version 2.0 (the "License");
  10173. * you may not use this file except in compliance with the License.
  10174. * You may obtain a copy of the License at
  10175. *
  10176. * http://www.apache.org/licenses/LICENSE-2.0
  10177. *
  10178. * Unless required by applicable law or agreed to in writing, software
  10179. * distributed under the License is distributed on an "AS IS" BASIS,
  10180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10181. * See the License for the specific language governing permissions and
  10182. * limitations under the License.
  10183. */
  10184. /**
  10185. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10186. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10187. * children.
  10188. */
  10189. class Tree {
  10190. /**
  10191. * @param name - Optional name of the node.
  10192. * @param parent - Optional parent node.
  10193. * @param node - Optional node to wrap.
  10194. */
  10195. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10196. this.name = name;
  10197. this.parent = parent;
  10198. this.node = node;
  10199. }
  10200. }
  10201. /**
  10202. * Returns a sub-Tree for the given path.
  10203. *
  10204. * @param pathObj - Path to look up.
  10205. * @returns Tree for path.
  10206. */
  10207. function treeSubTree(tree, pathObj) {
  10208. // TODO: Require pathObj to be Path?
  10209. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10210. let child = tree, next = pathGetFront(path);
  10211. while (next !== null) {
  10212. const childNode = safeGet(child.node.children, next) || {
  10213. children: {},
  10214. childCount: 0
  10215. };
  10216. child = new Tree(next, child, childNode);
  10217. path = pathPopFront(path);
  10218. next = pathGetFront(path);
  10219. }
  10220. return child;
  10221. }
  10222. /**
  10223. * Returns the data associated with this tree node.
  10224. *
  10225. * @returns The data or null if no data exists.
  10226. */
  10227. function treeGetValue(tree) {
  10228. return tree.node.value;
  10229. }
  10230. /**
  10231. * Sets data to this tree node.
  10232. *
  10233. * @param value - Value to set.
  10234. */
  10235. function treeSetValue(tree, value) {
  10236. tree.node.value = value;
  10237. treeUpdateParents(tree);
  10238. }
  10239. /**
  10240. * @returns Whether the tree has any children.
  10241. */
  10242. function treeHasChildren(tree) {
  10243. return tree.node.childCount > 0;
  10244. }
  10245. /**
  10246. * @returns Whethe rthe tree is empty (no value or children).
  10247. */
  10248. function treeIsEmpty(tree) {
  10249. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10250. }
  10251. /**
  10252. * Calls action for each child of this tree node.
  10253. *
  10254. * @param action - Action to be called for each child.
  10255. */
  10256. function treeForEachChild(tree, action) {
  10257. each(tree.node.children, (child, childTree) => {
  10258. action(new Tree(child, tree, childTree));
  10259. });
  10260. }
  10261. /**
  10262. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10263. *
  10264. * @param action - Action to be called for each child.
  10265. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10266. * false.
  10267. * @param childrenFirst - Whether to call action on children before calling it on
  10268. * parent.
  10269. */
  10270. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10271. if (includeSelf && !childrenFirst) {
  10272. action(tree);
  10273. }
  10274. treeForEachChild(tree, child => {
  10275. treeForEachDescendant(child, action, true, childrenFirst);
  10276. });
  10277. if (includeSelf && childrenFirst) {
  10278. action(tree);
  10279. }
  10280. }
  10281. /**
  10282. * Calls action on each ancestor node.
  10283. *
  10284. * @param action - Action to be called on each parent; return
  10285. * true to abort.
  10286. * @param includeSelf - Whether to call action on this node as well.
  10287. * @returns true if the action callback returned true.
  10288. */
  10289. function treeForEachAncestor(tree, action, includeSelf) {
  10290. let node = includeSelf ? tree : tree.parent;
  10291. while (node !== null) {
  10292. if (action(node)) {
  10293. return true;
  10294. }
  10295. node = node.parent;
  10296. }
  10297. return false;
  10298. }
  10299. /**
  10300. * @returns The path of this tree node, as a Path.
  10301. */
  10302. function treeGetPath(tree) {
  10303. return new Path(tree.parent === null
  10304. ? tree.name
  10305. : treeGetPath(tree.parent) + '/' + tree.name);
  10306. }
  10307. /**
  10308. * Adds or removes this child from its parent based on whether it's empty or not.
  10309. */
  10310. function treeUpdateParents(tree) {
  10311. if (tree.parent !== null) {
  10312. treeUpdateChild(tree.parent, tree.name, tree);
  10313. }
  10314. }
  10315. /**
  10316. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10317. *
  10318. * @param childName - The name of the child to update.
  10319. * @param child - The child to update.
  10320. */
  10321. function treeUpdateChild(tree, childName, child) {
  10322. const childEmpty = treeIsEmpty(child);
  10323. const childExists = contains(tree.node.children, childName);
  10324. if (childEmpty && childExists) {
  10325. delete tree.node.children[childName];
  10326. tree.node.childCount--;
  10327. treeUpdateParents(tree);
  10328. }
  10329. else if (!childEmpty && !childExists) {
  10330. tree.node.children[childName] = child.node;
  10331. tree.node.childCount++;
  10332. treeUpdateParents(tree);
  10333. }
  10334. }
  10335. /**
  10336. * @license
  10337. * Copyright 2017 Google LLC
  10338. *
  10339. * Licensed under the Apache License, Version 2.0 (the "License");
  10340. * you may not use this file except in compliance with the License.
  10341. * You may obtain a copy of the License at
  10342. *
  10343. * http://www.apache.org/licenses/LICENSE-2.0
  10344. *
  10345. * Unless required by applicable law or agreed to in writing, software
  10346. * distributed under the License is distributed on an "AS IS" BASIS,
  10347. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10348. * See the License for the specific language governing permissions and
  10349. * limitations under the License.
  10350. */
  10351. /**
  10352. * True for invalid Firebase keys
  10353. */
  10354. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10355. /**
  10356. * True for invalid Firebase paths.
  10357. * Allows '/' in paths.
  10358. */
  10359. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10360. /**
  10361. * Maximum number of characters to allow in leaf value
  10362. */
  10363. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10364. const isValidKey = function (key) {
  10365. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10366. };
  10367. const isValidPathString = function (pathString) {
  10368. return (typeof pathString === 'string' &&
  10369. pathString.length !== 0 &&
  10370. !INVALID_PATH_REGEX_.test(pathString));
  10371. };
  10372. const isValidRootPathString = function (pathString) {
  10373. if (pathString) {
  10374. // Allow '/.info/' at the beginning.
  10375. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10376. }
  10377. return isValidPathString(pathString);
  10378. };
  10379. const isValidPriority = function (priority) {
  10380. return (priority === null ||
  10381. typeof priority === 'string' ||
  10382. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10383. (priority &&
  10384. typeof priority === 'object' &&
  10385. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10386. contains(priority, '.sv')));
  10387. };
  10388. /**
  10389. * Pre-validate a datum passed as an argument to Firebase function.
  10390. */
  10391. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10392. if (optional && value === undefined) {
  10393. return;
  10394. }
  10395. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10396. };
  10397. /**
  10398. * Validate a data object client-side before sending to server.
  10399. */
  10400. const validateFirebaseData = function (errorPrefix, data, path_) {
  10401. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10402. if (data === undefined) {
  10403. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10404. }
  10405. if (typeof data === 'function') {
  10406. throw new Error(errorPrefix +
  10407. 'contains a function ' +
  10408. validationPathToErrorString(path) +
  10409. ' with contents = ' +
  10410. data.toString());
  10411. }
  10412. if (isInvalidJSONNumber(data)) {
  10413. throw new Error(errorPrefix +
  10414. 'contains ' +
  10415. data.toString() +
  10416. ' ' +
  10417. validationPathToErrorString(path));
  10418. }
  10419. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10420. if (typeof data === 'string' &&
  10421. data.length > MAX_LEAF_SIZE_ / 3 &&
  10422. stringLength(data) > MAX_LEAF_SIZE_) {
  10423. throw new Error(errorPrefix +
  10424. 'contains a string greater than ' +
  10425. MAX_LEAF_SIZE_ +
  10426. ' utf8 bytes ' +
  10427. validationPathToErrorString(path) +
  10428. " ('" +
  10429. data.substring(0, 50) +
  10430. "...')");
  10431. }
  10432. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10433. // to save extra walking of large objects.
  10434. if (data && typeof data === 'object') {
  10435. let hasDotValue = false;
  10436. let hasActualChild = false;
  10437. each(data, (key, value) => {
  10438. if (key === '.value') {
  10439. hasDotValue = true;
  10440. }
  10441. else if (key !== '.priority' && key !== '.sv') {
  10442. hasActualChild = true;
  10443. if (!isValidKey(key)) {
  10444. throw new Error(errorPrefix +
  10445. ' contains an invalid key (' +
  10446. key +
  10447. ') ' +
  10448. validationPathToErrorString(path) +
  10449. '. Keys must be non-empty strings ' +
  10450. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10451. }
  10452. }
  10453. validationPathPush(path, key);
  10454. validateFirebaseData(errorPrefix, value, path);
  10455. validationPathPop(path);
  10456. });
  10457. if (hasDotValue && hasActualChild) {
  10458. throw new Error(errorPrefix +
  10459. ' contains ".value" child ' +
  10460. validationPathToErrorString(path) +
  10461. ' in addition to actual children.');
  10462. }
  10463. }
  10464. };
  10465. /**
  10466. * Pre-validate paths passed in the firebase function.
  10467. */
  10468. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10469. let i, curPath;
  10470. for (i = 0; i < mergePaths.length; i++) {
  10471. curPath = mergePaths[i];
  10472. const keys = pathSlice(curPath);
  10473. for (let j = 0; j < keys.length; j++) {
  10474. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10475. else if (!isValidKey(keys[j])) {
  10476. throw new Error(errorPrefix +
  10477. 'contains an invalid key (' +
  10478. keys[j] +
  10479. ') in path ' +
  10480. curPath.toString() +
  10481. '. Keys must be non-empty strings ' +
  10482. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10483. }
  10484. }
  10485. }
  10486. // Check that update keys are not descendants of each other.
  10487. // We rely on the property that sorting guarantees that ancestors come
  10488. // right before descendants.
  10489. mergePaths.sort(pathCompare);
  10490. let prevPath = null;
  10491. for (i = 0; i < mergePaths.length; i++) {
  10492. curPath = mergePaths[i];
  10493. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10494. throw new Error(errorPrefix +
  10495. 'contains a path ' +
  10496. prevPath.toString() +
  10497. ' that is ancestor of another path ' +
  10498. curPath.toString());
  10499. }
  10500. prevPath = curPath;
  10501. }
  10502. };
  10503. /**
  10504. * pre-validate an object passed as an argument to firebase function (
  10505. * must be an object - e.g. for firebase.update()).
  10506. */
  10507. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10508. if (optional && data === undefined) {
  10509. return;
  10510. }
  10511. const errorPrefix$1 = errorPrefix(fnName, 'values');
  10512. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10513. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10514. }
  10515. const mergePaths = [];
  10516. each(data, (key, value) => {
  10517. const curPath = new Path(key);
  10518. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10519. if (pathGetBack(curPath) === '.priority') {
  10520. if (!isValidPriority(value)) {
  10521. throw new Error(errorPrefix$1 +
  10522. "contains an invalid value for '" +
  10523. curPath.toString() +
  10524. "', which must be a valid " +
  10525. 'Firebase priority (a string, finite number, server value, or null).');
  10526. }
  10527. }
  10528. mergePaths.push(curPath);
  10529. });
  10530. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10531. };
  10532. const validatePriority = function (fnName, priority, optional) {
  10533. if (optional && priority === undefined) {
  10534. return;
  10535. }
  10536. if (isInvalidJSONNumber(priority)) {
  10537. throw new Error(errorPrefix(fnName, 'priority') +
  10538. 'is ' +
  10539. priority.toString() +
  10540. ', but must be a valid Firebase priority (a string, finite number, ' +
  10541. 'server value, or null).');
  10542. }
  10543. // Special case to allow importing data with a .sv.
  10544. if (!isValidPriority(priority)) {
  10545. throw new Error(errorPrefix(fnName, 'priority') +
  10546. 'must be a valid Firebase priority ' +
  10547. '(a string, finite number, server value, or null).');
  10548. }
  10549. };
  10550. const validateKey = function (fnName, argumentName, key, optional) {
  10551. if (optional && key === undefined) {
  10552. return;
  10553. }
  10554. if (!isValidKey(key)) {
  10555. throw new Error(errorPrefix(fnName, argumentName) +
  10556. 'was an invalid key = "' +
  10557. key +
  10558. '". Firebase keys must be non-empty strings and ' +
  10559. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10560. }
  10561. };
  10562. /**
  10563. * @internal
  10564. */
  10565. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10566. if (optional && pathString === undefined) {
  10567. return;
  10568. }
  10569. if (!isValidPathString(pathString)) {
  10570. throw new Error(errorPrefix(fnName, argumentName) +
  10571. 'was an invalid path = "' +
  10572. pathString +
  10573. '". Paths must be non-empty strings and ' +
  10574. 'can\'t contain ".", "#", "$", "[", or "]"');
  10575. }
  10576. };
  10577. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10578. if (pathString) {
  10579. // Allow '/.info/' at the beginning.
  10580. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10581. }
  10582. validatePathString(fnName, argumentName, pathString, optional);
  10583. };
  10584. /**
  10585. * @internal
  10586. */
  10587. const validateWritablePath = function (fnName, path) {
  10588. if (pathGetFront(path) === '.info') {
  10589. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10590. }
  10591. };
  10592. const validateUrl = function (fnName, parsedUrl) {
  10593. // TODO = Validate server better.
  10594. const pathString = parsedUrl.path.toString();
  10595. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10596. parsedUrl.repoInfo.host.length === 0 ||
  10597. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10598. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10599. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10600. throw new Error(errorPrefix(fnName, 'url') +
  10601. 'must be a valid firebase URL and ' +
  10602. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10603. }
  10604. };
  10605. /**
  10606. * @license
  10607. * Copyright 2017 Google LLC
  10608. *
  10609. * Licensed under the Apache License, Version 2.0 (the "License");
  10610. * you may not use this file except in compliance with the License.
  10611. * You may obtain a copy of the License at
  10612. *
  10613. * http://www.apache.org/licenses/LICENSE-2.0
  10614. *
  10615. * Unless required by applicable law or agreed to in writing, software
  10616. * distributed under the License is distributed on an "AS IS" BASIS,
  10617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10618. * See the License for the specific language governing permissions and
  10619. * limitations under the License.
  10620. */
  10621. /**
  10622. * The event queue serves a few purposes:
  10623. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10624. * events being queued.
  10625. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10626. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10627. * left off, ensuring that the events are still raised synchronously and in order.
  10628. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10629. * events are raised synchronously.
  10630. *
  10631. * NOTE: This can all go away if/when we move to async events.
  10632. *
  10633. */
  10634. class EventQueue {
  10635. constructor() {
  10636. this.eventLists_ = [];
  10637. /**
  10638. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10639. */
  10640. this.recursionDepth_ = 0;
  10641. }
  10642. }
  10643. /**
  10644. * @param eventDataList - The new events to queue.
  10645. */
  10646. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10647. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10648. let currList = null;
  10649. for (let i = 0; i < eventDataList.length; i++) {
  10650. const data = eventDataList[i];
  10651. const path = data.getPath();
  10652. if (currList !== null && !pathEquals(path, currList.path)) {
  10653. eventQueue.eventLists_.push(currList);
  10654. currList = null;
  10655. }
  10656. if (currList === null) {
  10657. currList = { events: [], path };
  10658. }
  10659. currList.events.push(data);
  10660. }
  10661. if (currList) {
  10662. eventQueue.eventLists_.push(currList);
  10663. }
  10664. }
  10665. /**
  10666. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10667. * for the specified path.
  10668. *
  10669. * It is assumed that the new events are all for the specified path.
  10670. *
  10671. * @param path - The path to raise events for.
  10672. * @param eventDataList - The new events to raise.
  10673. */
  10674. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10675. eventQueueQueueEvents(eventQueue, eventDataList);
  10676. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10677. }
  10678. /**
  10679. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10680. * locations related to the specified change path (i.e. all ancestors and descendants).
  10681. *
  10682. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10683. *
  10684. * @param changedPath - The path to raise events for.
  10685. * @param eventDataList - The events to raise
  10686. */
  10687. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10688. eventQueueQueueEvents(eventQueue, eventDataList);
  10689. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10690. pathContains(changedPath, eventPath));
  10691. }
  10692. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10693. eventQueue.recursionDepth_++;
  10694. let sentAll = true;
  10695. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10696. const eventList = eventQueue.eventLists_[i];
  10697. if (eventList) {
  10698. const eventPath = eventList.path;
  10699. if (predicate(eventPath)) {
  10700. eventListRaise(eventQueue.eventLists_[i]);
  10701. eventQueue.eventLists_[i] = null;
  10702. }
  10703. else {
  10704. sentAll = false;
  10705. }
  10706. }
  10707. }
  10708. if (sentAll) {
  10709. eventQueue.eventLists_ = [];
  10710. }
  10711. eventQueue.recursionDepth_--;
  10712. }
  10713. /**
  10714. * Iterates through the list and raises each event
  10715. */
  10716. function eventListRaise(eventList) {
  10717. for (let i = 0; i < eventList.events.length; i++) {
  10718. const eventData = eventList.events[i];
  10719. if (eventData !== null) {
  10720. eventList.events[i] = null;
  10721. const eventFn = eventData.getEventRunner();
  10722. if (logger) {
  10723. log('event: ' + eventData.toString());
  10724. }
  10725. exceptionGuard(eventFn);
  10726. }
  10727. }
  10728. }
  10729. /**
  10730. * @license
  10731. * Copyright 2017 Google LLC
  10732. *
  10733. * Licensed under the Apache License, Version 2.0 (the "License");
  10734. * you may not use this file except in compliance with the License.
  10735. * You may obtain a copy of the License at
  10736. *
  10737. * http://www.apache.org/licenses/LICENSE-2.0
  10738. *
  10739. * Unless required by applicable law or agreed to in writing, software
  10740. * distributed under the License is distributed on an "AS IS" BASIS,
  10741. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10742. * See the License for the specific language governing permissions and
  10743. * limitations under the License.
  10744. */
  10745. const INTERRUPT_REASON = 'repo_interrupt';
  10746. /**
  10747. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10748. * things this ensure that if there's ever a bug causing a mismatch between
  10749. * client / server hashes for some data, we won't retry indefinitely.
  10750. */
  10751. const MAX_TRANSACTION_RETRIES = 25;
  10752. /**
  10753. * A connection to a single data repository.
  10754. */
  10755. class Repo {
  10756. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10757. this.repoInfo_ = repoInfo_;
  10758. this.forceRestClient_ = forceRestClient_;
  10759. this.authTokenProvider_ = authTokenProvider_;
  10760. this.appCheckProvider_ = appCheckProvider_;
  10761. this.dataUpdateCount = 0;
  10762. this.statsListener_ = null;
  10763. this.eventQueue_ = new EventQueue();
  10764. this.nextWriteId_ = 1;
  10765. this.interceptServerDataCallback_ = null;
  10766. /** A list of data pieces and paths to be set when this client disconnects. */
  10767. this.onDisconnect_ = newSparseSnapshotTree();
  10768. /** Stores queues of outstanding transactions for Firebase locations. */
  10769. this.transactionQueueTree_ = new Tree();
  10770. // TODO: This should be @private but it's used by test_access.js and internal.js
  10771. this.persistentConnection_ = null;
  10772. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10773. this.key = this.repoInfo_.toURLString();
  10774. }
  10775. /**
  10776. * @returns The URL corresponding to the root of this Firebase.
  10777. */
  10778. toString() {
  10779. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10780. }
  10781. }
  10782. function repoStart(repo, appId, authOverride) {
  10783. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10784. if (repo.forceRestClient_ || beingCrawled()) {
  10785. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10786. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10787. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10788. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10789. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10790. }
  10791. else {
  10792. // Validate authOverride
  10793. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10794. if (typeof authOverride !== 'object') {
  10795. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10796. }
  10797. try {
  10798. stringify(authOverride);
  10799. }
  10800. catch (e) {
  10801. throw new Error('Invalid authOverride provided: ' + e);
  10802. }
  10803. }
  10804. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10805. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10806. }, (connectStatus) => {
  10807. repoOnConnectStatus(repo, connectStatus);
  10808. }, (updates) => {
  10809. repoOnServerInfoUpdate(repo, updates);
  10810. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10811. repo.server_ = repo.persistentConnection_;
  10812. }
  10813. repo.authTokenProvider_.addTokenChangeListener(token => {
  10814. repo.server_.refreshAuthToken(token);
  10815. });
  10816. repo.appCheckProvider_.addTokenChangeListener(result => {
  10817. repo.server_.refreshAppCheckToken(result.token);
  10818. });
  10819. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10820. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10821. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10822. // Used for .info.
  10823. repo.infoData_ = new SnapshotHolder();
  10824. repo.infoSyncTree_ = new SyncTree({
  10825. startListening: (query, tag, currentHashFn, onComplete) => {
  10826. let infoEvents = [];
  10827. const node = repo.infoData_.getNode(query._path);
  10828. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10829. // on initial data...
  10830. if (!node.isEmpty()) {
  10831. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10832. setTimeout(() => {
  10833. onComplete('ok');
  10834. }, 0);
  10835. }
  10836. return infoEvents;
  10837. },
  10838. stopListening: () => { }
  10839. });
  10840. repoUpdateInfo(repo, 'connected', false);
  10841. repo.serverSyncTree_ = new SyncTree({
  10842. startListening: (query, tag, currentHashFn, onComplete) => {
  10843. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10844. const events = onComplete(status, data);
  10845. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10846. });
  10847. // No synchronous events for network-backed sync trees
  10848. return [];
  10849. },
  10850. stopListening: (query, tag) => {
  10851. repo.server_.unlisten(query, tag);
  10852. }
  10853. });
  10854. }
  10855. /**
  10856. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10857. */
  10858. function repoServerTime(repo) {
  10859. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10860. const offset = offsetNode.val() || 0;
  10861. return new Date().getTime() + offset;
  10862. }
  10863. /**
  10864. * Generate ServerValues using some variables from the repo object.
  10865. */
  10866. function repoGenerateServerValues(repo) {
  10867. return generateWithValues({
  10868. timestamp: repoServerTime(repo)
  10869. });
  10870. }
  10871. /**
  10872. * Called by realtime when we get new messages from the server.
  10873. */
  10874. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10875. // For testing.
  10876. repo.dataUpdateCount++;
  10877. const path = new Path(pathString);
  10878. data = repo.interceptServerDataCallback_
  10879. ? repo.interceptServerDataCallback_(pathString, data)
  10880. : data;
  10881. let events = [];
  10882. if (tag) {
  10883. if (isMerge) {
  10884. const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
  10885. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10886. }
  10887. else {
  10888. const taggedSnap = nodeFromJSON(data);
  10889. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10890. }
  10891. }
  10892. else if (isMerge) {
  10893. const changedChildren = map(data, (raw) => nodeFromJSON(raw));
  10894. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10895. }
  10896. else {
  10897. const snap = nodeFromJSON(data);
  10898. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10899. }
  10900. let affectedPath = path;
  10901. if (events.length > 0) {
  10902. // Since we have a listener outstanding for each transaction, receiving any events
  10903. // is a proxy for some change having occurred.
  10904. affectedPath = repoRerunTransactions(repo, path);
  10905. }
  10906. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10907. }
  10908. function repoOnConnectStatus(repo, connectStatus) {
  10909. repoUpdateInfo(repo, 'connected', connectStatus);
  10910. if (connectStatus === false) {
  10911. repoRunOnDisconnectEvents(repo);
  10912. }
  10913. }
  10914. function repoOnServerInfoUpdate(repo, updates) {
  10915. each(updates, (key, value) => {
  10916. repoUpdateInfo(repo, key, value);
  10917. });
  10918. }
  10919. function repoUpdateInfo(repo, pathString, value) {
  10920. const path = new Path('/.info/' + pathString);
  10921. const newNode = nodeFromJSON(value);
  10922. repo.infoData_.updateSnapshot(path, newNode);
  10923. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10924. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10925. }
  10926. function repoGetNextWriteId(repo) {
  10927. return repo.nextWriteId_++;
  10928. }
  10929. /**
  10930. * The purpose of `getValue` is to return the latest known value
  10931. * satisfying `query`.
  10932. *
  10933. * This method will first check for in-memory cached values
  10934. * belonging to active listeners. If they are found, such values
  10935. * are considered to be the most up-to-date.
  10936. *
  10937. * If the client is not connected, this method will wait until the
  10938. * repo has established a connection and then request the value for `query`.
  10939. * If the client is not able to retrieve the query result for another reason,
  10940. * it reports an error.
  10941. *
  10942. * @param query - The query to surface a value for.
  10943. */
  10944. function repoGetValue(repo, query, eventRegistration) {
  10945. // Only active queries are cached. There is no persisted cache.
  10946. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10947. if (cached != null) {
  10948. return Promise.resolve(cached);
  10949. }
  10950. return repo.server_.get(query).then(payload => {
  10951. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10952. /**
  10953. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10954. * Add an event registration,
  10955. * Update data at the path,
  10956. * Raise any events,
  10957. * Cleanup the SyncTree
  10958. */
  10959. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10960. let events;
  10961. if (query._queryParams.loadsAllData()) {
  10962. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10963. }
  10964. else {
  10965. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10966. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10967. }
  10968. /*
  10969. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10970. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10971. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10972. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10973. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10974. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10975. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10976. * ensure the corresponding child events will get fired.
  10977. */
  10978. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10979. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10980. return node;
  10981. }, err => {
  10982. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  10983. return Promise.reject(new Error(err));
  10984. });
  10985. }
  10986. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10987. repoLog(repo, 'set', {
  10988. path: path.toString(),
  10989. value: newVal,
  10990. priority: newPriority
  10991. });
  10992. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  10993. // (b) store unresolved paths on JSON parse
  10994. const serverValues = repoGenerateServerValues(repo);
  10995. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  10996. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  10997. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  10998. const writeId = repoGetNextWriteId(repo);
  10999. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11000. eventQueueQueueEvents(repo.eventQueue_, events);
  11001. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11002. const success = status === 'ok';
  11003. if (!success) {
  11004. warn('set at ' + path + ' failed: ' + status);
  11005. }
  11006. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11007. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11008. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11009. });
  11010. const affectedPath = repoAbortTransactions(repo, path);
  11011. repoRerunTransactions(repo, affectedPath);
  11012. // We queued the events above, so just flush the queue here
  11013. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11014. }
  11015. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11016. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11017. // Start with our existing data and merge each child into it.
  11018. let empty = true;
  11019. const serverValues = repoGenerateServerValues(repo);
  11020. const changedChildren = {};
  11021. each(childrenToMerge, (changedKey, changedValue) => {
  11022. empty = false;
  11023. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11024. });
  11025. if (!empty) {
  11026. const writeId = repoGetNextWriteId(repo);
  11027. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11028. eventQueueQueueEvents(repo.eventQueue_, events);
  11029. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11030. const success = status === 'ok';
  11031. if (!success) {
  11032. warn('update at ' + path + ' failed: ' + status);
  11033. }
  11034. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11035. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11036. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11037. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11038. });
  11039. each(childrenToMerge, (changedPath) => {
  11040. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11041. repoRerunTransactions(repo, affectedPath);
  11042. });
  11043. // We queued the events above, so just flush the queue here
  11044. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11045. }
  11046. else {
  11047. log("update() called with empty data. Don't do anything.");
  11048. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11049. }
  11050. }
  11051. /**
  11052. * Applies all of the changes stored up in the onDisconnect_ tree.
  11053. */
  11054. function repoRunOnDisconnectEvents(repo) {
  11055. repoLog(repo, 'onDisconnectEvents');
  11056. const serverValues = repoGenerateServerValues(repo);
  11057. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11058. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11059. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11060. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11061. });
  11062. let events = [];
  11063. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11064. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11065. const affectedPath = repoAbortTransactions(repo, path);
  11066. repoRerunTransactions(repo, affectedPath);
  11067. });
  11068. repo.onDisconnect_ = newSparseSnapshotTree();
  11069. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11070. }
  11071. function repoOnDisconnectCancel(repo, path, onComplete) {
  11072. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11073. if (status === 'ok') {
  11074. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11075. }
  11076. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11077. });
  11078. }
  11079. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11080. const newNode = nodeFromJSON(value);
  11081. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11082. if (status === 'ok') {
  11083. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11084. }
  11085. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11086. });
  11087. }
  11088. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11089. const newNode = nodeFromJSON(value, priority);
  11090. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11091. if (status === 'ok') {
  11092. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11093. }
  11094. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11095. });
  11096. }
  11097. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11098. if (isEmpty(childrenToMerge)) {
  11099. log("onDisconnect().update() called with empty data. Don't do anything.");
  11100. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11101. return;
  11102. }
  11103. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11104. if (status === 'ok') {
  11105. each(childrenToMerge, (childName, childNode) => {
  11106. const newChildNode = nodeFromJSON(childNode);
  11107. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11108. });
  11109. }
  11110. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11111. });
  11112. }
  11113. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11114. let events;
  11115. if (pathGetFront(query._path) === '.info') {
  11116. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11117. }
  11118. else {
  11119. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11120. }
  11121. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11122. }
  11123. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11124. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11125. // a little bit by handling the return values anyways.
  11126. let events;
  11127. if (pathGetFront(query._path) === '.info') {
  11128. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11129. }
  11130. else {
  11131. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11132. }
  11133. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11134. }
  11135. function repoInterrupt(repo) {
  11136. if (repo.persistentConnection_) {
  11137. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11138. }
  11139. }
  11140. function repoResume(repo) {
  11141. if (repo.persistentConnection_) {
  11142. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11143. }
  11144. }
  11145. function repoLog(repo, ...varArgs) {
  11146. let prefix = '';
  11147. if (repo.persistentConnection_) {
  11148. prefix = repo.persistentConnection_.id + ':';
  11149. }
  11150. log(prefix, ...varArgs);
  11151. }
  11152. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11153. if (callback) {
  11154. exceptionGuard(() => {
  11155. if (status === 'ok') {
  11156. callback(null);
  11157. }
  11158. else {
  11159. const code = (status || 'error').toUpperCase();
  11160. let message = code;
  11161. if (errorReason) {
  11162. message += ': ' + errorReason;
  11163. }
  11164. const error = new Error(message);
  11165. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11166. error.code = code;
  11167. callback(error);
  11168. }
  11169. });
  11170. }
  11171. }
  11172. /**
  11173. * Creates a new transaction, adds it to the transactions we're tracking, and
  11174. * sends it to the server if possible.
  11175. *
  11176. * @param path - Path at which to do transaction.
  11177. * @param transactionUpdate - Update callback.
  11178. * @param onComplete - Completion callback.
  11179. * @param unwatcher - Function that will be called when the transaction no longer
  11180. * need data updates for `path`.
  11181. * @param applyLocally - Whether or not to make intermediate results visible
  11182. */
  11183. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11184. repoLog(repo, 'transaction on ' + path);
  11185. // Initialize transaction.
  11186. const transaction = {
  11187. path,
  11188. update: transactionUpdate,
  11189. onComplete,
  11190. // One of TransactionStatus enums.
  11191. status: null,
  11192. // Used when combining transactions at different locations to figure out
  11193. // which one goes first.
  11194. order: LUIDGenerator(),
  11195. // Whether to raise local events for this transaction.
  11196. applyLocally,
  11197. // Count of how many times we've retried the transaction.
  11198. retryCount: 0,
  11199. // Function to call to clean up our .on() listener.
  11200. unwatcher,
  11201. // Stores why a transaction was aborted.
  11202. abortReason: null,
  11203. currentWriteId: null,
  11204. currentInputSnapshot: null,
  11205. currentOutputSnapshotRaw: null,
  11206. currentOutputSnapshotResolved: null
  11207. };
  11208. // Run transaction initially.
  11209. const currentState = repoGetLatestState(repo, path, undefined);
  11210. transaction.currentInputSnapshot = currentState;
  11211. const newVal = transaction.update(currentState.val());
  11212. if (newVal === undefined) {
  11213. // Abort transaction.
  11214. transaction.unwatcher();
  11215. transaction.currentOutputSnapshotRaw = null;
  11216. transaction.currentOutputSnapshotResolved = null;
  11217. if (transaction.onComplete) {
  11218. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11219. }
  11220. }
  11221. else {
  11222. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11223. // Mark as run and add to our queue.
  11224. transaction.status = 0 /* TransactionStatus.RUN */;
  11225. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11226. const nodeQueue = treeGetValue(queueNode) || [];
  11227. nodeQueue.push(transaction);
  11228. treeSetValue(queueNode, nodeQueue);
  11229. // Update visibleData and raise events
  11230. // Note: We intentionally raise events after updating all of our
  11231. // transaction state, since the user could start new transactions from the
  11232. // event callbacks.
  11233. let priorityForNode;
  11234. if (typeof newVal === 'object' &&
  11235. newVal !== null &&
  11236. contains(newVal, '.priority')) {
  11237. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11238. priorityForNode = safeGet(newVal, '.priority');
  11239. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11240. 'Priority must be a valid string, finite number, server value, or null.');
  11241. }
  11242. else {
  11243. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11244. ChildrenNode.EMPTY_NODE;
  11245. priorityForNode = currentNode.getPriority().val();
  11246. }
  11247. const serverValues = repoGenerateServerValues(repo);
  11248. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11249. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11250. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11251. transaction.currentOutputSnapshotResolved = newNode;
  11252. transaction.currentWriteId = repoGetNextWriteId(repo);
  11253. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11254. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11255. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11256. }
  11257. }
  11258. /**
  11259. * @param excludeSets - A specific set to exclude
  11260. */
  11261. function repoGetLatestState(repo, path, excludeSets) {
  11262. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11263. ChildrenNode.EMPTY_NODE);
  11264. }
  11265. /**
  11266. * Sends any already-run transactions that aren't waiting for outstanding
  11267. * transactions to complete.
  11268. *
  11269. * Externally it's called with no arguments, but it calls itself recursively
  11270. * with a particular transactionQueueTree node to recurse through the tree.
  11271. *
  11272. * @param node - transactionQueueTree node to start at.
  11273. */
  11274. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11275. // Before recursing, make sure any completed transactions are removed.
  11276. if (!node) {
  11277. repoPruneCompletedTransactionsBelowNode(repo, node);
  11278. }
  11279. if (treeGetValue(node)) {
  11280. const queue = repoBuildTransactionQueue(repo, node);
  11281. assert(queue.length > 0, 'Sending zero length transaction queue');
  11282. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11283. // If they're all run (and not sent), we can send them. Else, we must wait.
  11284. if (allRun) {
  11285. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11286. }
  11287. }
  11288. else if (treeHasChildren(node)) {
  11289. treeForEachChild(node, childNode => {
  11290. repoSendReadyTransactions(repo, childNode);
  11291. });
  11292. }
  11293. }
  11294. /**
  11295. * Given a list of run transactions, send them to the server and then handle
  11296. * the result (success or failure).
  11297. *
  11298. * @param path - The location of the queue.
  11299. * @param queue - Queue of transactions under the specified location.
  11300. */
  11301. function repoSendTransactionQueue(repo, path, queue) {
  11302. // Mark transactions as sent and increment retry count!
  11303. const setsToIgnore = queue.map(txn => {
  11304. return txn.currentWriteId;
  11305. });
  11306. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11307. let snapToSend = latestState;
  11308. const latestHash = latestState.hash();
  11309. for (let i = 0; i < queue.length; i++) {
  11310. const txn = queue[i];
  11311. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11312. txn.status = 1 /* TransactionStatus.SENT */;
  11313. txn.retryCount++;
  11314. const relativePath = newRelativePath(path, txn.path);
  11315. // If we've gotten to this point, the output snapshot must be defined.
  11316. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11317. }
  11318. const dataToSend = snapToSend.val(true);
  11319. const pathToSend = path;
  11320. // Send the put.
  11321. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11322. repoLog(repo, 'transaction put response', {
  11323. path: pathToSend.toString(),
  11324. status
  11325. });
  11326. let events = [];
  11327. if (status === 'ok') {
  11328. // Queue up the callbacks and fire them after cleaning up all of our
  11329. // transaction state, since the callback could trigger more
  11330. // transactions or sets.
  11331. const callbacks = [];
  11332. for (let i = 0; i < queue.length; i++) {
  11333. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11334. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11335. if (queue[i].onComplete) {
  11336. // We never unset the output snapshot, and given that this
  11337. // transaction is complete, it should be set
  11338. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11339. }
  11340. queue[i].unwatcher();
  11341. }
  11342. // Now remove the completed transactions.
  11343. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11344. // There may be pending transactions that we can now send.
  11345. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11346. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11347. // Finally, trigger onComplete callbacks.
  11348. for (let i = 0; i < callbacks.length; i++) {
  11349. exceptionGuard(callbacks[i]);
  11350. }
  11351. }
  11352. else {
  11353. // transactions are no longer sent. Update their status appropriately.
  11354. if (status === 'datastale') {
  11355. for (let i = 0; i < queue.length; i++) {
  11356. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11357. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11358. }
  11359. else {
  11360. queue[i].status = 0 /* TransactionStatus.RUN */;
  11361. }
  11362. }
  11363. }
  11364. else {
  11365. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11366. for (let i = 0; i < queue.length; i++) {
  11367. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11368. queue[i].abortReason = status;
  11369. }
  11370. }
  11371. repoRerunTransactions(repo, path);
  11372. }
  11373. }, latestHash);
  11374. }
  11375. /**
  11376. * Finds all transactions dependent on the data at changedPath and reruns them.
  11377. *
  11378. * Should be called any time cached data changes.
  11379. *
  11380. * Return the highest path that was affected by rerunning transactions. This
  11381. * is the path at which events need to be raised for.
  11382. *
  11383. * @param changedPath - The path in mergedData that changed.
  11384. * @returns The rootmost path that was affected by rerunning transactions.
  11385. */
  11386. function repoRerunTransactions(repo, changedPath) {
  11387. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11388. const path = treeGetPath(rootMostTransactionNode);
  11389. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11390. repoRerunTransactionQueue(repo, queue, path);
  11391. return path;
  11392. }
  11393. /**
  11394. * Does all the work of rerunning transactions (as well as cleans up aborted
  11395. * transactions and whatnot).
  11396. *
  11397. * @param queue - The queue of transactions to run.
  11398. * @param path - The path the queue is for.
  11399. */
  11400. function repoRerunTransactionQueue(repo, queue, path) {
  11401. if (queue.length === 0) {
  11402. return; // Nothing to do!
  11403. }
  11404. // Queue up the callbacks and fire them after cleaning up all of our
  11405. // transaction state, since the callback could trigger more transactions or
  11406. // sets.
  11407. const callbacks = [];
  11408. let events = [];
  11409. // Ignore all of the sets we're going to re-run.
  11410. const txnsToRerun = queue.filter(q => {
  11411. return q.status === 0 /* TransactionStatus.RUN */;
  11412. });
  11413. const setsToIgnore = txnsToRerun.map(q => {
  11414. return q.currentWriteId;
  11415. });
  11416. for (let i = 0; i < queue.length; i++) {
  11417. const transaction = queue[i];
  11418. const relativePath = newRelativePath(path, transaction.path);
  11419. let abortTransaction = false, abortReason;
  11420. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11421. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11422. abortTransaction = true;
  11423. abortReason = transaction.abortReason;
  11424. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11425. }
  11426. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11427. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11428. abortTransaction = true;
  11429. abortReason = 'maxretry';
  11430. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11431. }
  11432. else {
  11433. // This code reruns a transaction
  11434. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11435. transaction.currentInputSnapshot = currentNode;
  11436. const newData = queue[i].update(currentNode.val());
  11437. if (newData !== undefined) {
  11438. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11439. let newDataNode = nodeFromJSON(newData);
  11440. const hasExplicitPriority = typeof newData === 'object' &&
  11441. newData != null &&
  11442. contains(newData, '.priority');
  11443. if (!hasExplicitPriority) {
  11444. // Keep the old priority if there wasn't a priority explicitly specified.
  11445. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11446. }
  11447. const oldWriteId = transaction.currentWriteId;
  11448. const serverValues = repoGenerateServerValues(repo);
  11449. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11450. transaction.currentOutputSnapshotRaw = newDataNode;
  11451. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11452. transaction.currentWriteId = repoGetNextWriteId(repo);
  11453. // Mutates setsToIgnore in place
  11454. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11455. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11456. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11457. }
  11458. else {
  11459. abortTransaction = true;
  11460. abortReason = 'nodata';
  11461. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11462. }
  11463. }
  11464. }
  11465. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11466. events = [];
  11467. if (abortTransaction) {
  11468. // Abort.
  11469. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11470. // Removing a listener can trigger pruning which can muck with
  11471. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11472. // until we're done.
  11473. (function (unwatcher) {
  11474. setTimeout(unwatcher, Math.floor(0));
  11475. })(queue[i].unwatcher);
  11476. if (queue[i].onComplete) {
  11477. if (abortReason === 'nodata') {
  11478. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11479. }
  11480. else {
  11481. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11482. }
  11483. }
  11484. }
  11485. }
  11486. // Clean up completed transactions.
  11487. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11488. // Now fire callbacks, now that we're in a good, known state.
  11489. for (let i = 0; i < callbacks.length; i++) {
  11490. exceptionGuard(callbacks[i]);
  11491. }
  11492. // Try to send the transaction result to the server.
  11493. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11494. }
  11495. /**
  11496. * Returns the rootmost ancestor node of the specified path that has a pending
  11497. * transaction on it, or just returns the node for the given path if there are
  11498. * no pending transactions on any ancestor.
  11499. *
  11500. * @param path - The location to start at.
  11501. * @returns The rootmost node with a transaction.
  11502. */
  11503. function repoGetAncestorTransactionNode(repo, path) {
  11504. let front;
  11505. // Start at the root and walk deeper into the tree towards path until we
  11506. // find a node with pending transactions.
  11507. let transactionNode = repo.transactionQueueTree_;
  11508. front = pathGetFront(path);
  11509. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11510. transactionNode = treeSubTree(transactionNode, front);
  11511. path = pathPopFront(path);
  11512. front = pathGetFront(path);
  11513. }
  11514. return transactionNode;
  11515. }
  11516. /**
  11517. * Builds the queue of all transactions at or below the specified
  11518. * transactionNode.
  11519. *
  11520. * @param transactionNode
  11521. * @returns The generated queue.
  11522. */
  11523. function repoBuildTransactionQueue(repo, transactionNode) {
  11524. // Walk any child transaction queues and aggregate them into a single queue.
  11525. const transactionQueue = [];
  11526. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11527. // Sort them by the order the transactions were created.
  11528. transactionQueue.sort((a, b) => a.order - b.order);
  11529. return transactionQueue;
  11530. }
  11531. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11532. const nodeQueue = treeGetValue(node);
  11533. if (nodeQueue) {
  11534. for (let i = 0; i < nodeQueue.length; i++) {
  11535. queue.push(nodeQueue[i]);
  11536. }
  11537. }
  11538. treeForEachChild(node, child => {
  11539. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11540. });
  11541. }
  11542. /**
  11543. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11544. */
  11545. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11546. const queue = treeGetValue(node);
  11547. if (queue) {
  11548. let to = 0;
  11549. for (let from = 0; from < queue.length; from++) {
  11550. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11551. queue[to] = queue[from];
  11552. to++;
  11553. }
  11554. }
  11555. queue.length = to;
  11556. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11557. }
  11558. treeForEachChild(node, childNode => {
  11559. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11560. });
  11561. }
  11562. /**
  11563. * Aborts all transactions on ancestors or descendants of the specified path.
  11564. * Called when doing a set() or update() since we consider them incompatible
  11565. * with transactions.
  11566. *
  11567. * @param path - Path for which we want to abort related transactions.
  11568. */
  11569. function repoAbortTransactions(repo, path) {
  11570. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11571. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11572. treeForEachAncestor(transactionNode, (node) => {
  11573. repoAbortTransactionsOnNode(repo, node);
  11574. });
  11575. repoAbortTransactionsOnNode(repo, transactionNode);
  11576. treeForEachDescendant(transactionNode, (node) => {
  11577. repoAbortTransactionsOnNode(repo, node);
  11578. });
  11579. return affectedPath;
  11580. }
  11581. /**
  11582. * Abort transactions stored in this transaction queue node.
  11583. *
  11584. * @param node - Node to abort transactions for.
  11585. */
  11586. function repoAbortTransactionsOnNode(repo, node) {
  11587. const queue = treeGetValue(node);
  11588. if (queue) {
  11589. // Queue up the callbacks and fire them after cleaning up all of our
  11590. // transaction state, since the callback could trigger more transactions
  11591. // or sets.
  11592. const callbacks = [];
  11593. // Go through queue. Any already-sent transactions must be marked for
  11594. // abort, while the unsent ones can be immediately aborted and removed.
  11595. let events = [];
  11596. let lastSent = -1;
  11597. for (let i = 0; i < queue.length; i++) {
  11598. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11599. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11600. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11601. lastSent = i;
  11602. // Mark transaction for abort when it comes back.
  11603. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11604. queue[i].abortReason = 'set';
  11605. }
  11606. else {
  11607. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11608. // We can abort it immediately.
  11609. queue[i].unwatcher();
  11610. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11611. if (queue[i].onComplete) {
  11612. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11613. }
  11614. }
  11615. }
  11616. if (lastSent === -1) {
  11617. // We're not waiting for any sent transactions. We can clear the queue.
  11618. treeSetValue(node, undefined);
  11619. }
  11620. else {
  11621. // Remove the transactions we aborted.
  11622. queue.length = lastSent + 1;
  11623. }
  11624. // Now fire the callbacks.
  11625. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11626. for (let i = 0; i < callbacks.length; i++) {
  11627. exceptionGuard(callbacks[i]);
  11628. }
  11629. }
  11630. }
  11631. /**
  11632. * @license
  11633. * Copyright 2017 Google LLC
  11634. *
  11635. * Licensed under the Apache License, Version 2.0 (the "License");
  11636. * you may not use this file except in compliance with the License.
  11637. * You may obtain a copy of the License at
  11638. *
  11639. * http://www.apache.org/licenses/LICENSE-2.0
  11640. *
  11641. * Unless required by applicable law or agreed to in writing, software
  11642. * distributed under the License is distributed on an "AS IS" BASIS,
  11643. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11644. * See the License for the specific language governing permissions and
  11645. * limitations under the License.
  11646. */
  11647. function decodePath(pathString) {
  11648. let pathStringDecoded = '';
  11649. const pieces = pathString.split('/');
  11650. for (let i = 0; i < pieces.length; i++) {
  11651. if (pieces[i].length > 0) {
  11652. let piece = pieces[i];
  11653. try {
  11654. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11655. }
  11656. catch (e) { }
  11657. pathStringDecoded += '/' + piece;
  11658. }
  11659. }
  11660. return pathStringDecoded;
  11661. }
  11662. /**
  11663. * @returns key value hash
  11664. */
  11665. function decodeQuery(queryString) {
  11666. const results = {};
  11667. if (queryString.charAt(0) === '?') {
  11668. queryString = queryString.substring(1);
  11669. }
  11670. for (const segment of queryString.split('&')) {
  11671. if (segment.length === 0) {
  11672. continue;
  11673. }
  11674. const kv = segment.split('=');
  11675. if (kv.length === 2) {
  11676. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11677. }
  11678. else {
  11679. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11680. }
  11681. }
  11682. return results;
  11683. }
  11684. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11685. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11686. if (parsedUrl.domain === 'firebase.com') {
  11687. fatal(parsedUrl.host +
  11688. ' is no longer supported. ' +
  11689. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11690. }
  11691. // Catch common error of uninitialized namespace value.
  11692. if ((!namespace || namespace === 'undefined') &&
  11693. parsedUrl.domain !== 'localhost') {
  11694. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11695. }
  11696. if (!parsedUrl.secure) {
  11697. warnIfPageIsSecure();
  11698. }
  11699. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11700. return {
  11701. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11702. /*persistenceKey=*/ '',
  11703. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11704. path: new Path(parsedUrl.pathString)
  11705. };
  11706. };
  11707. const parseDatabaseURL = function (dataURL) {
  11708. // Default to empty strings in the event of a malformed string.
  11709. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11710. // Always default to SSL, unless otherwise specified.
  11711. let secure = true, scheme = 'https', port = 443;
  11712. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11713. if (typeof dataURL === 'string') {
  11714. // Parse scheme.
  11715. let colonInd = dataURL.indexOf('//');
  11716. if (colonInd >= 0) {
  11717. scheme = dataURL.substring(0, colonInd - 1);
  11718. dataURL = dataURL.substring(colonInd + 2);
  11719. }
  11720. // Parse host, path, and query string.
  11721. let slashInd = dataURL.indexOf('/');
  11722. if (slashInd === -1) {
  11723. slashInd = dataURL.length;
  11724. }
  11725. let questionMarkInd = dataURL.indexOf('?');
  11726. if (questionMarkInd === -1) {
  11727. questionMarkInd = dataURL.length;
  11728. }
  11729. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11730. if (slashInd < questionMarkInd) {
  11731. // For pathString, questionMarkInd will always come after slashInd
  11732. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11733. }
  11734. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11735. // If we have a port, use scheme for determining if it's secure.
  11736. colonInd = host.indexOf(':');
  11737. if (colonInd >= 0) {
  11738. secure = scheme === 'https' || scheme === 'wss';
  11739. port = parseInt(host.substring(colonInd + 1), 10);
  11740. }
  11741. else {
  11742. colonInd = host.length;
  11743. }
  11744. const hostWithoutPort = host.slice(0, colonInd);
  11745. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11746. domain = 'localhost';
  11747. }
  11748. else if (hostWithoutPort.split('.').length <= 2) {
  11749. domain = hostWithoutPort;
  11750. }
  11751. else {
  11752. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11753. const dotInd = host.indexOf('.');
  11754. subdomain = host.substring(0, dotInd).toLowerCase();
  11755. domain = host.substring(dotInd + 1);
  11756. // Normalize namespaces to lowercase to share storage / connection.
  11757. namespace = subdomain;
  11758. }
  11759. // Always treat the value of the `ns` as the namespace name if it is present.
  11760. if ('ns' in queryParams) {
  11761. namespace = queryParams['ns'];
  11762. }
  11763. }
  11764. return {
  11765. host,
  11766. port,
  11767. domain,
  11768. subdomain,
  11769. secure,
  11770. scheme,
  11771. pathString,
  11772. namespace
  11773. };
  11774. };
  11775. /**
  11776. * @license
  11777. * Copyright 2017 Google LLC
  11778. *
  11779. * Licensed under the Apache License, Version 2.0 (the "License");
  11780. * you may not use this file except in compliance with the License.
  11781. * You may obtain a copy of the License at
  11782. *
  11783. * http://www.apache.org/licenses/LICENSE-2.0
  11784. *
  11785. * Unless required by applicable law or agreed to in writing, software
  11786. * distributed under the License is distributed on an "AS IS" BASIS,
  11787. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11788. * See the License for the specific language governing permissions and
  11789. * limitations under the License.
  11790. */
  11791. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11792. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11793. /**
  11794. * Fancy ID generator that creates 20-character string identifiers with the
  11795. * following properties:
  11796. *
  11797. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11798. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11799. * collide with other clients' IDs.
  11800. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11801. * that will sort properly).
  11802. * 4. They're monotonically increasing. Even if you generate more than one in
  11803. * the same timestamp, the latter ones will sort after the former ones. We do
  11804. * this by using the previous random bits but "incrementing" them by 1 (only
  11805. * in the case of a timestamp collision).
  11806. */
  11807. const nextPushId = (function () {
  11808. // Timestamp of last push, used to prevent local collisions if you push twice
  11809. // in one ms.
  11810. let lastPushTime = 0;
  11811. // We generate 72-bits of randomness which get turned into 12 characters and
  11812. // appended to the timestamp to prevent collisions with other clients. We
  11813. // store the last characters we generated because in the event of a collision,
  11814. // we'll use those same characters except "incremented" by one.
  11815. const lastRandChars = [];
  11816. return function (now) {
  11817. const duplicateTime = now === lastPushTime;
  11818. lastPushTime = now;
  11819. let i;
  11820. const timeStampChars = new Array(8);
  11821. for (i = 7; i >= 0; i--) {
  11822. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11823. // NOTE: Can't use << here because javascript will convert to int and lose
  11824. // the upper bits.
  11825. now = Math.floor(now / 64);
  11826. }
  11827. assert(now === 0, 'Cannot push at time == 0');
  11828. let id = timeStampChars.join('');
  11829. if (!duplicateTime) {
  11830. for (i = 0; i < 12; i++) {
  11831. lastRandChars[i] = Math.floor(Math.random() * 64);
  11832. }
  11833. }
  11834. else {
  11835. // If the timestamp hasn't changed since last push, use the same random
  11836. // number, except incremented by 1.
  11837. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11838. lastRandChars[i] = 0;
  11839. }
  11840. lastRandChars[i]++;
  11841. }
  11842. for (i = 0; i < 12; i++) {
  11843. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11844. }
  11845. assert(id.length === 20, 'nextPushId: Length should be 20.');
  11846. return id;
  11847. };
  11848. })();
  11849. /**
  11850. * @license
  11851. * Copyright 2017 Google LLC
  11852. *
  11853. * Licensed under the Apache License, Version 2.0 (the "License");
  11854. * you may not use this file except in compliance with the License.
  11855. * You may obtain a copy of the License at
  11856. *
  11857. * http://www.apache.org/licenses/LICENSE-2.0
  11858. *
  11859. * Unless required by applicable law or agreed to in writing, software
  11860. * distributed under the License is distributed on an "AS IS" BASIS,
  11861. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11862. * See the License for the specific language governing permissions and
  11863. * limitations under the License.
  11864. */
  11865. /**
  11866. * Encapsulates the data needed to raise an event
  11867. */
  11868. class DataEvent {
  11869. /**
  11870. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11871. * @param eventRegistration - The function to call to with the event data. User provided
  11872. * @param snapshot - The data backing the event
  11873. * @param prevName - Optional, the name of the previous child for child_* events.
  11874. */
  11875. constructor(eventType, eventRegistration, snapshot, prevName) {
  11876. this.eventType = eventType;
  11877. this.eventRegistration = eventRegistration;
  11878. this.snapshot = snapshot;
  11879. this.prevName = prevName;
  11880. }
  11881. getPath() {
  11882. const ref = this.snapshot.ref;
  11883. if (this.eventType === 'value') {
  11884. return ref._path;
  11885. }
  11886. else {
  11887. return ref.parent._path;
  11888. }
  11889. }
  11890. getEventType() {
  11891. return this.eventType;
  11892. }
  11893. getEventRunner() {
  11894. return this.eventRegistration.getEventRunner(this);
  11895. }
  11896. toString() {
  11897. return (this.getPath().toString() +
  11898. ':' +
  11899. this.eventType +
  11900. ':' +
  11901. stringify(this.snapshot.exportVal()));
  11902. }
  11903. }
  11904. class CancelEvent {
  11905. constructor(eventRegistration, error, path) {
  11906. this.eventRegistration = eventRegistration;
  11907. this.error = error;
  11908. this.path = path;
  11909. }
  11910. getPath() {
  11911. return this.path;
  11912. }
  11913. getEventType() {
  11914. return 'cancel';
  11915. }
  11916. getEventRunner() {
  11917. return this.eventRegistration.getEventRunner(this);
  11918. }
  11919. toString() {
  11920. return this.path.toString() + ':cancel';
  11921. }
  11922. }
  11923. /**
  11924. * @license
  11925. * Copyright 2017 Google LLC
  11926. *
  11927. * Licensed under the Apache License, Version 2.0 (the "License");
  11928. * you may not use this file except in compliance with the License.
  11929. * You may obtain a copy of the License at
  11930. *
  11931. * http://www.apache.org/licenses/LICENSE-2.0
  11932. *
  11933. * Unless required by applicable law or agreed to in writing, software
  11934. * distributed under the License is distributed on an "AS IS" BASIS,
  11935. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11936. * See the License for the specific language governing permissions and
  11937. * limitations under the License.
  11938. */
  11939. /**
  11940. * A wrapper class that converts events from the database@exp SDK to the legacy
  11941. * Database SDK. Events are not converted directly as event registration relies
  11942. * on reference comparison of the original user callback (see `matches()`) and
  11943. * relies on equality of the legacy SDK's `context` object.
  11944. */
  11945. class CallbackContext {
  11946. constructor(snapshotCallback, cancelCallback) {
  11947. this.snapshotCallback = snapshotCallback;
  11948. this.cancelCallback = cancelCallback;
  11949. }
  11950. onValue(expDataSnapshot, previousChildName) {
  11951. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11952. }
  11953. onCancel(error) {
  11954. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11955. return this.cancelCallback.call(null, error);
  11956. }
  11957. get hasCancelCallback() {
  11958. return !!this.cancelCallback;
  11959. }
  11960. matches(other) {
  11961. return (this.snapshotCallback === other.snapshotCallback ||
  11962. (this.snapshotCallback.userCallback !== undefined &&
  11963. this.snapshotCallback.userCallback ===
  11964. other.snapshotCallback.userCallback &&
  11965. this.snapshotCallback.context === other.snapshotCallback.context));
  11966. }
  11967. }
  11968. /**
  11969. * @license
  11970. * Copyright 2021 Google LLC
  11971. *
  11972. * Licensed under the Apache License, Version 2.0 (the "License");
  11973. * you may not use this file except in compliance with the License.
  11974. * You may obtain a copy of the License at
  11975. *
  11976. * http://www.apache.org/licenses/LICENSE-2.0
  11977. *
  11978. * Unless required by applicable law or agreed to in writing, software
  11979. * distributed under the License is distributed on an "AS IS" BASIS,
  11980. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11981. * See the License for the specific language governing permissions and
  11982. * limitations under the License.
  11983. */
  11984. /**
  11985. * The `onDisconnect` class allows you to write or clear data when your client
  11986. * disconnects from the Database server. These updates occur whether your
  11987. * client disconnects cleanly or not, so you can rely on them to clean up data
  11988. * even if a connection is dropped or a client crashes.
  11989. *
  11990. * The `onDisconnect` class is most commonly used to manage presence in
  11991. * applications where it is useful to detect how many clients are connected and
  11992. * when other clients disconnect. See
  11993. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  11994. * for more information.
  11995. *
  11996. * To avoid problems when a connection is dropped before the requests can be
  11997. * transferred to the Database server, these functions should be called before
  11998. * writing any data.
  11999. *
  12000. * Note that `onDisconnect` operations are only triggered once. If you want an
  12001. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12002. * the `onDisconnect` operations each time you reconnect.
  12003. */
  12004. class OnDisconnect {
  12005. /** @hideconstructor */
  12006. constructor(_repo, _path) {
  12007. this._repo = _repo;
  12008. this._path = _path;
  12009. }
  12010. /**
  12011. * Cancels all previously queued `onDisconnect()` set or update events for this
  12012. * location and all children.
  12013. *
  12014. * If a write has been queued for this location via a `set()` or `update()` at a
  12015. * parent location, the write at this location will be canceled, though writes
  12016. * to sibling locations will still occur.
  12017. *
  12018. * @returns Resolves when synchronization to the server is complete.
  12019. */
  12020. cancel() {
  12021. const deferred = new Deferred();
  12022. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12023. return deferred.promise;
  12024. }
  12025. /**
  12026. * Ensures the data at this location is deleted when the client is disconnected
  12027. * (due to closing the browser, navigating to a new page, or network issues).
  12028. *
  12029. * @returns Resolves when synchronization to the server is complete.
  12030. */
  12031. remove() {
  12032. validateWritablePath('OnDisconnect.remove', this._path);
  12033. const deferred = new Deferred();
  12034. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12035. return deferred.promise;
  12036. }
  12037. /**
  12038. * Ensures the data at this location is set to the specified value when the
  12039. * client is disconnected (due to closing the browser, navigating to a new page,
  12040. * or network issues).
  12041. *
  12042. * `set()` is especially useful for implementing "presence" systems, where a
  12043. * value should be changed or cleared when a user disconnects so that they
  12044. * appear "offline" to other users. See
  12045. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12046. * for more information.
  12047. *
  12048. * Note that `onDisconnect` operations are only triggered once. If you want an
  12049. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12050. * the `onDisconnect` operations each time.
  12051. *
  12052. * @param value - The value to be written to this location on disconnect (can
  12053. * be an object, array, string, number, boolean, or null).
  12054. * @returns Resolves when synchronization to the Database is complete.
  12055. */
  12056. set(value) {
  12057. validateWritablePath('OnDisconnect.set', this._path);
  12058. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12059. const deferred = new Deferred();
  12060. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12061. return deferred.promise;
  12062. }
  12063. /**
  12064. * Ensures the data at this location is set to the specified value and priority
  12065. * when the client is disconnected (due to closing the browser, navigating to a
  12066. * new page, or network issues).
  12067. *
  12068. * @param value - The value to be written to this location on disconnect (can
  12069. * be an object, array, string, number, boolean, or null).
  12070. * @param priority - The priority to be written (string, number, or null).
  12071. * @returns Resolves when synchronization to the Database is complete.
  12072. */
  12073. setWithPriority(value, priority) {
  12074. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12075. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12076. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12077. const deferred = new Deferred();
  12078. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12079. return deferred.promise;
  12080. }
  12081. /**
  12082. * Writes multiple values at this location when the client is disconnected (due
  12083. * to closing the browser, navigating to a new page, or network issues).
  12084. *
  12085. * The `values` argument contains multiple property-value pairs that will be
  12086. * written to the Database together. Each child property can either be a simple
  12087. * property (for example, "name") or a relative path (for example, "name/first")
  12088. * from the current location to the data to update.
  12089. *
  12090. * As opposed to the `set()` method, `update()` can be use to selectively update
  12091. * only the referenced properties at the current location (instead of replacing
  12092. * all the child properties at the current location).
  12093. *
  12094. * @param values - Object containing multiple values.
  12095. * @returns Resolves when synchronization to the Database is complete.
  12096. */
  12097. update(values) {
  12098. validateWritablePath('OnDisconnect.update', this._path);
  12099. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12100. const deferred = new Deferred();
  12101. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12102. return deferred.promise;
  12103. }
  12104. }
  12105. /**
  12106. * @license
  12107. * Copyright 2020 Google LLC
  12108. *
  12109. * Licensed under the Apache License, Version 2.0 (the "License");
  12110. * you may not use this file except in compliance with the License.
  12111. * You may obtain a copy of the License at
  12112. *
  12113. * http://www.apache.org/licenses/LICENSE-2.0
  12114. *
  12115. * Unless required by applicable law or agreed to in writing, software
  12116. * distributed under the License is distributed on an "AS IS" BASIS,
  12117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12118. * See the License for the specific language governing permissions and
  12119. * limitations under the License.
  12120. */
  12121. /**
  12122. * @internal
  12123. */
  12124. class QueryImpl {
  12125. /**
  12126. * @hideconstructor
  12127. */
  12128. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12129. this._repo = _repo;
  12130. this._path = _path;
  12131. this._queryParams = _queryParams;
  12132. this._orderByCalled = _orderByCalled;
  12133. }
  12134. get key() {
  12135. if (pathIsEmpty(this._path)) {
  12136. return null;
  12137. }
  12138. else {
  12139. return pathGetBack(this._path);
  12140. }
  12141. }
  12142. get ref() {
  12143. return new ReferenceImpl(this._repo, this._path);
  12144. }
  12145. get _queryIdentifier() {
  12146. const obj = queryParamsGetQueryObject(this._queryParams);
  12147. const id = ObjectToUniqueKey(obj);
  12148. return id === '{}' ? 'default' : id;
  12149. }
  12150. /**
  12151. * An object representation of the query parameters used by this Query.
  12152. */
  12153. get _queryObject() {
  12154. return queryParamsGetQueryObject(this._queryParams);
  12155. }
  12156. isEqual(other) {
  12157. other = getModularInstance(other);
  12158. if (!(other instanceof QueryImpl)) {
  12159. return false;
  12160. }
  12161. const sameRepo = this._repo === other._repo;
  12162. const samePath = pathEquals(this._path, other._path);
  12163. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12164. return sameRepo && samePath && sameQueryIdentifier;
  12165. }
  12166. toJSON() {
  12167. return this.toString();
  12168. }
  12169. toString() {
  12170. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12171. }
  12172. }
  12173. /**
  12174. * Validates that no other order by call has been made
  12175. */
  12176. function validateNoPreviousOrderByCall(query, fnName) {
  12177. if (query._orderByCalled === true) {
  12178. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12179. }
  12180. }
  12181. /**
  12182. * Validates start/end values for queries.
  12183. */
  12184. function validateQueryEndpoints(params) {
  12185. let startNode = null;
  12186. let endNode = null;
  12187. if (params.hasStart()) {
  12188. startNode = params.getIndexStartValue();
  12189. }
  12190. if (params.hasEnd()) {
  12191. endNode = params.getIndexEndValue();
  12192. }
  12193. if (params.getIndex() === KEY_INDEX) {
  12194. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12195. 'startAt(), endAt(), or equalTo().';
  12196. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12197. 'endAt(), endBefore(), or equalTo() must be a string.';
  12198. if (params.hasStart()) {
  12199. const startName = params.getIndexStartName();
  12200. if (startName !== MIN_NAME) {
  12201. throw new Error(tooManyArgsError);
  12202. }
  12203. else if (typeof startNode !== 'string') {
  12204. throw new Error(wrongArgTypeError);
  12205. }
  12206. }
  12207. if (params.hasEnd()) {
  12208. const endName = params.getIndexEndName();
  12209. if (endName !== MAX_NAME) {
  12210. throw new Error(tooManyArgsError);
  12211. }
  12212. else if (typeof endNode !== 'string') {
  12213. throw new Error(wrongArgTypeError);
  12214. }
  12215. }
  12216. }
  12217. else if (params.getIndex() === PRIORITY_INDEX) {
  12218. if ((startNode != null && !isValidPriority(startNode)) ||
  12219. (endNode != null && !isValidPriority(endNode))) {
  12220. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12221. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12222. '(null, a number, or a string).');
  12223. }
  12224. }
  12225. else {
  12226. assert(params.getIndex() instanceof PathIndex ||
  12227. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12228. if ((startNode != null && typeof startNode === 'object') ||
  12229. (endNode != null && typeof endNode === 'object')) {
  12230. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12231. 'equalTo() cannot be an object.');
  12232. }
  12233. }
  12234. }
  12235. /**
  12236. * Validates that limit* has been called with the correct combination of parameters
  12237. */
  12238. function validateLimit(params) {
  12239. if (params.hasStart() &&
  12240. params.hasEnd() &&
  12241. params.hasLimit() &&
  12242. !params.hasAnchoredLimit()) {
  12243. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12244. 'limitToFirst() or limitToLast() instead.');
  12245. }
  12246. }
  12247. /**
  12248. * @internal
  12249. */
  12250. class ReferenceImpl extends QueryImpl {
  12251. /** @hideconstructor */
  12252. constructor(repo, path) {
  12253. super(repo, path, new QueryParams(), false);
  12254. }
  12255. get parent() {
  12256. const parentPath = pathParent(this._path);
  12257. return parentPath === null
  12258. ? null
  12259. : new ReferenceImpl(this._repo, parentPath);
  12260. }
  12261. get root() {
  12262. let ref = this;
  12263. while (ref.parent !== null) {
  12264. ref = ref.parent;
  12265. }
  12266. return ref;
  12267. }
  12268. }
  12269. /**
  12270. * A `DataSnapshot` contains data from a Database location.
  12271. *
  12272. * Any time you read data from the Database, you receive the data as a
  12273. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12274. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12275. * JavaScript object by calling the `val()` method. Alternatively, you can
  12276. * traverse into the snapshot by calling `child()` to return child snapshots
  12277. * (which you could then call `val()` on).
  12278. *
  12279. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12280. * a Database location. It cannot be modified and will never change (to modify
  12281. * data, you always call the `set()` method on a `Reference` directly).
  12282. */
  12283. class DataSnapshot {
  12284. /**
  12285. * @param _node - A SnapshotNode to wrap.
  12286. * @param ref - The location this snapshot came from.
  12287. * @param _index - The iteration order for this snapshot
  12288. * @hideconstructor
  12289. */
  12290. constructor(_node,
  12291. /**
  12292. * The location of this DataSnapshot.
  12293. */
  12294. ref, _index) {
  12295. this._node = _node;
  12296. this.ref = ref;
  12297. this._index = _index;
  12298. }
  12299. /**
  12300. * Gets the priority value of the data in this `DataSnapshot`.
  12301. *
  12302. * Applications need not use priority but can order collections by
  12303. * ordinary properties (see
  12304. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12305. * ).
  12306. */
  12307. get priority() {
  12308. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12309. return this._node.getPriority().val();
  12310. }
  12311. /**
  12312. * The key (last part of the path) of the location of this `DataSnapshot`.
  12313. *
  12314. * The last token in a Database location is considered its key. For example,
  12315. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12316. * `DataSnapshot` will return the key for the location that generated it.
  12317. * However, accessing the key on the root URL of a Database will return
  12318. * `null`.
  12319. */
  12320. get key() {
  12321. return this.ref.key;
  12322. }
  12323. /** Returns the number of child properties of this `DataSnapshot`. */
  12324. get size() {
  12325. return this._node.numChildren();
  12326. }
  12327. /**
  12328. * Gets another `DataSnapshot` for the location at the specified relative path.
  12329. *
  12330. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12331. * another `DataSnapshot` for the location at the specified relative path. The
  12332. * relative path can either be a simple child name (for example, "ada") or a
  12333. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12334. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12335. * whose value is `null`) is returned.
  12336. *
  12337. * @param path - A relative path to the location of child data.
  12338. */
  12339. child(path) {
  12340. const childPath = new Path(path);
  12341. const childRef = child(this.ref, path);
  12342. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12343. }
  12344. /**
  12345. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12346. * efficient than using `snapshot.val() !== null`.
  12347. */
  12348. exists() {
  12349. return !this._node.isEmpty();
  12350. }
  12351. /**
  12352. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12353. *
  12354. * The `exportVal()` method is similar to `val()`, except priority information
  12355. * is included (if available), making it suitable for backing up your data.
  12356. *
  12357. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12358. * Array, string, number, boolean, or `null`).
  12359. */
  12360. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12361. exportVal() {
  12362. return this._node.val(true);
  12363. }
  12364. /**
  12365. * Enumerates the top-level children in the `DataSnapshot`.
  12366. *
  12367. * Because of the way JavaScript objects work, the ordering of data in the
  12368. * JavaScript object returned by `val()` is not guaranteed to match the
  12369. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12370. * where `forEach()` comes in handy. It guarantees the children of a
  12371. * `DataSnapshot` will be iterated in their query order.
  12372. *
  12373. * If no explicit `orderBy*()` method is used, results are returned
  12374. * ordered by key (unless priorities are used, in which case, results are
  12375. * returned by priority).
  12376. *
  12377. * @param action - A function that will be called for each child DataSnapshot.
  12378. * The callback can return true to cancel further enumeration.
  12379. * @returns true if enumeration was canceled due to your callback returning
  12380. * true.
  12381. */
  12382. forEach(action) {
  12383. if (this._node.isLeafNode()) {
  12384. return false;
  12385. }
  12386. const childrenNode = this._node;
  12387. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12388. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12389. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12390. });
  12391. }
  12392. /**
  12393. * Returns true if the specified child path has (non-null) data.
  12394. *
  12395. * @param path - A relative path to the location of a potential child.
  12396. * @returns `true` if data exists at the specified child path; else
  12397. * `false`.
  12398. */
  12399. hasChild(path) {
  12400. const childPath = new Path(path);
  12401. return !this._node.getChild(childPath).isEmpty();
  12402. }
  12403. /**
  12404. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12405. * properties.
  12406. *
  12407. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12408. * children. If it does, you can enumerate them using `forEach()`. If it
  12409. * doesn't, then either this snapshot contains a primitive value (which can be
  12410. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12411. * `null`).
  12412. *
  12413. * @returns true if this snapshot has any children; else false.
  12414. */
  12415. hasChildren() {
  12416. if (this._node.isLeafNode()) {
  12417. return false;
  12418. }
  12419. else {
  12420. return !this._node.isEmpty();
  12421. }
  12422. }
  12423. /**
  12424. * Returns a JSON-serializable representation of this object.
  12425. */
  12426. toJSON() {
  12427. return this.exportVal();
  12428. }
  12429. /**
  12430. * Extracts a JavaScript value from a `DataSnapshot`.
  12431. *
  12432. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12433. * scalar type (string, number, or boolean), an array, or an object. It may
  12434. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12435. * data).
  12436. *
  12437. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12438. * Array, string, number, boolean, or `null`).
  12439. */
  12440. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12441. val() {
  12442. return this._node.val();
  12443. }
  12444. }
  12445. /**
  12446. *
  12447. * Returns a `Reference` representing the location in the Database
  12448. * corresponding to the provided path. If no path is provided, the `Reference`
  12449. * will point to the root of the Database.
  12450. *
  12451. * @param db - The database instance to obtain a reference for.
  12452. * @param path - Optional path representing the location the returned
  12453. * `Reference` will point. If not provided, the returned `Reference` will
  12454. * point to the root of the Database.
  12455. * @returns If a path is provided, a `Reference`
  12456. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12457. * root of the Database.
  12458. */
  12459. function ref(db, path) {
  12460. db = getModularInstance(db);
  12461. db._checkNotDeleted('ref');
  12462. return path !== undefined ? child(db._root, path) : db._root;
  12463. }
  12464. /**
  12465. * Returns a `Reference` representing the location in the Database
  12466. * corresponding to the provided Firebase URL.
  12467. *
  12468. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12469. * has a different domain than the current `Database` instance.
  12470. *
  12471. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12472. * and are not applied to the returned `Reference`.
  12473. *
  12474. * @param db - The database instance to obtain a reference for.
  12475. * @param url - The Firebase URL at which the returned `Reference` will
  12476. * point.
  12477. * @returns A `Reference` pointing to the provided
  12478. * Firebase URL.
  12479. */
  12480. function refFromURL(db, url) {
  12481. db = getModularInstance(db);
  12482. db._checkNotDeleted('refFromURL');
  12483. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12484. validateUrl('refFromURL', parsedURL);
  12485. const repoInfo = parsedURL.repoInfo;
  12486. if (!db._repo.repoInfo_.isCustomHost() &&
  12487. repoInfo.host !== db._repo.repoInfo_.host) {
  12488. fatal('refFromURL' +
  12489. ': Host name does not match the current database: ' +
  12490. '(found ' +
  12491. repoInfo.host +
  12492. ' but expected ' +
  12493. db._repo.repoInfo_.host +
  12494. ')');
  12495. }
  12496. return ref(db, parsedURL.path.toString());
  12497. }
  12498. /**
  12499. * Gets a `Reference` for the location at the specified relative path.
  12500. *
  12501. * The relative path can either be a simple child name (for example, "ada") or
  12502. * a deeper slash-separated path (for example, "ada/name/first").
  12503. *
  12504. * @param parent - The parent location.
  12505. * @param path - A relative path from this location to the desired child
  12506. * location.
  12507. * @returns The specified child location.
  12508. */
  12509. function child(parent, path) {
  12510. parent = getModularInstance(parent);
  12511. if (pathGetFront(parent._path) === null) {
  12512. validateRootPathString('child', 'path', path, false);
  12513. }
  12514. else {
  12515. validatePathString('child', 'path', path, false);
  12516. }
  12517. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12518. }
  12519. /**
  12520. * Returns an `OnDisconnect` object - see
  12521. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12522. * for more information on how to use it.
  12523. *
  12524. * @param ref - The reference to add OnDisconnect triggers for.
  12525. */
  12526. function onDisconnect(ref) {
  12527. ref = getModularInstance(ref);
  12528. return new OnDisconnect(ref._repo, ref._path);
  12529. }
  12530. /**
  12531. * Generates a new child location using a unique key and returns its
  12532. * `Reference`.
  12533. *
  12534. * This is the most common pattern for adding data to a collection of items.
  12535. *
  12536. * If you provide a value to `push()`, the value is written to the
  12537. * generated location. If you don't pass a value, nothing is written to the
  12538. * database and the child remains empty (but you can use the `Reference`
  12539. * elsewhere).
  12540. *
  12541. * The unique keys generated by `push()` are ordered by the current time, so the
  12542. * resulting list of items is chronologically sorted. The keys are also
  12543. * designed to be unguessable (they contain 72 random bits of entropy).
  12544. *
  12545. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12546. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12547. *
  12548. * @param parent - The parent location.
  12549. * @param value - Optional value to be written at the generated location.
  12550. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12551. * but can be used immediately as the `Reference` to the child location.
  12552. */
  12553. function push(parent, value) {
  12554. parent = getModularInstance(parent);
  12555. validateWritablePath('push', parent._path);
  12556. validateFirebaseDataArg('push', value, parent._path, true);
  12557. const now = repoServerTime(parent._repo);
  12558. const name = nextPushId(now);
  12559. // push() returns a ThennableReference whose promise is fulfilled with a
  12560. // regular Reference. We use child() to create handles to two different
  12561. // references. The first is turned into a ThennableReference below by adding
  12562. // then() and catch() methods and is used as the return value of push(). The
  12563. // second remains a regular Reference and is used as the fulfilled value of
  12564. // the first ThennableReference.
  12565. const thennablePushRef = child(parent, name);
  12566. const pushRef = child(parent, name);
  12567. let promise;
  12568. if (value != null) {
  12569. promise = set(pushRef, value).then(() => pushRef);
  12570. }
  12571. else {
  12572. promise = Promise.resolve(pushRef);
  12573. }
  12574. thennablePushRef.then = promise.then.bind(promise);
  12575. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12576. return thennablePushRef;
  12577. }
  12578. /**
  12579. * Removes the data at this Database location.
  12580. *
  12581. * Any data at child locations will also be deleted.
  12582. *
  12583. * The effect of the remove will be visible immediately and the corresponding
  12584. * event 'value' will be triggered. Synchronization of the remove to the
  12585. * Firebase servers will also be started, and the returned Promise will resolve
  12586. * when complete. If provided, the onComplete callback will be called
  12587. * asynchronously after synchronization has finished.
  12588. *
  12589. * @param ref - The location to remove.
  12590. * @returns Resolves when remove on server is complete.
  12591. */
  12592. function remove(ref) {
  12593. validateWritablePath('remove', ref._path);
  12594. return set(ref, null);
  12595. }
  12596. /**
  12597. * Writes data to this Database location.
  12598. *
  12599. * This will overwrite any data at this location and all child locations.
  12600. *
  12601. * The effect of the write will be visible immediately, and the corresponding
  12602. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12603. * the data to the Firebase servers will also be started, and the returned
  12604. * Promise will resolve when complete. If provided, the `onComplete` callback
  12605. * will be called asynchronously after synchronization has finished.
  12606. *
  12607. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12608. * all data at this location and all child locations will be deleted.
  12609. *
  12610. * `set()` will remove any priority stored at this location, so if priority is
  12611. * meant to be preserved, you need to use `setWithPriority()` instead.
  12612. *
  12613. * Note that modifying data with `set()` will cancel any pending transactions
  12614. * at that location, so extreme care should be taken if mixing `set()` and
  12615. * `transaction()` to modify the same data.
  12616. *
  12617. * A single `set()` will generate a single "value" event at the location where
  12618. * the `set()` was performed.
  12619. *
  12620. * @param ref - The location to write to.
  12621. * @param value - The value to be written (string, number, boolean, object,
  12622. * array, or null).
  12623. * @returns Resolves when write to server is complete.
  12624. */
  12625. function set(ref, value) {
  12626. ref = getModularInstance(ref);
  12627. validateWritablePath('set', ref._path);
  12628. validateFirebaseDataArg('set', value, ref._path, false);
  12629. const deferred = new Deferred();
  12630. repoSetWithPriority(ref._repo, ref._path, value,
  12631. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12632. return deferred.promise;
  12633. }
  12634. /**
  12635. * Sets a priority for the data at this Database location.
  12636. *
  12637. * Applications need not use priority but can order collections by
  12638. * ordinary properties (see
  12639. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12640. * ).
  12641. *
  12642. * @param ref - The location to write to.
  12643. * @param priority - The priority to be written (string, number, or null).
  12644. * @returns Resolves when write to server is complete.
  12645. */
  12646. function setPriority(ref, priority) {
  12647. ref = getModularInstance(ref);
  12648. validateWritablePath('setPriority', ref._path);
  12649. validatePriority('setPriority', priority, false);
  12650. const deferred = new Deferred();
  12651. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12652. return deferred.promise;
  12653. }
  12654. /**
  12655. * Writes data the Database location. Like `set()` but also specifies the
  12656. * priority for that data.
  12657. *
  12658. * Applications need not use priority but can order collections by
  12659. * ordinary properties (see
  12660. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12661. * ).
  12662. *
  12663. * @param ref - The location to write to.
  12664. * @param value - The value to be written (string, number, boolean, object,
  12665. * array, or null).
  12666. * @param priority - The priority to be written (string, number, or null).
  12667. * @returns Resolves when write to server is complete.
  12668. */
  12669. function setWithPriority(ref, value, priority) {
  12670. validateWritablePath('setWithPriority', ref._path);
  12671. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12672. validatePriority('setWithPriority', priority, false);
  12673. if (ref.key === '.length' || ref.key === '.keys') {
  12674. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12675. }
  12676. const deferred = new Deferred();
  12677. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12678. return deferred.promise;
  12679. }
  12680. /**
  12681. * Writes multiple values to the Database at once.
  12682. *
  12683. * The `values` argument contains multiple property-value pairs that will be
  12684. * written to the Database together. Each child property can either be a simple
  12685. * property (for example, "name") or a relative path (for example,
  12686. * "name/first") from the current location to the data to update.
  12687. *
  12688. * As opposed to the `set()` method, `update()` can be use to selectively update
  12689. * only the referenced properties at the current location (instead of replacing
  12690. * all the child properties at the current location).
  12691. *
  12692. * The effect of the write will be visible immediately, and the corresponding
  12693. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12694. * the data to the Firebase servers will also be started, and the returned
  12695. * Promise will resolve when complete. If provided, the `onComplete` callback
  12696. * will be called asynchronously after synchronization has finished.
  12697. *
  12698. * A single `update()` will generate a single "value" event at the location
  12699. * where the `update()` was performed, regardless of how many children were
  12700. * modified.
  12701. *
  12702. * Note that modifying data with `update()` will cancel any pending
  12703. * transactions at that location, so extreme care should be taken if mixing
  12704. * `update()` and `transaction()` to modify the same data.
  12705. *
  12706. * Passing `null` to `update()` will remove the data at this location.
  12707. *
  12708. * See
  12709. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12710. *
  12711. * @param ref - The location to write to.
  12712. * @param values - Object containing multiple values.
  12713. * @returns Resolves when update on server is complete.
  12714. */
  12715. function update(ref, values) {
  12716. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12717. const deferred = new Deferred();
  12718. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12719. return deferred.promise;
  12720. }
  12721. /**
  12722. * Gets the most up-to-date result for this query.
  12723. *
  12724. * @param query - The query to run.
  12725. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12726. * available, or rejects if the client is unable to return a value (e.g., if the
  12727. * server is unreachable and there is nothing cached).
  12728. */
  12729. function get(query) {
  12730. query = getModularInstance(query);
  12731. const callbackContext = new CallbackContext(() => { });
  12732. const container = new ValueEventRegistration(callbackContext);
  12733. return repoGetValue(query._repo, query, container).then(node => {
  12734. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12735. });
  12736. }
  12737. /**
  12738. * Represents registration for 'value' events.
  12739. */
  12740. class ValueEventRegistration {
  12741. constructor(callbackContext) {
  12742. this.callbackContext = callbackContext;
  12743. }
  12744. respondsTo(eventType) {
  12745. return eventType === 'value';
  12746. }
  12747. createEvent(change, query) {
  12748. const index = query._queryParams.getIndex();
  12749. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12750. }
  12751. getEventRunner(eventData) {
  12752. if (eventData.getEventType() === 'cancel') {
  12753. return () => this.callbackContext.onCancel(eventData.error);
  12754. }
  12755. else {
  12756. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12757. }
  12758. }
  12759. createCancelEvent(error, path) {
  12760. if (this.callbackContext.hasCancelCallback) {
  12761. return new CancelEvent(this, error, path);
  12762. }
  12763. else {
  12764. return null;
  12765. }
  12766. }
  12767. matches(other) {
  12768. if (!(other instanceof ValueEventRegistration)) {
  12769. return false;
  12770. }
  12771. else if (!other.callbackContext || !this.callbackContext) {
  12772. // If no callback specified, we consider it to match any callback.
  12773. return true;
  12774. }
  12775. else {
  12776. return other.callbackContext.matches(this.callbackContext);
  12777. }
  12778. }
  12779. hasAnyCallback() {
  12780. return this.callbackContext !== null;
  12781. }
  12782. }
  12783. /**
  12784. * Represents the registration of a child_x event.
  12785. */
  12786. class ChildEventRegistration {
  12787. constructor(eventType, callbackContext) {
  12788. this.eventType = eventType;
  12789. this.callbackContext = callbackContext;
  12790. }
  12791. respondsTo(eventType) {
  12792. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12793. eventToCheck =
  12794. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12795. return this.eventType === eventToCheck;
  12796. }
  12797. createCancelEvent(error, path) {
  12798. if (this.callbackContext.hasCancelCallback) {
  12799. return new CancelEvent(this, error, path);
  12800. }
  12801. else {
  12802. return null;
  12803. }
  12804. }
  12805. createEvent(change, query) {
  12806. assert(change.childName != null, 'Child events should have a childName.');
  12807. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12808. const index = query._queryParams.getIndex();
  12809. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12810. }
  12811. getEventRunner(eventData) {
  12812. if (eventData.getEventType() === 'cancel') {
  12813. return () => this.callbackContext.onCancel(eventData.error);
  12814. }
  12815. else {
  12816. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12817. }
  12818. }
  12819. matches(other) {
  12820. if (other instanceof ChildEventRegistration) {
  12821. return (this.eventType === other.eventType &&
  12822. (!this.callbackContext ||
  12823. !other.callbackContext ||
  12824. this.callbackContext.matches(other.callbackContext)));
  12825. }
  12826. return false;
  12827. }
  12828. hasAnyCallback() {
  12829. return !!this.callbackContext;
  12830. }
  12831. }
  12832. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12833. let cancelCallback;
  12834. if (typeof cancelCallbackOrListenOptions === 'object') {
  12835. cancelCallback = undefined;
  12836. options = cancelCallbackOrListenOptions;
  12837. }
  12838. if (typeof cancelCallbackOrListenOptions === 'function') {
  12839. cancelCallback = cancelCallbackOrListenOptions;
  12840. }
  12841. if (options && options.onlyOnce) {
  12842. const userCallback = callback;
  12843. const onceCallback = (dataSnapshot, previousChildName) => {
  12844. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12845. userCallback(dataSnapshot, previousChildName);
  12846. };
  12847. onceCallback.userCallback = callback.userCallback;
  12848. onceCallback.context = callback.context;
  12849. callback = onceCallback;
  12850. }
  12851. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12852. const container = eventType === 'value'
  12853. ? new ValueEventRegistration(callbackContext)
  12854. : new ChildEventRegistration(eventType, callbackContext);
  12855. repoAddEventCallbackForQuery(query._repo, query, container);
  12856. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12857. }
  12858. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12859. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12860. }
  12861. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12862. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12863. }
  12864. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12865. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12866. }
  12867. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12868. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12869. }
  12870. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12871. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12872. }
  12873. /**
  12874. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12875. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12876. * the respective `on*` callbacks.
  12877. *
  12878. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12879. * will not automatically remove listeners registered on child nodes, `off()`
  12880. * must also be called on any child listeners to remove the callback.
  12881. *
  12882. * If a callback is not specified, all callbacks for the specified eventType
  12883. * will be removed. Similarly, if no eventType is specified, all callbacks
  12884. * for the `Reference` will be removed.
  12885. *
  12886. * Individual listeners can also be removed by invoking their unsubscribe
  12887. * callbacks.
  12888. *
  12889. * @param query - The query that the listener was registered with.
  12890. * @param eventType - One of the following strings: "value", "child_added",
  12891. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12892. * for the `Reference` will be removed.
  12893. * @param callback - The callback function that was passed to `on()` or
  12894. * `undefined` to remove all callbacks.
  12895. */
  12896. function off(query, eventType, callback) {
  12897. let container = null;
  12898. const expCallback = callback ? new CallbackContext(callback) : null;
  12899. if (eventType === 'value') {
  12900. container = new ValueEventRegistration(expCallback);
  12901. }
  12902. else if (eventType) {
  12903. container = new ChildEventRegistration(eventType, expCallback);
  12904. }
  12905. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12906. }
  12907. /**
  12908. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12909. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12910. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12911. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12912. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12913. * {@link orderByValue} or {@link equalTo} and
  12914. * can then be passed to {@link query} to create a new query instance that
  12915. * also contains this `QueryConstraint`.
  12916. */
  12917. class QueryConstraint {
  12918. }
  12919. class QueryEndAtConstraint extends QueryConstraint {
  12920. constructor(_value, _key) {
  12921. super();
  12922. this._value = _value;
  12923. this._key = _key;
  12924. }
  12925. _apply(query) {
  12926. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12927. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12928. validateLimit(newParams);
  12929. validateQueryEndpoints(newParams);
  12930. if (query._queryParams.hasEnd()) {
  12931. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12932. 'endBefore or equalTo).');
  12933. }
  12934. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12935. }
  12936. }
  12937. /**
  12938. * Creates a `QueryConstraint` with the specified ending point.
  12939. *
  12940. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12941. * allows you to choose arbitrary starting and ending points for your queries.
  12942. *
  12943. * The ending point is inclusive, so children with exactly the specified value
  12944. * will be included in the query. The optional key argument can be used to
  12945. * further limit the range of the query. If it is specified, then children that
  12946. * have exactly the specified value must also have a key name less than or equal
  12947. * to the specified key.
  12948. *
  12949. * You can read more about `endAt()` in
  12950. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12951. *
  12952. * @param value - The value to end at. The argument type depends on which
  12953. * `orderBy*()` function was used in this query. Specify a value that matches
  12954. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12955. * value must be a string.
  12956. * @param key - The child key to end at, among the children with the previously
  12957. * specified priority. This argument is only allowed if ordering by child,
  12958. * value, or priority.
  12959. */
  12960. function endAt(value, key) {
  12961. validateKey('endAt', 'key', key, true);
  12962. return new QueryEndAtConstraint(value, key);
  12963. }
  12964. class QueryEndBeforeConstraint extends QueryConstraint {
  12965. constructor(_value, _key) {
  12966. super();
  12967. this._value = _value;
  12968. this._key = _key;
  12969. }
  12970. _apply(query) {
  12971. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12972. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12973. validateLimit(newParams);
  12974. validateQueryEndpoints(newParams);
  12975. if (query._queryParams.hasEnd()) {
  12976. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12977. 'endBefore or equalTo).');
  12978. }
  12979. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12980. }
  12981. }
  12982. /**
  12983. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12984. *
  12985. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12986. * allows you to choose arbitrary starting and ending points for your queries.
  12987. *
  12988. * The ending point is exclusive. If only a value is provided, children
  12989. * with a value less than the specified value will be included in the query.
  12990. * If a key is specified, then children must have a value less than or equal
  12991. * to the specified value and a key name less than the specified key.
  12992. *
  12993. * @param value - The value to end before. The argument type depends on which
  12994. * `orderBy*()` function was used in this query. Specify a value that matches
  12995. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12996. * value must be a string.
  12997. * @param key - The child key to end before, among the children with the
  12998. * previously specified priority. This argument is only allowed if ordering by
  12999. * child, value, or priority.
  13000. */
  13001. function endBefore(value, key) {
  13002. validateKey('endBefore', 'key', key, true);
  13003. return new QueryEndBeforeConstraint(value, key);
  13004. }
  13005. class QueryStartAtConstraint extends QueryConstraint {
  13006. constructor(_value, _key) {
  13007. super();
  13008. this._value = _value;
  13009. this._key = _key;
  13010. }
  13011. _apply(query) {
  13012. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13013. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13014. validateLimit(newParams);
  13015. validateQueryEndpoints(newParams);
  13016. if (query._queryParams.hasStart()) {
  13017. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13018. 'startBefore or equalTo).');
  13019. }
  13020. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13021. }
  13022. }
  13023. /**
  13024. * Creates a `QueryConstraint` with the specified starting point.
  13025. *
  13026. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13027. * allows you to choose arbitrary starting and ending points for your queries.
  13028. *
  13029. * The starting point is inclusive, so children with exactly the specified value
  13030. * will be included in the query. The optional key argument can be used to
  13031. * further limit the range of the query. If it is specified, then children that
  13032. * have exactly the specified value must also have a key name greater than or
  13033. * equal to the specified key.
  13034. *
  13035. * You can read more about `startAt()` in
  13036. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13037. *
  13038. * @param value - The value to start at. The argument type depends on which
  13039. * `orderBy*()` function was used in this query. Specify a value that matches
  13040. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13041. * value must be a string.
  13042. * @param key - The child key to start at. This argument is only allowed if
  13043. * ordering by child, value, or priority.
  13044. */
  13045. function startAt(value = null, key) {
  13046. validateKey('startAt', 'key', key, true);
  13047. return new QueryStartAtConstraint(value, key);
  13048. }
  13049. class QueryStartAfterConstraint extends QueryConstraint {
  13050. constructor(_value, _key) {
  13051. super();
  13052. this._value = _value;
  13053. this._key = _key;
  13054. }
  13055. _apply(query) {
  13056. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13057. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13058. validateLimit(newParams);
  13059. validateQueryEndpoints(newParams);
  13060. if (query._queryParams.hasStart()) {
  13061. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13062. 'startAfter, or equalTo).');
  13063. }
  13064. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13065. }
  13066. }
  13067. /**
  13068. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13069. *
  13070. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13071. * allows you to choose arbitrary starting and ending points for your queries.
  13072. *
  13073. * The starting point is exclusive. If only a value is provided, children
  13074. * with a value greater than the specified value will be included in the query.
  13075. * If a key is specified, then children must have a value greater than or equal
  13076. * to the specified value and a a key name greater than the specified key.
  13077. *
  13078. * @param value - The value to start after. The argument type depends on which
  13079. * `orderBy*()` function was used in this query. Specify a value that matches
  13080. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13081. * value must be a string.
  13082. * @param key - The child key to start after. This argument is only allowed if
  13083. * ordering by child, value, or priority.
  13084. */
  13085. function startAfter(value, key) {
  13086. validateKey('startAfter', 'key', key, true);
  13087. return new QueryStartAfterConstraint(value, key);
  13088. }
  13089. class QueryLimitToFirstConstraint extends QueryConstraint {
  13090. constructor(_limit) {
  13091. super();
  13092. this._limit = _limit;
  13093. }
  13094. _apply(query) {
  13095. if (query._queryParams.hasLimit()) {
  13096. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13097. 'or limitToLast).');
  13098. }
  13099. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13100. }
  13101. }
  13102. /**
  13103. * Creates a new `QueryConstraint` that if limited to the first specific number
  13104. * of children.
  13105. *
  13106. * The `limitToFirst()` method is used to set a maximum number of children to be
  13107. * synced for a given callback. If we set a limit of 100, we will initially only
  13108. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13109. * stored in our Database, a `child_added` event will fire for each message.
  13110. * However, if we have over 100 messages, we will only receive a `child_added`
  13111. * event for the first 100 ordered messages. As items change, we will receive
  13112. * `child_removed` events for each item that drops out of the active list so
  13113. * that the total number stays at 100.
  13114. *
  13115. * You can read more about `limitToFirst()` in
  13116. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13117. *
  13118. * @param limit - The maximum number of nodes to include in this query.
  13119. */
  13120. function limitToFirst(limit) {
  13121. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13122. throw new Error('limitToFirst: First argument must be a positive integer.');
  13123. }
  13124. return new QueryLimitToFirstConstraint(limit);
  13125. }
  13126. class QueryLimitToLastConstraint extends QueryConstraint {
  13127. constructor(_limit) {
  13128. super();
  13129. this._limit = _limit;
  13130. }
  13131. _apply(query) {
  13132. if (query._queryParams.hasLimit()) {
  13133. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13134. 'or limitToLast).');
  13135. }
  13136. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13137. }
  13138. }
  13139. /**
  13140. * Creates a new `QueryConstraint` that is limited to return only the last
  13141. * specified number of children.
  13142. *
  13143. * The `limitToLast()` method is used to set a maximum number of children to be
  13144. * synced for a given callback. If we set a limit of 100, we will initially only
  13145. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13146. * stored in our Database, a `child_added` event will fire for each message.
  13147. * However, if we have over 100 messages, we will only receive a `child_added`
  13148. * event for the last 100 ordered messages. As items change, we will receive
  13149. * `child_removed` events for each item that drops out of the active list so
  13150. * that the total number stays at 100.
  13151. *
  13152. * You can read more about `limitToLast()` in
  13153. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13154. *
  13155. * @param limit - The maximum number of nodes to include in this query.
  13156. */
  13157. function limitToLast(limit) {
  13158. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13159. throw new Error('limitToLast: First argument must be a positive integer.');
  13160. }
  13161. return new QueryLimitToLastConstraint(limit);
  13162. }
  13163. class QueryOrderByChildConstraint extends QueryConstraint {
  13164. constructor(_path) {
  13165. super();
  13166. this._path = _path;
  13167. }
  13168. _apply(query) {
  13169. validateNoPreviousOrderByCall(query, 'orderByChild');
  13170. const parsedPath = new Path(this._path);
  13171. if (pathIsEmpty(parsedPath)) {
  13172. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13173. }
  13174. const index = new PathIndex(parsedPath);
  13175. const newParams = queryParamsOrderBy(query._queryParams, index);
  13176. validateQueryEndpoints(newParams);
  13177. return new QueryImpl(query._repo, query._path, newParams,
  13178. /*orderByCalled=*/ true);
  13179. }
  13180. }
  13181. /**
  13182. * Creates a new `QueryConstraint` that orders by the specified child key.
  13183. *
  13184. * Queries can only order by one key at a time. Calling `orderByChild()`
  13185. * multiple times on the same query is an error.
  13186. *
  13187. * Firebase queries allow you to order your data by any child key on the fly.
  13188. * However, if you know in advance what your indexes will be, you can define
  13189. * them via the .indexOn rule in your Security Rules for better performance. See
  13190. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13191. * rule for more information.
  13192. *
  13193. * You can read more about `orderByChild()` in
  13194. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13195. *
  13196. * @param path - The path to order by.
  13197. */
  13198. function orderByChild(path) {
  13199. if (path === '$key') {
  13200. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13201. }
  13202. else if (path === '$priority') {
  13203. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13204. }
  13205. else if (path === '$value') {
  13206. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13207. }
  13208. validatePathString('orderByChild', 'path', path, false);
  13209. return new QueryOrderByChildConstraint(path);
  13210. }
  13211. class QueryOrderByKeyConstraint extends QueryConstraint {
  13212. _apply(query) {
  13213. validateNoPreviousOrderByCall(query, 'orderByKey');
  13214. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13215. validateQueryEndpoints(newParams);
  13216. return new QueryImpl(query._repo, query._path, newParams,
  13217. /*orderByCalled=*/ true);
  13218. }
  13219. }
  13220. /**
  13221. * Creates a new `QueryConstraint` that orders by the key.
  13222. *
  13223. * Sorts the results of a query by their (ascending) key values.
  13224. *
  13225. * You can read more about `orderByKey()` in
  13226. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13227. */
  13228. function orderByKey() {
  13229. return new QueryOrderByKeyConstraint();
  13230. }
  13231. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13232. _apply(query) {
  13233. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13234. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13235. validateQueryEndpoints(newParams);
  13236. return new QueryImpl(query._repo, query._path, newParams,
  13237. /*orderByCalled=*/ true);
  13238. }
  13239. }
  13240. /**
  13241. * Creates a new `QueryConstraint` that orders by priority.
  13242. *
  13243. * Applications need not use priority but can order collections by
  13244. * ordinary properties (see
  13245. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13246. * for alternatives to priority.
  13247. */
  13248. function orderByPriority() {
  13249. return new QueryOrderByPriorityConstraint();
  13250. }
  13251. class QueryOrderByValueConstraint extends QueryConstraint {
  13252. _apply(query) {
  13253. validateNoPreviousOrderByCall(query, 'orderByValue');
  13254. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13255. validateQueryEndpoints(newParams);
  13256. return new QueryImpl(query._repo, query._path, newParams,
  13257. /*orderByCalled=*/ true);
  13258. }
  13259. }
  13260. /**
  13261. * Creates a new `QueryConstraint` that orders by value.
  13262. *
  13263. * If the children of a query are all scalar values (string, number, or
  13264. * boolean), you can order the results by their (ascending) values.
  13265. *
  13266. * You can read more about `orderByValue()` in
  13267. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13268. */
  13269. function orderByValue() {
  13270. return new QueryOrderByValueConstraint();
  13271. }
  13272. class QueryEqualToValueConstraint extends QueryConstraint {
  13273. constructor(_value, _key) {
  13274. super();
  13275. this._value = _value;
  13276. this._key = _key;
  13277. }
  13278. _apply(query) {
  13279. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13280. if (query._queryParams.hasStart()) {
  13281. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13282. 'equalTo).');
  13283. }
  13284. if (query._queryParams.hasEnd()) {
  13285. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13286. 'equalTo).');
  13287. }
  13288. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13289. }
  13290. }
  13291. /**
  13292. * Creates a `QueryConstraint` that includes children that match the specified
  13293. * value.
  13294. *
  13295. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13296. * allows you to choose arbitrary starting and ending points for your queries.
  13297. *
  13298. * The optional key argument can be used to further limit the range of the
  13299. * query. If it is specified, then children that have exactly the specified
  13300. * value must also have exactly the specified key as their key name. This can be
  13301. * used to filter result sets with many matches for the same value.
  13302. *
  13303. * You can read more about `equalTo()` in
  13304. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13305. *
  13306. * @param value - The value to match for. The argument type depends on which
  13307. * `orderBy*()` function was used in this query. Specify a value that matches
  13308. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13309. * value must be a string.
  13310. * @param key - The child key to start at, among the children with the
  13311. * previously specified priority. This argument is only allowed if ordering by
  13312. * child, value, or priority.
  13313. */
  13314. function equalTo(value, key) {
  13315. validateKey('equalTo', 'key', key, true);
  13316. return new QueryEqualToValueConstraint(value, key);
  13317. }
  13318. /**
  13319. * Creates a new immutable instance of `Query` that is extended to also include
  13320. * additional query constraints.
  13321. *
  13322. * @param query - The Query instance to use as a base for the new constraints.
  13323. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13324. * @throws if any of the provided query constraints cannot be combined with the
  13325. * existing or new constraints.
  13326. */
  13327. function query(query, ...queryConstraints) {
  13328. let queryImpl = getModularInstance(query);
  13329. for (const constraint of queryConstraints) {
  13330. queryImpl = constraint._apply(queryImpl);
  13331. }
  13332. return queryImpl;
  13333. }
  13334. /**
  13335. * Define reference constructor in various modules
  13336. *
  13337. * We are doing this here to avoid several circular
  13338. * dependency issues
  13339. */
  13340. syncPointSetReferenceConstructor(ReferenceImpl);
  13341. syncTreeSetReferenceConstructor(ReferenceImpl);
  13342. /**
  13343. * @license
  13344. * Copyright 2020 Google LLC
  13345. *
  13346. * Licensed under the Apache License, Version 2.0 (the "License");
  13347. * you may not use this file except in compliance with the License.
  13348. * You may obtain a copy of the License at
  13349. *
  13350. * http://www.apache.org/licenses/LICENSE-2.0
  13351. *
  13352. * Unless required by applicable law or agreed to in writing, software
  13353. * distributed under the License is distributed on an "AS IS" BASIS,
  13354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13355. * See the License for the specific language governing permissions and
  13356. * limitations under the License.
  13357. */
  13358. /**
  13359. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13360. * modifying this definition, consult the definition in:
  13361. *
  13362. * https://github.com/firebase/firebase-admin-node
  13363. *
  13364. * and make sure the two are consistent.
  13365. */
  13366. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13367. /**
  13368. * Creates and caches `Repo` instances.
  13369. */
  13370. const repos = {};
  13371. /**
  13372. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13373. */
  13374. let useRestClient = false;
  13375. /**
  13376. * Update an existing `Repo` in place to point to a new host/port.
  13377. */
  13378. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13379. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13380. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  13381. if (tokenProvider) {
  13382. repo.authTokenProvider_ = tokenProvider;
  13383. }
  13384. }
  13385. /**
  13386. * This function should only ever be called to CREATE a new database instance.
  13387. * @internal
  13388. */
  13389. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13390. let dbUrl = url || app.options.databaseURL;
  13391. if (dbUrl === undefined) {
  13392. if (!app.options.projectId) {
  13393. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13394. ' a Project ID when calling firebase.initializeApp().');
  13395. }
  13396. log('Using default host for project ', app.options.projectId);
  13397. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13398. }
  13399. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13400. let repoInfo = parsedUrl.repoInfo;
  13401. let isEmulator;
  13402. let dbEmulatorHost = undefined;
  13403. if (typeof process !== 'undefined' && process.env) {
  13404. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13405. }
  13406. if (dbEmulatorHost) {
  13407. isEmulator = true;
  13408. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13409. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13410. repoInfo = parsedUrl.repoInfo;
  13411. }
  13412. else {
  13413. isEmulator = !parsedUrl.repoInfo.secure;
  13414. }
  13415. const authTokenProvider = nodeAdmin && isEmulator
  13416. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13417. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13418. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13419. if (!pathIsEmpty(parsedUrl.path)) {
  13420. fatal('Database URL must point to the root of a Firebase Database ' +
  13421. '(not including a child path).');
  13422. }
  13423. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13424. return new Database(repo, app);
  13425. }
  13426. /**
  13427. * Remove the repo and make sure it is disconnected.
  13428. *
  13429. */
  13430. function repoManagerDeleteRepo(repo, appName) {
  13431. const appRepos = repos[appName];
  13432. // This should never happen...
  13433. if (!appRepos || appRepos[repo.key] !== repo) {
  13434. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13435. }
  13436. repoInterrupt(repo);
  13437. delete appRepos[repo.key];
  13438. }
  13439. /**
  13440. * Ensures a repo doesn't already exist and then creates one using the
  13441. * provided app.
  13442. *
  13443. * @param repoInfo - The metadata about the Repo
  13444. * @returns The Repo object for the specified server / repoName.
  13445. */
  13446. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13447. let appRepos = repos[app.name];
  13448. if (!appRepos) {
  13449. appRepos = {};
  13450. repos[app.name] = appRepos;
  13451. }
  13452. let repo = appRepos[repoInfo.toURLString()];
  13453. if (repo) {
  13454. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13455. }
  13456. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13457. appRepos[repoInfo.toURLString()] = repo;
  13458. return repo;
  13459. }
  13460. /**
  13461. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13462. */
  13463. function repoManagerForceRestClient(forceRestClient) {
  13464. useRestClient = forceRestClient;
  13465. }
  13466. /**
  13467. * Class representing a Firebase Realtime Database.
  13468. */
  13469. class Database {
  13470. /** @hideconstructor */
  13471. constructor(_repoInternal,
  13472. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13473. app) {
  13474. this._repoInternal = _repoInternal;
  13475. this.app = app;
  13476. /** Represents a `Database` instance. */
  13477. this['type'] = 'database';
  13478. /** Track if the instance has been used (root or repo accessed) */
  13479. this._instanceStarted = false;
  13480. }
  13481. get _repo() {
  13482. if (!this._instanceStarted) {
  13483. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13484. this._instanceStarted = true;
  13485. }
  13486. return this._repoInternal;
  13487. }
  13488. get _root() {
  13489. if (!this._rootInternal) {
  13490. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13491. }
  13492. return this._rootInternal;
  13493. }
  13494. _delete() {
  13495. if (this._rootInternal !== null) {
  13496. repoManagerDeleteRepo(this._repo, this.app.name);
  13497. this._repoInternal = null;
  13498. this._rootInternal = null;
  13499. }
  13500. return Promise.resolve();
  13501. }
  13502. _checkNotDeleted(apiName) {
  13503. if (this._rootInternal === null) {
  13504. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13505. }
  13506. }
  13507. }
  13508. function checkTransportInit() {
  13509. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13510. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13511. }
  13512. }
  13513. /**
  13514. * Force the use of websockets instead of longPolling.
  13515. */
  13516. function forceWebSockets() {
  13517. checkTransportInit();
  13518. BrowserPollConnection.forceDisallow();
  13519. }
  13520. /**
  13521. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13522. */
  13523. function forceLongPolling() {
  13524. checkTransportInit();
  13525. WebSocketConnection.forceDisallow();
  13526. BrowserPollConnection.forceAllow();
  13527. }
  13528. /**
  13529. * Returns the instance of the Realtime Database SDK that is associated
  13530. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  13531. * with default settings if no instance exists or if the existing instance uses
  13532. * a custom database URL.
  13533. *
  13534. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13535. * Database instance is associated with.
  13536. * @param url - The URL of the Realtime Database instance to connect to. If not
  13537. * provided, the SDK connects to the default instance of the Firebase App.
  13538. * @returns The `Database` instance of the provided app.
  13539. */
  13540. function getDatabase(app = getApp(), url) {
  13541. const db = _getProvider(app, 'database').getImmediate({
  13542. identifier: url
  13543. });
  13544. if (!db._instanceStarted) {
  13545. const emulator = getDefaultEmulatorHostnameAndPort('database');
  13546. if (emulator) {
  13547. connectDatabaseEmulator(db, ...emulator);
  13548. }
  13549. }
  13550. return db;
  13551. }
  13552. /**
  13553. * Modify the provided instance to communicate with the Realtime Database
  13554. * emulator.
  13555. *
  13556. * <p>Note: This method must be called before performing any other operation.
  13557. *
  13558. * @param db - The instance to modify.
  13559. * @param host - The emulator host (ex: localhost)
  13560. * @param port - The emulator port (ex: 8080)
  13561. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13562. */
  13563. function connectDatabaseEmulator(db, host, port, options = {}) {
  13564. db = getModularInstance(db);
  13565. db._checkNotDeleted('useEmulator');
  13566. if (db._instanceStarted) {
  13567. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13568. }
  13569. const repo = db._repoInternal;
  13570. let tokenProvider = undefined;
  13571. if (repo.repoInfo_.nodeAdmin) {
  13572. if (options.mockUserToken) {
  13573. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13574. }
  13575. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13576. }
  13577. else if (options.mockUserToken) {
  13578. const token = typeof options.mockUserToken === 'string'
  13579. ? options.mockUserToken
  13580. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13581. tokenProvider = new EmulatorTokenProvider(token);
  13582. }
  13583. // Modify the repo to apply emulator settings
  13584. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13585. }
  13586. /**
  13587. * Disconnects from the server (all Database operations will be completed
  13588. * offline).
  13589. *
  13590. * The client automatically maintains a persistent connection to the Database
  13591. * server, which will remain active indefinitely and reconnect when
  13592. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13593. * to control the client connection in cases where a persistent connection is
  13594. * undesirable.
  13595. *
  13596. * While offline, the client will no longer receive data updates from the
  13597. * Database. However, all Database operations performed locally will continue to
  13598. * immediately fire events, allowing your application to continue behaving
  13599. * normally. Additionally, each operation performed locally will automatically
  13600. * be queued and retried upon reconnection to the Database server.
  13601. *
  13602. * To reconnect to the Database and begin receiving remote events, see
  13603. * `goOnline()`.
  13604. *
  13605. * @param db - The instance to disconnect.
  13606. */
  13607. function goOffline(db) {
  13608. db = getModularInstance(db);
  13609. db._checkNotDeleted('goOffline');
  13610. repoInterrupt(db._repo);
  13611. }
  13612. /**
  13613. * Reconnects to the server and synchronizes the offline Database state
  13614. * with the server state.
  13615. *
  13616. * This method should be used after disabling the active connection with
  13617. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13618. * and fire the appropriate events so that your client "catches up"
  13619. * automatically.
  13620. *
  13621. * @param db - The instance to reconnect.
  13622. */
  13623. function goOnline(db) {
  13624. db = getModularInstance(db);
  13625. db._checkNotDeleted('goOnline');
  13626. repoResume(db._repo);
  13627. }
  13628. function enableLogging(logger, persistent) {
  13629. enableLogging$1(logger, persistent);
  13630. }
  13631. /**
  13632. * @license
  13633. * Copyright 2021 Google LLC
  13634. *
  13635. * Licensed under the Apache License, Version 2.0 (the "License");
  13636. * you may not use this file except in compliance with the License.
  13637. * You may obtain a copy of the License at
  13638. *
  13639. * http://www.apache.org/licenses/LICENSE-2.0
  13640. *
  13641. * Unless required by applicable law or agreed to in writing, software
  13642. * distributed under the License is distributed on an "AS IS" BASIS,
  13643. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13644. * See the License for the specific language governing permissions and
  13645. * limitations under the License.
  13646. */
  13647. function registerDatabase(variant) {
  13648. setSDKVersion(SDK_VERSION$1);
  13649. _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
  13650. const app = container.getProvider('app').getImmediate();
  13651. const authProvider = container.getProvider('auth-internal');
  13652. const appCheckProvider = container.getProvider('app-check-internal');
  13653. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13654. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13655. registerVersion(name, version, variant);
  13656. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  13657. registerVersion(name, version, 'esm2017');
  13658. }
  13659. /**
  13660. * @license
  13661. * Copyright 2020 Google LLC
  13662. *
  13663. * Licensed under the Apache License, Version 2.0 (the "License");
  13664. * you may not use this file except in compliance with the License.
  13665. * You may obtain a copy of the License at
  13666. *
  13667. * http://www.apache.org/licenses/LICENSE-2.0
  13668. *
  13669. * Unless required by applicable law or agreed to in writing, software
  13670. * distributed under the License is distributed on an "AS IS" BASIS,
  13671. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13672. * See the License for the specific language governing permissions and
  13673. * limitations under the License.
  13674. */
  13675. const SERVER_TIMESTAMP = {
  13676. '.sv': 'timestamp'
  13677. };
  13678. /**
  13679. * Returns a placeholder value for auto-populating the current timestamp (time
  13680. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13681. * servers.
  13682. */
  13683. function serverTimestamp() {
  13684. return SERVER_TIMESTAMP;
  13685. }
  13686. /**
  13687. * Returns a placeholder value that can be used to atomically increment the
  13688. * current database value by the provided delta.
  13689. *
  13690. * @param delta - the amount to modify the current value atomically.
  13691. * @returns A placeholder value for modifying data atomically server-side.
  13692. */
  13693. function increment(delta) {
  13694. return {
  13695. '.sv': {
  13696. 'increment': delta
  13697. }
  13698. };
  13699. }
  13700. /**
  13701. * @license
  13702. * Copyright 2020 Google LLC
  13703. *
  13704. * Licensed under the Apache License, Version 2.0 (the "License");
  13705. * you may not use this file except in compliance with the License.
  13706. * You may obtain a copy of the License at
  13707. *
  13708. * http://www.apache.org/licenses/LICENSE-2.0
  13709. *
  13710. * Unless required by applicable law or agreed to in writing, software
  13711. * distributed under the License is distributed on an "AS IS" BASIS,
  13712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13713. * See the License for the specific language governing permissions and
  13714. * limitations under the License.
  13715. */
  13716. /**
  13717. * A type for the resolve value of {@link runTransaction}.
  13718. */
  13719. class TransactionResult {
  13720. /** @hideconstructor */
  13721. constructor(
  13722. /** Whether the transaction was successfully committed. */
  13723. committed,
  13724. /** The resulting data snapshot. */
  13725. snapshot) {
  13726. this.committed = committed;
  13727. this.snapshot = snapshot;
  13728. }
  13729. /** Returns a JSON-serializable representation of this object. */
  13730. toJSON() {
  13731. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13732. }
  13733. }
  13734. /**
  13735. * Atomically modifies the data at this location.
  13736. *
  13737. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13738. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13739. * used to modify the existing value to a new value, ensuring there are no
  13740. * conflicts with other clients writing to the same location at the same time.
  13741. *
  13742. * To accomplish this, you pass `runTransaction()` an update function which is
  13743. * used to transform the current value into a new value. If another client
  13744. * writes to the location before your new value is successfully written, your
  13745. * update function will be called again with the new current value, and the
  13746. * write will be retried. This will happen repeatedly until your write succeeds
  13747. * without conflict or you abort the transaction by not returning a value from
  13748. * your update function.
  13749. *
  13750. * Note: Modifying data with `set()` will cancel any pending transactions at
  13751. * that location, so extreme care should be taken if mixing `set()` and
  13752. * `runTransaction()` to update the same data.
  13753. *
  13754. * Note: When using transactions with Security and Firebase Rules in place, be
  13755. * aware that a client needs `.read` access in addition to `.write` access in
  13756. * order to perform a transaction. This is because the client-side nature of
  13757. * transactions requires the client to read the data in order to transactionally
  13758. * update it.
  13759. *
  13760. * @param ref - The location to atomically modify.
  13761. * @param transactionUpdate - A developer-supplied function which will be passed
  13762. * the current data stored at this location (as a JavaScript object). The
  13763. * function should return the new value it would like written (as a JavaScript
  13764. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13765. * transaction will be aborted and the data at this location will not be
  13766. * modified.
  13767. * @param options - An options object to configure transactions.
  13768. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13769. * callback to handle success and failure.
  13770. */
  13771. function runTransaction(ref,
  13772. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13773. transactionUpdate, options) {
  13774. var _a;
  13775. ref = getModularInstance(ref);
  13776. validateWritablePath('Reference.transaction', ref._path);
  13777. if (ref.key === '.length' || ref.key === '.keys') {
  13778. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13779. }
  13780. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13781. const deferred = new Deferred();
  13782. const promiseComplete = (error, committed, node) => {
  13783. let dataSnapshot = null;
  13784. if (error) {
  13785. deferred.reject(error);
  13786. }
  13787. else {
  13788. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13789. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13790. }
  13791. };
  13792. // Add a watch to make sure we get server updates.
  13793. const unwatcher = onValue(ref, () => { });
  13794. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13795. return deferred.promise;
  13796. }
  13797. /**
  13798. * @license
  13799. * Copyright 2017 Google LLC
  13800. *
  13801. * Licensed under the Apache License, Version 2.0 (the "License");
  13802. * you may not use this file except in compliance with the License.
  13803. * You may obtain a copy of the License at
  13804. *
  13805. * http://www.apache.org/licenses/LICENSE-2.0
  13806. *
  13807. * Unless required by applicable law or agreed to in writing, software
  13808. * distributed under the License is distributed on an "AS IS" BASIS,
  13809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13810. * See the License for the specific language governing permissions and
  13811. * limitations under the License.
  13812. */
  13813. PersistentConnection;
  13814. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13815. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13816. this.sendRequest('q', { p: pathString }, onComplete);
  13817. };
  13818. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13819. PersistentConnection.prototype.echo = function (data, onEcho) {
  13820. this.sendRequest('echo', { d: data }, onEcho);
  13821. };
  13822. // RealTimeConnection properties that we use in tests.
  13823. Connection;
  13824. /**
  13825. * @internal
  13826. */
  13827. const hijackHash = function (newHash) {
  13828. const oldPut = PersistentConnection.prototype.put;
  13829. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13830. if (hash !== undefined) {
  13831. hash = newHash();
  13832. }
  13833. oldPut.call(this, pathString, data, onComplete, hash);
  13834. };
  13835. return function () {
  13836. PersistentConnection.prototype.put = oldPut;
  13837. };
  13838. };
  13839. RepoInfo;
  13840. /**
  13841. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13842. * @internal
  13843. */
  13844. const forceRestClient = function (forceRestClient) {
  13845. repoManagerForceRestClient(forceRestClient);
  13846. };
  13847. /**
  13848. * Firebase Realtime Database
  13849. *
  13850. * @packageDocumentation
  13851. */
  13852. registerDatabase();
  13853. export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
  13854. //# sourceMappingURL=index.esm2017.js.map