index.cjs.js 539 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var app = require('@firebase/app');
  4. var component = require('@firebase/component');
  5. var util = require('@firebase/util');
  6. var logger$1 = require('@firebase/logger');
  7. const name = "@firebase/database";
  8. const version = "1.0.9";
  9. /**
  10. * @license
  11. * Copyright 2019 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. /** The semver (www.semver.org) version of the SDK. */
  26. let SDK_VERSION = '';
  27. /**
  28. * SDK_VERSION should be set before any database instance is created
  29. * @internal
  30. */
  31. function setSDKVersion(version) {
  32. SDK_VERSION = version;
  33. }
  34. /**
  35. * @license
  36. * Copyright 2017 Google LLC
  37. *
  38. * Licensed under the Apache License, Version 2.0 (the "License");
  39. * you may not use this file except in compliance with the License.
  40. * You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing, software
  45. * distributed under the License is distributed on an "AS IS" BASIS,
  46. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  47. * See the License for the specific language governing permissions and
  48. * limitations under the License.
  49. */
  50. /**
  51. * Wraps a DOM Storage object and:
  52. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  53. * - prefixes names with "firebase:" to avoid collisions with app data.
  54. *
  55. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  56. * and one for localStorage.
  57. *
  58. */
  59. class DOMStorageWrapper {
  60. /**
  61. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  62. */
  63. constructor(domStorage_) {
  64. this.domStorage_ = domStorage_;
  65. // Use a prefix to avoid collisions with other stuff saved by the app.
  66. this.prefix_ = 'firebase:';
  67. }
  68. /**
  69. * @param key - The key to save the value under
  70. * @param value - The value being stored, or null to remove the key.
  71. */
  72. set(key, value) {
  73. if (value == null) {
  74. this.domStorage_.removeItem(this.prefixedName_(key));
  75. }
  76. else {
  77. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  78. }
  79. }
  80. /**
  81. * @returns The value that was stored under this key, or null
  82. */
  83. get(key) {
  84. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  85. if (storedVal == null) {
  86. return null;
  87. }
  88. else {
  89. return util.jsonEval(storedVal);
  90. }
  91. }
  92. remove(key) {
  93. this.domStorage_.removeItem(this.prefixedName_(key));
  94. }
  95. prefixedName_(name) {
  96. return this.prefix_ + name;
  97. }
  98. toString() {
  99. return this.domStorage_.toString();
  100. }
  101. }
  102. /**
  103. * @license
  104. * Copyright 2017 Google LLC
  105. *
  106. * Licensed under the Apache License, Version 2.0 (the "License");
  107. * you may not use this file except in compliance with the License.
  108. * You may obtain a copy of the License at
  109. *
  110. * http://www.apache.org/licenses/LICENSE-2.0
  111. *
  112. * Unless required by applicable law or agreed to in writing, software
  113. * distributed under the License is distributed on an "AS IS" BASIS,
  114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  115. * See the License for the specific language governing permissions and
  116. * limitations under the License.
  117. */
  118. /**
  119. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  120. * (TODO: create interface for both to implement).
  121. */
  122. class MemoryStorage {
  123. constructor() {
  124. this.cache_ = {};
  125. this.isInMemoryStorage = true;
  126. }
  127. set(key, value) {
  128. if (value == null) {
  129. delete this.cache_[key];
  130. }
  131. else {
  132. this.cache_[key] = value;
  133. }
  134. }
  135. get(key) {
  136. if (util.contains(this.cache_, key)) {
  137. return this.cache_[key];
  138. }
  139. return null;
  140. }
  141. remove(key) {
  142. delete this.cache_[key];
  143. }
  144. }
  145. /**
  146. * @license
  147. * Copyright 2017 Google LLC
  148. *
  149. * Licensed under the Apache License, Version 2.0 (the "License");
  150. * you may not use this file except in compliance with the License.
  151. * You may obtain a copy of the License at
  152. *
  153. * http://www.apache.org/licenses/LICENSE-2.0
  154. *
  155. * Unless required by applicable law or agreed to in writing, software
  156. * distributed under the License is distributed on an "AS IS" BASIS,
  157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  158. * See the License for the specific language governing permissions and
  159. * limitations under the License.
  160. */
  161. /**
  162. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  163. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  164. * to reflect this type
  165. *
  166. * @param domStorageName - Name of the underlying storage object
  167. * (e.g. 'localStorage' or 'sessionStorage').
  168. * @returns Turning off type information until a common interface is defined.
  169. */
  170. const createStoragefor = function (domStorageName) {
  171. try {
  172. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  173. // so it must be inside the try/catch.
  174. if (typeof window !== 'undefined' &&
  175. typeof window[domStorageName] !== 'undefined') {
  176. // Need to test cache. Just because it's here doesn't mean it works
  177. const domStorage = window[domStorageName];
  178. domStorage.setItem('firebase:sentinel', 'cache');
  179. domStorage.removeItem('firebase:sentinel');
  180. return new DOMStorageWrapper(domStorage);
  181. }
  182. }
  183. catch (e) { }
  184. // Failed to create wrapper. Just return in-memory storage.
  185. // TODO: log?
  186. return new MemoryStorage();
  187. };
  188. /** A storage object that lasts across sessions */
  189. const PersistentStorage = createStoragefor('localStorage');
  190. /** A storage object that only lasts one session */
  191. const SessionStorage = createStoragefor('sessionStorage');
  192. /**
  193. * @license
  194. * Copyright 2017 Google LLC
  195. *
  196. * Licensed under the Apache License, Version 2.0 (the "License");
  197. * you may not use this file except in compliance with the License.
  198. * You may obtain a copy of the License at
  199. *
  200. * http://www.apache.org/licenses/LICENSE-2.0
  201. *
  202. * Unless required by applicable law or agreed to in writing, software
  203. * distributed under the License is distributed on an "AS IS" BASIS,
  204. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  205. * See the License for the specific language governing permissions and
  206. * limitations under the License.
  207. */
  208. const logClient = new logger$1.Logger('@firebase/database');
  209. /**
  210. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  211. */
  212. const LUIDGenerator = (function () {
  213. let id = 1;
  214. return function () {
  215. return id++;
  216. };
  217. })();
  218. /**
  219. * Sha1 hash of the input string
  220. * @param str - The string to hash
  221. * @returns {!string} The resulting hash
  222. */
  223. const sha1 = function (str) {
  224. const utf8Bytes = util.stringToByteArray(str);
  225. const sha1 = new util.Sha1();
  226. sha1.update(utf8Bytes);
  227. const sha1Bytes = sha1.digest();
  228. return util.base64.encodeByteArray(sha1Bytes);
  229. };
  230. const buildLogMessage_ = function (...varArgs) {
  231. let message = '';
  232. for (let i = 0; i < varArgs.length; i++) {
  233. const arg = varArgs[i];
  234. if (Array.isArray(arg) ||
  235. (arg &&
  236. typeof arg === 'object' &&
  237. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  238. typeof arg.length === 'number')) {
  239. message += buildLogMessage_.apply(null, arg);
  240. }
  241. else if (typeof arg === 'object') {
  242. message += util.stringify(arg);
  243. }
  244. else {
  245. message += arg;
  246. }
  247. message += ' ';
  248. }
  249. return message;
  250. };
  251. /**
  252. * Use this for all debug messages in Firebase.
  253. */
  254. let logger = null;
  255. /**
  256. * Flag to check for log availability on first log message
  257. */
  258. let firstLog_ = true;
  259. /**
  260. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  261. * @param logger_ - A flag to turn on logging, or a custom logger
  262. * @param persistent - Whether or not to persist logging settings across refreshes
  263. */
  264. const enableLogging$1 = function (logger_, persistent) {
  265. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  266. if (logger_ === true) {
  267. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  268. logger = logClient.log.bind(logClient);
  269. if (persistent) {
  270. SessionStorage.set('logging_enabled', true);
  271. }
  272. }
  273. else if (typeof logger_ === 'function') {
  274. logger = logger_;
  275. }
  276. else {
  277. logger = null;
  278. SessionStorage.remove('logging_enabled');
  279. }
  280. };
  281. const log = function (...varArgs) {
  282. if (firstLog_ === true) {
  283. firstLog_ = false;
  284. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  285. enableLogging$1(true);
  286. }
  287. }
  288. if (logger) {
  289. const message = buildLogMessage_.apply(null, varArgs);
  290. logger(message);
  291. }
  292. };
  293. const logWrapper = function (prefix) {
  294. return function (...varArgs) {
  295. log(prefix, ...varArgs);
  296. };
  297. };
  298. const error = function (...varArgs) {
  299. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  300. logClient.error(message);
  301. };
  302. const fatal = function (...varArgs) {
  303. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  304. logClient.error(message);
  305. throw new Error(message);
  306. };
  307. const warn = function (...varArgs) {
  308. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  309. logClient.warn(message);
  310. };
  311. /**
  312. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  313. * does not use https.
  314. */
  315. const warnIfPageIsSecure = function () {
  316. // Be very careful accessing browser globals. Who knows what may or may not exist.
  317. if (typeof window !== 'undefined' &&
  318. window.location &&
  319. window.location.protocol &&
  320. window.location.protocol.indexOf('https:') !== -1) {
  321. warn('Insecure Firebase access from a secure page. ' +
  322. 'Please use https in calls to new Firebase().');
  323. }
  324. };
  325. /**
  326. * Returns true if data is NaN, or +/- Infinity.
  327. */
  328. const isInvalidJSONNumber = function (data) {
  329. return (typeof data === 'number' &&
  330. (data !== data || // NaN
  331. data === Number.POSITIVE_INFINITY ||
  332. data === Number.NEGATIVE_INFINITY));
  333. };
  334. const executeWhenDOMReady = function (fn) {
  335. if (util.isNodeSdk() || document.readyState === 'complete') {
  336. fn();
  337. }
  338. else {
  339. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  340. // fire before onload), but fall back to onload.
  341. let called = false;
  342. const wrappedFn = function () {
  343. if (!document.body) {
  344. setTimeout(wrappedFn, Math.floor(10));
  345. return;
  346. }
  347. if (!called) {
  348. called = true;
  349. fn();
  350. }
  351. };
  352. if (document.addEventListener) {
  353. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  354. // fallback to onload.
  355. window.addEventListener('load', wrappedFn, false);
  356. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  357. }
  358. else if (document.attachEvent) {
  359. // IE.
  360. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  361. document.attachEvent('onreadystatechange', () => {
  362. if (document.readyState === 'complete') {
  363. wrappedFn();
  364. }
  365. });
  366. // fallback to onload.
  367. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  368. window.attachEvent('onload', wrappedFn);
  369. // jQuery has an extra hack for IE that we could employ (based on
  370. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  371. // I'm hoping we don't need it.
  372. }
  373. }
  374. };
  375. /**
  376. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  377. */
  378. const MIN_NAME = '[MIN_NAME]';
  379. /**
  380. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  381. */
  382. const MAX_NAME = '[MAX_NAME]';
  383. /**
  384. * Compares valid Firebase key names, plus min and max name
  385. */
  386. const nameCompare = function (a, b) {
  387. if (a === b) {
  388. return 0;
  389. }
  390. else if (a === MIN_NAME || b === MAX_NAME) {
  391. return -1;
  392. }
  393. else if (b === MIN_NAME || a === MAX_NAME) {
  394. return 1;
  395. }
  396. else {
  397. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  398. if (aAsInt !== null) {
  399. if (bAsInt !== null) {
  400. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  401. }
  402. else {
  403. return -1;
  404. }
  405. }
  406. else if (bAsInt !== null) {
  407. return 1;
  408. }
  409. else {
  410. return a < b ? -1 : 1;
  411. }
  412. }
  413. };
  414. /**
  415. * @returns {!number} comparison result.
  416. */
  417. const stringCompare = function (a, b) {
  418. if (a === b) {
  419. return 0;
  420. }
  421. else if (a < b) {
  422. return -1;
  423. }
  424. else {
  425. return 1;
  426. }
  427. };
  428. const requireKey = function (key, obj) {
  429. if (obj && key in obj) {
  430. return obj[key];
  431. }
  432. else {
  433. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  434. }
  435. };
  436. const ObjectToUniqueKey = function (obj) {
  437. if (typeof obj !== 'object' || obj === null) {
  438. return util.stringify(obj);
  439. }
  440. const keys = [];
  441. // eslint-disable-next-line guard-for-in
  442. for (const k in obj) {
  443. keys.push(k);
  444. }
  445. // Export as json, but with the keys sorted.
  446. keys.sort();
  447. let key = '{';
  448. for (let i = 0; i < keys.length; i++) {
  449. if (i !== 0) {
  450. key += ',';
  451. }
  452. key += util.stringify(keys[i]);
  453. key += ':';
  454. key += ObjectToUniqueKey(obj[keys[i]]);
  455. }
  456. key += '}';
  457. return key;
  458. };
  459. /**
  460. * Splits a string into a number of smaller segments of maximum size
  461. * @param str - The string
  462. * @param segsize - The maximum number of chars in the string.
  463. * @returns The string, split into appropriately-sized chunks
  464. */
  465. const splitStringBySize = function (str, segsize) {
  466. const len = str.length;
  467. if (len <= segsize) {
  468. return [str];
  469. }
  470. const dataSegs = [];
  471. for (let c = 0; c < len; c += segsize) {
  472. if (c + segsize > len) {
  473. dataSegs.push(str.substring(c, len));
  474. }
  475. else {
  476. dataSegs.push(str.substring(c, c + segsize));
  477. }
  478. }
  479. return dataSegs;
  480. };
  481. /**
  482. * Apply a function to each (key, value) pair in an object or
  483. * apply a function to each (index, value) pair in an array
  484. * @param obj - The object or array to iterate over
  485. * @param fn - The function to apply
  486. */
  487. function each(obj, fn) {
  488. for (const key in obj) {
  489. if (obj.hasOwnProperty(key)) {
  490. fn(key, obj[key]);
  491. }
  492. }
  493. }
  494. /**
  495. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  496. * I made one modification at the end and removed the NaN / Infinity
  497. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  498. * @param v - A double
  499. *
  500. */
  501. const doubleToIEEE754String = function (v) {
  502. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  503. const ebits = 11, fbits = 52;
  504. const bias = (1 << (ebits - 1)) - 1;
  505. let s, e, f, ln, i;
  506. // Compute sign, exponent, fraction
  507. // Skip NaN / Infinity handling --MJL.
  508. if (v === 0) {
  509. e = 0;
  510. f = 0;
  511. s = 1 / v === -Infinity ? 1 : 0;
  512. }
  513. else {
  514. s = v < 0;
  515. v = Math.abs(v);
  516. if (v >= Math.pow(2, 1 - bias)) {
  517. // Normalized
  518. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  519. e = ln + bias;
  520. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  521. }
  522. else {
  523. // Denormalized
  524. e = 0;
  525. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  526. }
  527. }
  528. // Pack sign, exponent, fraction
  529. const bits = [];
  530. for (i = fbits; i; i -= 1) {
  531. bits.push(f % 2 ? 1 : 0);
  532. f = Math.floor(f / 2);
  533. }
  534. for (i = ebits; i; i -= 1) {
  535. bits.push(e % 2 ? 1 : 0);
  536. e = Math.floor(e / 2);
  537. }
  538. bits.push(s ? 1 : 0);
  539. bits.reverse();
  540. const str = bits.join('');
  541. // Return the data as a hex string. --MJL
  542. let hexByteString = '';
  543. for (i = 0; i < 64; i += 8) {
  544. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  545. if (hexByte.length === 1) {
  546. hexByte = '0' + hexByte;
  547. }
  548. hexByteString = hexByteString + hexByte;
  549. }
  550. return hexByteString.toLowerCase();
  551. };
  552. /**
  553. * Used to detect if we're in a Chrome content script (which executes in an
  554. * isolated environment where long-polling doesn't work).
  555. */
  556. const isChromeExtensionContentScript = function () {
  557. return !!(typeof window === 'object' &&
  558. window['chrome'] &&
  559. window['chrome']['extension'] &&
  560. !/^chrome/.test(window.location.href));
  561. };
  562. /**
  563. * Used to detect if we're in a Windows 8 Store app.
  564. */
  565. const isWindowsStoreApp = function () {
  566. // Check for the presence of a couple WinRT globals
  567. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  568. };
  569. /**
  570. * Converts a server error code to a JavaScript Error
  571. */
  572. function errorForServerCode(code, query) {
  573. let reason = 'Unknown Error';
  574. if (code === 'too_big') {
  575. reason =
  576. 'The data requested exceeds the maximum size ' +
  577. 'that can be accessed with a single request.';
  578. }
  579. else if (code === 'permission_denied') {
  580. reason = "Client doesn't have permission to access the desired data.";
  581. }
  582. else if (code === 'unavailable') {
  583. reason = 'The service is unavailable';
  584. }
  585. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  586. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  587. error.code = code.toUpperCase();
  588. return error;
  589. }
  590. /**
  591. * Used to test for integer-looking strings
  592. */
  593. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  594. /**
  595. * For use in keys, the minimum possible 32-bit integer.
  596. */
  597. const INTEGER_32_MIN = -2147483648;
  598. /**
  599. * For use in keys, the maximum possible 32-bit integer.
  600. */
  601. const INTEGER_32_MAX = 2147483647;
  602. /**
  603. * If the string contains a 32-bit integer, return it. Else return null.
  604. */
  605. const tryParseInt = function (str) {
  606. if (INTEGER_REGEXP_.test(str)) {
  607. const intVal = Number(str);
  608. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  609. return intVal;
  610. }
  611. }
  612. return null;
  613. };
  614. /**
  615. * Helper to run some code but catch any exceptions and re-throw them later.
  616. * Useful for preventing user callbacks from breaking internal code.
  617. *
  618. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  619. * convenient (we don't have to try to figure out when is a safe point to
  620. * re-throw it), and the behavior seems reasonable:
  621. *
  622. * * If you aren't pausing on exceptions, you get an error in the console with
  623. * the correct stack trace.
  624. * * If you're pausing on all exceptions, the debugger will pause on your
  625. * exception and then again when we rethrow it.
  626. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  627. * on us re-throwing it.
  628. *
  629. * @param fn - The code to guard.
  630. */
  631. const exceptionGuard = function (fn) {
  632. try {
  633. fn();
  634. }
  635. catch (e) {
  636. // Re-throw exception when it's safe.
  637. setTimeout(() => {
  638. // It used to be that "throw e" would result in a good console error with
  639. // relevant context, but as of Chrome 39, you just get the firebase.js
  640. // file/line number where we re-throw it, which is useless. So we log
  641. // e.stack explicitly.
  642. const stack = e.stack || '';
  643. warn('Exception was thrown by user callback.', stack);
  644. throw e;
  645. }, Math.floor(0));
  646. }
  647. };
  648. /**
  649. * @returns {boolean} true if we think we're currently being crawled.
  650. */
  651. const beingCrawled = function () {
  652. const userAgent = (typeof window === 'object' &&
  653. window['navigator'] &&
  654. window['navigator']['userAgent']) ||
  655. '';
  656. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  657. // believe to support JavaScript/AJAX rendering.
  658. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  659. // would have seen the page" is flaky if we don't treat it as a crawler.
  660. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  661. };
  662. /**
  663. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  664. *
  665. * It is removed with clearTimeout() as normal.
  666. *
  667. * @param fn - Function to run.
  668. * @param time - Milliseconds to wait before running.
  669. * @returns The setTimeout() return value.
  670. */
  671. const setTimeoutNonBlocking = function (fn, time) {
  672. const timeout = setTimeout(fn, time);
  673. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  674. if (typeof timeout === 'number' &&
  675. // @ts-ignore Is only defined in Deno environments.
  676. typeof Deno !== 'undefined' &&
  677. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  678. Deno['unrefTimer']) {
  679. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  680. Deno.unrefTimer(timeout);
  681. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  682. }
  683. else if (typeof timeout === 'object' && timeout['unref']) {
  684. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  685. timeout['unref']();
  686. }
  687. return timeout;
  688. };
  689. /**
  690. * @license
  691. * Copyright 2021 Google LLC
  692. *
  693. * Licensed under the Apache License, Version 2.0 (the "License");
  694. * you may not use this file except in compliance with the License.
  695. * You may obtain a copy of the License at
  696. *
  697. * http://www.apache.org/licenses/LICENSE-2.0
  698. *
  699. * Unless required by applicable law or agreed to in writing, software
  700. * distributed under the License is distributed on an "AS IS" BASIS,
  701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  702. * See the License for the specific language governing permissions and
  703. * limitations under the License.
  704. */
  705. /**
  706. * Abstraction around AppCheck's token fetching capabilities.
  707. */
  708. class AppCheckTokenProvider {
  709. constructor(appName_, appCheckProvider) {
  710. this.appName_ = appName_;
  711. this.appCheckProvider = appCheckProvider;
  712. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  713. if (!this.appCheck) {
  714. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  715. }
  716. }
  717. getToken(forceRefresh) {
  718. if (!this.appCheck) {
  719. return new Promise((resolve, reject) => {
  720. // Support delayed initialization of FirebaseAppCheck. This allows our
  721. // customers to initialize the RTDB SDK before initializing Firebase
  722. // AppCheck and ensures that all requests are authenticated if a token
  723. // becomes available before the timeout below expires.
  724. setTimeout(() => {
  725. if (this.appCheck) {
  726. this.getToken(forceRefresh).then(resolve, reject);
  727. }
  728. else {
  729. resolve(null);
  730. }
  731. }, 0);
  732. });
  733. }
  734. return this.appCheck.getToken(forceRefresh);
  735. }
  736. addTokenChangeListener(listener) {
  737. var _a;
  738. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  739. }
  740. notifyForInvalidToken() {
  741. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  742. 'are invalid. This usually indicates your app was not initialized correctly.');
  743. }
  744. }
  745. /**
  746. * @license
  747. * Copyright 2017 Google LLC
  748. *
  749. * Licensed under the Apache License, Version 2.0 (the "License");
  750. * you may not use this file except in compliance with the License.
  751. * You may obtain a copy of the License at
  752. *
  753. * http://www.apache.org/licenses/LICENSE-2.0
  754. *
  755. * Unless required by applicable law or agreed to in writing, software
  756. * distributed under the License is distributed on an "AS IS" BASIS,
  757. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  758. * See the License for the specific language governing permissions and
  759. * limitations under the License.
  760. */
  761. /**
  762. * Abstraction around FirebaseApp's token fetching capabilities.
  763. */
  764. class FirebaseAuthTokenProvider {
  765. constructor(appName_, firebaseOptions_, authProvider_) {
  766. this.appName_ = appName_;
  767. this.firebaseOptions_ = firebaseOptions_;
  768. this.authProvider_ = authProvider_;
  769. this.auth_ = null;
  770. this.auth_ = authProvider_.getImmediate({ optional: true });
  771. if (!this.auth_) {
  772. authProvider_.onInit(auth => (this.auth_ = auth));
  773. }
  774. }
  775. getToken(forceRefresh) {
  776. if (!this.auth_) {
  777. return new Promise((resolve, reject) => {
  778. // Support delayed initialization of FirebaseAuth. This allows our
  779. // customers to initialize the RTDB SDK before initializing Firebase
  780. // Auth and ensures that all requests are authenticated if a token
  781. // becomes available before the timeout below expires.
  782. setTimeout(() => {
  783. if (this.auth_) {
  784. this.getToken(forceRefresh).then(resolve, reject);
  785. }
  786. else {
  787. resolve(null);
  788. }
  789. }, 0);
  790. });
  791. }
  792. return this.auth_.getToken(forceRefresh).catch(error => {
  793. // TODO: Need to figure out all the cases this is raised and whether
  794. // this makes sense.
  795. if (error && error.code === 'auth/token-not-initialized') {
  796. log('Got auth/token-not-initialized error. Treating as null token.');
  797. return null;
  798. }
  799. else {
  800. return Promise.reject(error);
  801. }
  802. });
  803. }
  804. addTokenChangeListener(listener) {
  805. // TODO: We might want to wrap the listener and call it with no args to
  806. // avoid a leaky abstraction, but that makes removing the listener harder.
  807. if (this.auth_) {
  808. this.auth_.addAuthTokenListener(listener);
  809. }
  810. else {
  811. this.authProvider_
  812. .get()
  813. .then(auth => auth.addAuthTokenListener(listener));
  814. }
  815. }
  816. removeTokenChangeListener(listener) {
  817. this.authProvider_
  818. .get()
  819. .then(auth => auth.removeAuthTokenListener(listener));
  820. }
  821. notifyForInvalidToken() {
  822. let errorMessage = 'Provided authentication credentials for the app named "' +
  823. this.appName_ +
  824. '" are invalid. This usually indicates your app was not ' +
  825. 'initialized correctly. ';
  826. if ('credential' in this.firebaseOptions_) {
  827. errorMessage +=
  828. 'Make sure the "credential" property provided to initializeApp() ' +
  829. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  830. 'project.';
  831. }
  832. else if ('serviceAccount' in this.firebaseOptions_) {
  833. errorMessage +=
  834. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  835. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  836. 'project.';
  837. }
  838. else {
  839. errorMessage +=
  840. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  841. 'initializeApp() match the values provided for your app at ' +
  842. 'https://console.firebase.google.com/.';
  843. }
  844. warn(errorMessage);
  845. }
  846. }
  847. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  848. class EmulatorTokenProvider {
  849. constructor(accessToken) {
  850. this.accessToken = accessToken;
  851. }
  852. getToken(forceRefresh) {
  853. return Promise.resolve({
  854. accessToken: this.accessToken
  855. });
  856. }
  857. addTokenChangeListener(listener) {
  858. // Invoke the listener immediately to match the behavior in Firebase Auth
  859. // (see packages/auth/src/auth.js#L1807)
  860. listener(this.accessToken);
  861. }
  862. removeTokenChangeListener(listener) { }
  863. notifyForInvalidToken() { }
  864. }
  865. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  866. EmulatorTokenProvider.OWNER = 'owner';
  867. /**
  868. * @license
  869. * Copyright 2017 Google LLC
  870. *
  871. * Licensed under the Apache License, Version 2.0 (the "License");
  872. * you may not use this file except in compliance with the License.
  873. * You may obtain a copy of the License at
  874. *
  875. * http://www.apache.org/licenses/LICENSE-2.0
  876. *
  877. * Unless required by applicable law or agreed to in writing, software
  878. * distributed under the License is distributed on an "AS IS" BASIS,
  879. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  880. * See the License for the specific language governing permissions and
  881. * limitations under the License.
  882. */
  883. const PROTOCOL_VERSION = '5';
  884. const VERSION_PARAM = 'v';
  885. const TRANSPORT_SESSION_PARAM = 's';
  886. const REFERER_PARAM = 'r';
  887. const FORGE_REF = 'f';
  888. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  889. // firebase.corp.google.com
  890. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  891. const LAST_SESSION_PARAM = 'ls';
  892. const APPLICATION_ID_PARAM = 'p';
  893. const APP_CHECK_TOKEN_PARAM = 'ac';
  894. const WEBSOCKET = 'websocket';
  895. const LONG_POLLING = 'long_polling';
  896. /**
  897. * @license
  898. * Copyright 2017 Google LLC
  899. *
  900. * Licensed under the Apache License, Version 2.0 (the "License");
  901. * you may not use this file except in compliance with the License.
  902. * You may obtain a copy of the License at
  903. *
  904. * http://www.apache.org/licenses/LICENSE-2.0
  905. *
  906. * Unless required by applicable law or agreed to in writing, software
  907. * distributed under the License is distributed on an "AS IS" BASIS,
  908. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  909. * See the License for the specific language governing permissions and
  910. * limitations under the License.
  911. */
  912. /**
  913. * A class that holds metadata about a Repo object
  914. */
  915. class RepoInfo {
  916. /**
  917. * @param host - Hostname portion of the url for the repo
  918. * @param secure - Whether or not this repo is accessed over ssl
  919. * @param namespace - The namespace represented by the repo
  920. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  921. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  922. * @param persistenceKey - Override the default session persistence storage key
  923. */
  924. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  925. this.secure = secure;
  926. this.namespace = namespace;
  927. this.webSocketOnly = webSocketOnly;
  928. this.nodeAdmin = nodeAdmin;
  929. this.persistenceKey = persistenceKey;
  930. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  931. this.isUsingEmulator = isUsingEmulator;
  932. this._host = host.toLowerCase();
  933. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  934. this.internalHost =
  935. PersistentStorage.get('host:' + host) || this._host;
  936. }
  937. isCacheableHost() {
  938. return this.internalHost.substr(0, 2) === 's-';
  939. }
  940. isCustomHost() {
  941. return (this._domain !== 'firebaseio.com' &&
  942. this._domain !== 'firebaseio-demo.com');
  943. }
  944. get host() {
  945. return this._host;
  946. }
  947. set host(newHost) {
  948. if (newHost !== this.internalHost) {
  949. this.internalHost = newHost;
  950. if (this.isCacheableHost()) {
  951. PersistentStorage.set('host:' + this._host, this.internalHost);
  952. }
  953. }
  954. }
  955. toString() {
  956. let str = this.toURLString();
  957. if (this.persistenceKey) {
  958. str += '<' + this.persistenceKey + '>';
  959. }
  960. return str;
  961. }
  962. toURLString() {
  963. const protocol = this.secure ? 'https://' : 'http://';
  964. const query = this.includeNamespaceInQueryParams
  965. ? `?ns=${this.namespace}`
  966. : '';
  967. return `${protocol}${this.host}/${query}`;
  968. }
  969. }
  970. function repoInfoNeedsQueryParam(repoInfo) {
  971. return (repoInfo.host !== repoInfo.internalHost ||
  972. repoInfo.isCustomHost() ||
  973. repoInfo.includeNamespaceInQueryParams);
  974. }
  975. /**
  976. * Returns the websocket URL for this repo
  977. * @param repoInfo - RepoInfo object
  978. * @param type - of connection
  979. * @param params - list
  980. * @returns The URL for this repo
  981. */
  982. function repoInfoConnectionURL(repoInfo, type, params) {
  983. util.assert(typeof type === 'string', 'typeof type must == string');
  984. util.assert(typeof params === 'object', 'typeof params must == object');
  985. let connURL;
  986. if (type === WEBSOCKET) {
  987. connURL =
  988. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  989. }
  990. else if (type === LONG_POLLING) {
  991. connURL =
  992. (repoInfo.secure ? 'https://' : 'http://') +
  993. repoInfo.internalHost +
  994. '/.lp?';
  995. }
  996. else {
  997. throw new Error('Unknown connection type: ' + type);
  998. }
  999. if (repoInfoNeedsQueryParam(repoInfo)) {
  1000. params['ns'] = repoInfo.namespace;
  1001. }
  1002. const pairs = [];
  1003. each(params, (key, value) => {
  1004. pairs.push(key + '=' + value);
  1005. });
  1006. return connURL + pairs.join('&');
  1007. }
  1008. /**
  1009. * @license
  1010. * Copyright 2017 Google LLC
  1011. *
  1012. * Licensed under the Apache License, Version 2.0 (the "License");
  1013. * you may not use this file except in compliance with the License.
  1014. * You may obtain a copy of the License at
  1015. *
  1016. * http://www.apache.org/licenses/LICENSE-2.0
  1017. *
  1018. * Unless required by applicable law or agreed to in writing, software
  1019. * distributed under the License is distributed on an "AS IS" BASIS,
  1020. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1021. * See the License for the specific language governing permissions and
  1022. * limitations under the License.
  1023. */
  1024. /**
  1025. * Tracks a collection of stats.
  1026. */
  1027. class StatsCollection {
  1028. constructor() {
  1029. this.counters_ = {};
  1030. }
  1031. incrementCounter(name, amount = 1) {
  1032. if (!util.contains(this.counters_, name)) {
  1033. this.counters_[name] = 0;
  1034. }
  1035. this.counters_[name] += amount;
  1036. }
  1037. get() {
  1038. return util.deepCopy(this.counters_);
  1039. }
  1040. }
  1041. /**
  1042. * @license
  1043. * Copyright 2017 Google LLC
  1044. *
  1045. * Licensed under the Apache License, Version 2.0 (the "License");
  1046. * you may not use this file except in compliance with the License.
  1047. * You may obtain a copy of the License at
  1048. *
  1049. * http://www.apache.org/licenses/LICENSE-2.0
  1050. *
  1051. * Unless required by applicable law or agreed to in writing, software
  1052. * distributed under the License is distributed on an "AS IS" BASIS,
  1053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1054. * See the License for the specific language governing permissions and
  1055. * limitations under the License.
  1056. */
  1057. const collections = {};
  1058. const reporters = {};
  1059. function statsManagerGetCollection(repoInfo) {
  1060. const hashString = repoInfo.toString();
  1061. if (!collections[hashString]) {
  1062. collections[hashString] = new StatsCollection();
  1063. }
  1064. return collections[hashString];
  1065. }
  1066. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1067. const hashString = repoInfo.toString();
  1068. if (!reporters[hashString]) {
  1069. reporters[hashString] = creatorFunction();
  1070. }
  1071. return reporters[hashString];
  1072. }
  1073. /**
  1074. * @license
  1075. * Copyright 2017 Google LLC
  1076. *
  1077. * Licensed under the Apache License, Version 2.0 (the "License");
  1078. * you may not use this file except in compliance with the License.
  1079. * You may obtain a copy of the License at
  1080. *
  1081. * http://www.apache.org/licenses/LICENSE-2.0
  1082. *
  1083. * Unless required by applicable law or agreed to in writing, software
  1084. * distributed under the License is distributed on an "AS IS" BASIS,
  1085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1086. * See the License for the specific language governing permissions and
  1087. * limitations under the License.
  1088. */
  1089. /**
  1090. * This class ensures the packets from the server arrive in order
  1091. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1092. */
  1093. class PacketReceiver {
  1094. /**
  1095. * @param onMessage_
  1096. */
  1097. constructor(onMessage_) {
  1098. this.onMessage_ = onMessage_;
  1099. this.pendingResponses = [];
  1100. this.currentResponseNum = 0;
  1101. this.closeAfterResponse = -1;
  1102. this.onClose = null;
  1103. }
  1104. closeAfter(responseNum, callback) {
  1105. this.closeAfterResponse = responseNum;
  1106. this.onClose = callback;
  1107. if (this.closeAfterResponse < this.currentResponseNum) {
  1108. this.onClose();
  1109. this.onClose = null;
  1110. }
  1111. }
  1112. /**
  1113. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1114. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1115. * browsers will respond in the same order as the requests we sent
  1116. */
  1117. handleResponse(requestNum, data) {
  1118. this.pendingResponses[requestNum] = data;
  1119. while (this.pendingResponses[this.currentResponseNum]) {
  1120. const toProcess = this.pendingResponses[this.currentResponseNum];
  1121. delete this.pendingResponses[this.currentResponseNum];
  1122. for (let i = 0; i < toProcess.length; ++i) {
  1123. if (toProcess[i]) {
  1124. exceptionGuard(() => {
  1125. this.onMessage_(toProcess[i]);
  1126. });
  1127. }
  1128. }
  1129. if (this.currentResponseNum === this.closeAfterResponse) {
  1130. if (this.onClose) {
  1131. this.onClose();
  1132. this.onClose = null;
  1133. }
  1134. break;
  1135. }
  1136. this.currentResponseNum++;
  1137. }
  1138. }
  1139. }
  1140. /**
  1141. * @license
  1142. * Copyright 2017 Google LLC
  1143. *
  1144. * Licensed under the Apache License, Version 2.0 (the "License");
  1145. * you may not use this file except in compliance with the License.
  1146. * You may obtain a copy of the License at
  1147. *
  1148. * http://www.apache.org/licenses/LICENSE-2.0
  1149. *
  1150. * Unless required by applicable law or agreed to in writing, software
  1151. * distributed under the License is distributed on an "AS IS" BASIS,
  1152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1153. * See the License for the specific language governing permissions and
  1154. * limitations under the License.
  1155. */
  1156. // URL query parameters associated with longpolling
  1157. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1158. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1159. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1160. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1161. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1162. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1163. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1164. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1165. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1166. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1167. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1168. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1169. //Data size constants.
  1170. //TODO: Perf: the maximum length actually differs from browser to browser.
  1171. // We should check what browser we're on and set accordingly.
  1172. const MAX_URL_DATA_SIZE = 1870;
  1173. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1174. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1175. /**
  1176. * Keepalive period
  1177. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1178. * length of 30 seconds that we can't exceed.
  1179. */
  1180. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1181. /**
  1182. * How long to wait before aborting a long-polling connection attempt.
  1183. */
  1184. const LP_CONNECT_TIMEOUT = 30000;
  1185. /**
  1186. * This class manages a single long-polling connection.
  1187. */
  1188. class BrowserPollConnection {
  1189. /**
  1190. * @param connId An identifier for this connection, used for logging
  1191. * @param repoInfo The info for the endpoint to send data to.
  1192. * @param applicationId The Firebase App ID for this project.
  1193. * @param appCheckToken The AppCheck token for this client.
  1194. * @param authToken The AuthToken to use for this connection.
  1195. * @param transportSessionId Optional transportSessionid if we are
  1196. * reconnecting for an existing transport session
  1197. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1198. * already created a connection previously
  1199. */
  1200. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1201. this.connId = connId;
  1202. this.repoInfo = repoInfo;
  1203. this.applicationId = applicationId;
  1204. this.appCheckToken = appCheckToken;
  1205. this.authToken = authToken;
  1206. this.transportSessionId = transportSessionId;
  1207. this.lastSessionId = lastSessionId;
  1208. this.bytesSent = 0;
  1209. this.bytesReceived = 0;
  1210. this.everConnected_ = false;
  1211. this.log_ = logWrapper(connId);
  1212. this.stats_ = statsManagerGetCollection(repoInfo);
  1213. this.urlFn = (params) => {
  1214. // Always add the token if we have one.
  1215. if (this.appCheckToken) {
  1216. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1217. }
  1218. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1219. };
  1220. }
  1221. /**
  1222. * @param onMessage - Callback when messages arrive
  1223. * @param onDisconnect - Callback with connection lost.
  1224. */
  1225. open(onMessage, onDisconnect) {
  1226. this.curSegmentNum = 0;
  1227. this.onDisconnect_ = onDisconnect;
  1228. this.myPacketOrderer = new PacketReceiver(onMessage);
  1229. this.isClosed_ = false;
  1230. this.connectTimeoutTimer_ = setTimeout(() => {
  1231. this.log_('Timed out trying to connect.');
  1232. // Make sure we clear the host cache
  1233. this.onClosed_();
  1234. this.connectTimeoutTimer_ = null;
  1235. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1236. }, Math.floor(LP_CONNECT_TIMEOUT));
  1237. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1238. executeWhenDOMReady(() => {
  1239. if (this.isClosed_) {
  1240. return;
  1241. }
  1242. //Set up a callback that gets triggered once a connection is set up.
  1243. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1244. const [command, arg1, arg2, arg3, arg4] = args;
  1245. this.incrementIncomingBytes_(args);
  1246. if (!this.scriptTagHolder) {
  1247. return; // we closed the connection.
  1248. }
  1249. if (this.connectTimeoutTimer_) {
  1250. clearTimeout(this.connectTimeoutTimer_);
  1251. this.connectTimeoutTimer_ = null;
  1252. }
  1253. this.everConnected_ = true;
  1254. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1255. this.id = arg1;
  1256. this.password = arg2;
  1257. }
  1258. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1259. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1260. if (arg1) {
  1261. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1262. // through our already open polls), so don't send any more.
  1263. this.scriptTagHolder.sendNewPolls = false;
  1264. // arg1 in this case is the last response number sent by the server. We should try to receive
  1265. // all of the responses up to this one before closing
  1266. this.myPacketOrderer.closeAfter(arg1, () => {
  1267. this.onClosed_();
  1268. });
  1269. }
  1270. else {
  1271. this.onClosed_();
  1272. }
  1273. }
  1274. else {
  1275. throw new Error('Unrecognized command received: ' + command);
  1276. }
  1277. }, (...args) => {
  1278. const [pN, data] = args;
  1279. this.incrementIncomingBytes_(args);
  1280. this.myPacketOrderer.handleResponse(pN, data);
  1281. }, () => {
  1282. this.onClosed_();
  1283. }, this.urlFn);
  1284. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1285. //from cache.
  1286. const urlParams = {};
  1287. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1288. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1289. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1290. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1291. this.scriptTagHolder.uniqueCallbackIdentifier;
  1292. }
  1293. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1294. if (this.transportSessionId) {
  1295. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1296. }
  1297. if (this.lastSessionId) {
  1298. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1299. }
  1300. if (this.applicationId) {
  1301. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1302. }
  1303. if (this.appCheckToken) {
  1304. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1305. }
  1306. if (typeof location !== 'undefined' &&
  1307. location.hostname &&
  1308. FORGE_DOMAIN_RE.test(location.hostname)) {
  1309. urlParams[REFERER_PARAM] = FORGE_REF;
  1310. }
  1311. const connectURL = this.urlFn(urlParams);
  1312. this.log_('Connecting via long-poll to ' + connectURL);
  1313. this.scriptTagHolder.addTag(connectURL, () => {
  1314. /* do nothing */
  1315. });
  1316. });
  1317. }
  1318. /**
  1319. * Call this when a handshake has completed successfully and we want to consider the connection established
  1320. */
  1321. start() {
  1322. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1323. this.addDisconnectPingFrame(this.id, this.password);
  1324. }
  1325. /**
  1326. * Forces long polling to be considered as a potential transport
  1327. */
  1328. static forceAllow() {
  1329. BrowserPollConnection.forceAllow_ = true;
  1330. }
  1331. /**
  1332. * Forces longpolling to not be considered as a potential transport
  1333. */
  1334. static forceDisallow() {
  1335. BrowserPollConnection.forceDisallow_ = true;
  1336. }
  1337. // Static method, use string literal so it can be accessed in a generic way
  1338. static isAvailable() {
  1339. if (util.isNodeSdk()) {
  1340. return false;
  1341. }
  1342. else if (BrowserPollConnection.forceAllow_) {
  1343. return true;
  1344. }
  1345. else {
  1346. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1347. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1348. return (!BrowserPollConnection.forceDisallow_ &&
  1349. typeof document !== 'undefined' &&
  1350. document.createElement != null &&
  1351. !isChromeExtensionContentScript() &&
  1352. !isWindowsStoreApp());
  1353. }
  1354. }
  1355. /**
  1356. * No-op for polling
  1357. */
  1358. markConnectionHealthy() { }
  1359. /**
  1360. * Stops polling and cleans up the iframe
  1361. */
  1362. shutdown_() {
  1363. this.isClosed_ = true;
  1364. if (this.scriptTagHolder) {
  1365. this.scriptTagHolder.close();
  1366. this.scriptTagHolder = null;
  1367. }
  1368. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1369. if (this.myDisconnFrame) {
  1370. document.body.removeChild(this.myDisconnFrame);
  1371. this.myDisconnFrame = null;
  1372. }
  1373. if (this.connectTimeoutTimer_) {
  1374. clearTimeout(this.connectTimeoutTimer_);
  1375. this.connectTimeoutTimer_ = null;
  1376. }
  1377. }
  1378. /**
  1379. * Triggered when this transport is closed
  1380. */
  1381. onClosed_() {
  1382. if (!this.isClosed_) {
  1383. this.log_('Longpoll is closing itself');
  1384. this.shutdown_();
  1385. if (this.onDisconnect_) {
  1386. this.onDisconnect_(this.everConnected_);
  1387. this.onDisconnect_ = null;
  1388. }
  1389. }
  1390. }
  1391. /**
  1392. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1393. * that we've left.
  1394. */
  1395. close() {
  1396. if (!this.isClosed_) {
  1397. this.log_('Longpoll is being closed.');
  1398. this.shutdown_();
  1399. }
  1400. }
  1401. /**
  1402. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1403. * broken into chunks (since URLs have a small maximum length).
  1404. * @param data - The JSON data to transmit.
  1405. */
  1406. send(data) {
  1407. const dataStr = util.stringify(data);
  1408. this.bytesSent += dataStr.length;
  1409. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1410. //first, lets get the base64-encoded data
  1411. const base64data = util.base64Encode(dataStr);
  1412. //We can only fit a certain amount in each URL, so we need to split this request
  1413. //up into multiple pieces if it doesn't fit in one request.
  1414. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1415. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1416. //of segments so that we can reassemble the packet on the server.
  1417. for (let i = 0; i < dataSegs.length; i++) {
  1418. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1419. this.curSegmentNum++;
  1420. }
  1421. }
  1422. /**
  1423. * This is how we notify the server that we're leaving.
  1424. * We aren't able to send requests with DHTML on a window close event, but we can
  1425. * trigger XHR requests in some browsers (everything but Opera basically).
  1426. */
  1427. addDisconnectPingFrame(id, pw) {
  1428. if (util.isNodeSdk()) {
  1429. return;
  1430. }
  1431. this.myDisconnFrame = document.createElement('iframe');
  1432. const urlParams = {};
  1433. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1434. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1435. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1436. this.myDisconnFrame.src = this.urlFn(urlParams);
  1437. this.myDisconnFrame.style.display = 'none';
  1438. document.body.appendChild(this.myDisconnFrame);
  1439. }
  1440. /**
  1441. * Used to track the bytes received by this client
  1442. */
  1443. incrementIncomingBytes_(args) {
  1444. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1445. const bytesReceived = util.stringify(args).length;
  1446. this.bytesReceived += bytesReceived;
  1447. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1448. }
  1449. }
  1450. /*********************************************************************************************
  1451. * A wrapper around an iframe that is used as a long-polling script holder.
  1452. *********************************************************************************************/
  1453. class FirebaseIFrameScriptHolder {
  1454. /**
  1455. * @param commandCB - The callback to be called when control commands are received from the server.
  1456. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1457. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1458. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1459. */
  1460. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1461. this.onDisconnect = onDisconnect;
  1462. this.urlFn = urlFn;
  1463. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1464. //problems in some browsers.
  1465. this.outstandingRequests = new Set();
  1466. //A queue of the pending segments waiting for transmission to the server.
  1467. this.pendingSegs = [];
  1468. //A serial number. We use this for two things:
  1469. // 1) A way to ensure the browser doesn't cache responses to polls
  1470. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1471. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1472. // JSONP code in the order it was added to the iframe.
  1473. this.currentSerial = Math.floor(Math.random() * 100000000);
  1474. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1475. // incoming data from the server that we're waiting for).
  1476. this.sendNewPolls = true;
  1477. if (!util.isNodeSdk()) {
  1478. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1479. //iframes where we put the long-polling script tags. We have two callbacks:
  1480. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1481. // 2) Message Callback - Triggered when new data arrives.
  1482. this.uniqueCallbackIdentifier = LUIDGenerator();
  1483. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1484. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1485. onMessageCB;
  1486. //Create an iframe for us to add script tags to.
  1487. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1488. // Set the iframe's contents.
  1489. let script = '';
  1490. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1491. // for ie9, but ie8 needs to do it again in the document itself.
  1492. if (this.myIFrame.src &&
  1493. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1494. const currentDomain = document.domain;
  1495. script = '<script>document.domain="' + currentDomain + '";</script>';
  1496. }
  1497. const iframeContents = '<html><body>' + script + '</body></html>';
  1498. try {
  1499. this.myIFrame.doc.open();
  1500. this.myIFrame.doc.write(iframeContents);
  1501. this.myIFrame.doc.close();
  1502. }
  1503. catch (e) {
  1504. log('frame writing exception');
  1505. if (e.stack) {
  1506. log(e.stack);
  1507. }
  1508. log(e);
  1509. }
  1510. }
  1511. else {
  1512. this.commandCB = commandCB;
  1513. this.onMessageCB = onMessageCB;
  1514. }
  1515. }
  1516. /**
  1517. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1518. * actually use.
  1519. */
  1520. static createIFrame_() {
  1521. const iframe = document.createElement('iframe');
  1522. iframe.style.display = 'none';
  1523. // This is necessary in order to initialize the document inside the iframe
  1524. if (document.body) {
  1525. document.body.appendChild(iframe);
  1526. try {
  1527. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1528. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1529. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1530. const a = iframe.contentWindow.document;
  1531. if (!a) {
  1532. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1533. log('No IE domain setting required');
  1534. }
  1535. }
  1536. catch (e) {
  1537. const domain = document.domain;
  1538. iframe.src =
  1539. "javascript:void((function(){document.open();document.domain='" +
  1540. domain +
  1541. "';document.close();})())";
  1542. }
  1543. }
  1544. else {
  1545. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1546. // never gets hit.
  1547. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1548. }
  1549. // Get the document of the iframe in a browser-specific way.
  1550. if (iframe.contentDocument) {
  1551. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1552. }
  1553. else if (iframe.contentWindow) {
  1554. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1555. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1556. }
  1557. else if (iframe.document) {
  1558. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1559. iframe.doc = iframe.document; //others?
  1560. }
  1561. return iframe;
  1562. }
  1563. /**
  1564. * Cancel all outstanding queries and remove the frame.
  1565. */
  1566. close() {
  1567. //Mark this iframe as dead, so no new requests are sent.
  1568. this.alive = false;
  1569. if (this.myIFrame) {
  1570. //We have to actually remove all of the html inside this iframe before removing it from the
  1571. //window, or IE will continue loading and executing the script tags we've already added, which
  1572. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1573. this.myIFrame.doc.body.textContent = '';
  1574. setTimeout(() => {
  1575. if (this.myIFrame !== null) {
  1576. document.body.removeChild(this.myIFrame);
  1577. this.myIFrame = null;
  1578. }
  1579. }, Math.floor(0));
  1580. }
  1581. // Protect from being called recursively.
  1582. const onDisconnect = this.onDisconnect;
  1583. if (onDisconnect) {
  1584. this.onDisconnect = null;
  1585. onDisconnect();
  1586. }
  1587. }
  1588. /**
  1589. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1590. * @param id - The ID of this connection
  1591. * @param pw - The password for this connection
  1592. */
  1593. startLongPoll(id, pw) {
  1594. this.myID = id;
  1595. this.myPW = pw;
  1596. this.alive = true;
  1597. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1598. while (this.newRequest_()) { }
  1599. }
  1600. /**
  1601. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1602. * too many outstanding requests and we are still alive.
  1603. *
  1604. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1605. * needed.
  1606. */
  1607. newRequest_() {
  1608. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1609. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1610. // close the old request.
  1611. if (this.alive &&
  1612. this.sendNewPolls &&
  1613. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1614. //construct our url
  1615. this.currentSerial++;
  1616. const urlParams = {};
  1617. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1618. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1619. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1620. let theURL = this.urlFn(urlParams);
  1621. //Now add as much data as we can.
  1622. let curDataString = '';
  1623. let i = 0;
  1624. while (this.pendingSegs.length > 0) {
  1625. //first, lets see if the next segment will fit.
  1626. const nextSeg = this.pendingSegs[0];
  1627. if (nextSeg.d.length +
  1628. SEG_HEADER_SIZE +
  1629. curDataString.length <=
  1630. MAX_URL_DATA_SIZE) {
  1631. //great, the segment will fit. Lets append it.
  1632. const theSeg = this.pendingSegs.shift();
  1633. curDataString =
  1634. curDataString +
  1635. '&' +
  1636. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1637. i +
  1638. '=' +
  1639. theSeg.seg +
  1640. '&' +
  1641. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1642. i +
  1643. '=' +
  1644. theSeg.ts +
  1645. '&' +
  1646. FIREBASE_LONGPOLL_DATA_PARAM +
  1647. i +
  1648. '=' +
  1649. theSeg.d;
  1650. i++;
  1651. }
  1652. else {
  1653. break;
  1654. }
  1655. }
  1656. theURL = theURL + curDataString;
  1657. this.addLongPollTag_(theURL, this.currentSerial);
  1658. return true;
  1659. }
  1660. else {
  1661. return false;
  1662. }
  1663. }
  1664. /**
  1665. * Queue a packet for transmission to the server.
  1666. * @param segnum - A sequential id for this packet segment used for reassembly
  1667. * @param totalsegs - The total number of segments in this packet
  1668. * @param data - The data for this segment.
  1669. */
  1670. enqueueSegment(segnum, totalsegs, data) {
  1671. //add this to the queue of segments to send.
  1672. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1673. //send the data immediately if there isn't already data being transmitted, unless
  1674. //startLongPoll hasn't been called yet.
  1675. if (this.alive) {
  1676. this.newRequest_();
  1677. }
  1678. }
  1679. /**
  1680. * Add a script tag for a regular long-poll request.
  1681. * @param url - The URL of the script tag.
  1682. * @param serial - The serial number of the request.
  1683. */
  1684. addLongPollTag_(url, serial) {
  1685. //remember that we sent this request.
  1686. this.outstandingRequests.add(serial);
  1687. const doNewRequest = () => {
  1688. this.outstandingRequests.delete(serial);
  1689. this.newRequest_();
  1690. };
  1691. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1692. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1693. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1694. const readyStateCB = () => {
  1695. // Request completed. Cancel the keepalive.
  1696. clearTimeout(keepaliveTimeout);
  1697. // Trigger a new request so we can continue receiving data.
  1698. doNewRequest();
  1699. };
  1700. this.addTag(url, readyStateCB);
  1701. }
  1702. /**
  1703. * Add an arbitrary script tag to the iframe.
  1704. * @param url - The URL for the script tag source.
  1705. * @param loadCB - A callback to be triggered once the script has loaded.
  1706. */
  1707. addTag(url, loadCB) {
  1708. if (util.isNodeSdk()) {
  1709. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1710. this.doNodeLongPoll(url, loadCB);
  1711. }
  1712. else {
  1713. setTimeout(() => {
  1714. try {
  1715. // if we're already closed, don't add this poll
  1716. if (!this.sendNewPolls) {
  1717. return;
  1718. }
  1719. const newScript = this.myIFrame.doc.createElement('script');
  1720. newScript.type = 'text/javascript';
  1721. newScript.async = true;
  1722. newScript.src = url;
  1723. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1724. newScript.onload = newScript.onreadystatechange =
  1725. function () {
  1726. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1727. const rstate = newScript.readyState;
  1728. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1729. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1730. newScript.onload = newScript.onreadystatechange = null;
  1731. if (newScript.parentNode) {
  1732. newScript.parentNode.removeChild(newScript);
  1733. }
  1734. loadCB();
  1735. }
  1736. };
  1737. newScript.onerror = () => {
  1738. log('Long-poll script failed to load: ' + url);
  1739. this.sendNewPolls = false;
  1740. this.close();
  1741. };
  1742. this.myIFrame.doc.body.appendChild(newScript);
  1743. }
  1744. catch (e) {
  1745. // TODO: we should make this error visible somehow
  1746. }
  1747. }, Math.floor(1));
  1748. }
  1749. }
  1750. }
  1751. /**
  1752. * @license
  1753. * Copyright 2017 Google LLC
  1754. *
  1755. * Licensed under the Apache License, Version 2.0 (the "License");
  1756. * you may not use this file except in compliance with the License.
  1757. * You may obtain a copy of the License at
  1758. *
  1759. * http://www.apache.org/licenses/LICENSE-2.0
  1760. *
  1761. * Unless required by applicable law or agreed to in writing, software
  1762. * distributed under the License is distributed on an "AS IS" BASIS,
  1763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1764. * See the License for the specific language governing permissions and
  1765. * limitations under the License.
  1766. */
  1767. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1768. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1769. let WebSocketImpl = null;
  1770. if (typeof MozWebSocket !== 'undefined') {
  1771. WebSocketImpl = MozWebSocket;
  1772. }
  1773. else if (typeof WebSocket !== 'undefined') {
  1774. WebSocketImpl = WebSocket;
  1775. }
  1776. /**
  1777. * Create a new websocket connection with the given callbacks.
  1778. */
  1779. class WebSocketConnection {
  1780. /**
  1781. * @param connId identifier for this transport
  1782. * @param repoInfo The info for the websocket endpoint.
  1783. * @param applicationId The Firebase App ID for this project.
  1784. * @param appCheckToken The App Check Token for this client.
  1785. * @param authToken The Auth Token for this client.
  1786. * @param transportSessionId Optional transportSessionId if this is connecting
  1787. * to an existing transport session
  1788. * @param lastSessionId Optional lastSessionId if there was a previous
  1789. * connection
  1790. */
  1791. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1792. this.connId = connId;
  1793. this.applicationId = applicationId;
  1794. this.appCheckToken = appCheckToken;
  1795. this.authToken = authToken;
  1796. this.keepaliveTimer = null;
  1797. this.frames = null;
  1798. this.totalFrames = 0;
  1799. this.bytesSent = 0;
  1800. this.bytesReceived = 0;
  1801. this.log_ = logWrapper(this.connId);
  1802. this.stats_ = statsManagerGetCollection(repoInfo);
  1803. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1804. this.nodeAdmin = repoInfo.nodeAdmin;
  1805. }
  1806. /**
  1807. * @param repoInfo - The info for the websocket endpoint.
  1808. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1809. * session
  1810. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1811. * @returns connection url
  1812. */
  1813. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1814. const urlParams = {};
  1815. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1816. if (!util.isNodeSdk() &&
  1817. typeof location !== 'undefined' &&
  1818. location.hostname &&
  1819. FORGE_DOMAIN_RE.test(location.hostname)) {
  1820. urlParams[REFERER_PARAM] = FORGE_REF;
  1821. }
  1822. if (transportSessionId) {
  1823. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1824. }
  1825. if (lastSessionId) {
  1826. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1827. }
  1828. if (appCheckToken) {
  1829. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1830. }
  1831. if (applicationId) {
  1832. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1833. }
  1834. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1835. }
  1836. /**
  1837. * @param onMessage - Callback when messages arrive
  1838. * @param onDisconnect - Callback with connection lost.
  1839. */
  1840. open(onMessage, onDisconnect) {
  1841. this.onDisconnect = onDisconnect;
  1842. this.onMessage = onMessage;
  1843. this.log_('Websocket connecting to ' + this.connURL);
  1844. this.everConnected_ = false;
  1845. // Assume failure until proven otherwise.
  1846. PersistentStorage.set('previous_websocket_failure', true);
  1847. try {
  1848. let options;
  1849. if (util.isNodeSdk()) {
  1850. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1851. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1852. options = {
  1853. headers: {
  1854. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  1855. 'X-Firebase-GMPID': this.applicationId || ''
  1856. }
  1857. };
  1858. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1859. // Note that we send the credentials here even if they aren't admin credentials, which is
  1860. // not a problem.
  1861. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1862. // through the websocket connection once it is established.
  1863. if (this.authToken) {
  1864. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1865. }
  1866. if (this.appCheckToken) {
  1867. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1868. }
  1869. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1870. const env = process['env'];
  1871. const proxy = this.connURL.indexOf('wss://') === 0
  1872. ? env['HTTPS_PROXY'] || env['https_proxy']
  1873. : env['HTTP_PROXY'] || env['http_proxy'];
  1874. if (proxy) {
  1875. options['proxy'] = { origin: proxy };
  1876. }
  1877. }
  1878. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1879. }
  1880. catch (e) {
  1881. this.log_('Error instantiating WebSocket.');
  1882. const error = e.message || e.data;
  1883. if (error) {
  1884. this.log_(error);
  1885. }
  1886. this.onClosed_();
  1887. return;
  1888. }
  1889. this.mySock.onopen = () => {
  1890. this.log_('Websocket connected.');
  1891. this.everConnected_ = true;
  1892. };
  1893. this.mySock.onclose = () => {
  1894. this.log_('Websocket connection was disconnected.');
  1895. this.mySock = null;
  1896. this.onClosed_();
  1897. };
  1898. this.mySock.onmessage = m => {
  1899. this.handleIncomingFrame(m);
  1900. };
  1901. this.mySock.onerror = e => {
  1902. this.log_('WebSocket error. Closing connection.');
  1903. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1904. const error = e.message || e.data;
  1905. if (error) {
  1906. this.log_(error);
  1907. }
  1908. this.onClosed_();
  1909. };
  1910. }
  1911. /**
  1912. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1913. */
  1914. start() { }
  1915. static forceDisallow() {
  1916. WebSocketConnection.forceDisallow_ = true;
  1917. }
  1918. static isAvailable() {
  1919. let isOldAndroid = false;
  1920. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1921. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1922. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1923. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1924. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1925. isOldAndroid = true;
  1926. }
  1927. }
  1928. }
  1929. return (!isOldAndroid &&
  1930. WebSocketImpl !== null &&
  1931. !WebSocketConnection.forceDisallow_);
  1932. }
  1933. /**
  1934. * Returns true if we previously failed to connect with this transport.
  1935. */
  1936. static previouslyFailed() {
  1937. // If our persistent storage is actually only in-memory storage,
  1938. // we default to assuming that it previously failed to be safe.
  1939. return (PersistentStorage.isInMemoryStorage ||
  1940. PersistentStorage.get('previous_websocket_failure') === true);
  1941. }
  1942. markConnectionHealthy() {
  1943. PersistentStorage.remove('previous_websocket_failure');
  1944. }
  1945. appendFrame_(data) {
  1946. this.frames.push(data);
  1947. if (this.frames.length === this.totalFrames) {
  1948. const fullMess = this.frames.join('');
  1949. this.frames = null;
  1950. const jsonMess = util.jsonEval(fullMess);
  1951. //handle the message
  1952. this.onMessage(jsonMess);
  1953. }
  1954. }
  1955. /**
  1956. * @param frameCount - The number of frames we are expecting from the server
  1957. */
  1958. handleNewFrameCount_(frameCount) {
  1959. this.totalFrames = frameCount;
  1960. this.frames = [];
  1961. }
  1962. /**
  1963. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1964. * @returns Any remaining data to be process, or null if there is none
  1965. */
  1966. extractFrameCount_(data) {
  1967. util.assert(this.frames === null, 'We already have a frame buffer');
  1968. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1969. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1970. if (data.length <= 6) {
  1971. const frameCount = Number(data);
  1972. if (!isNaN(frameCount)) {
  1973. this.handleNewFrameCount_(frameCount);
  1974. return null;
  1975. }
  1976. }
  1977. this.handleNewFrameCount_(1);
  1978. return data;
  1979. }
  1980. /**
  1981. * Process a websocket frame that has arrived from the server.
  1982. * @param mess - The frame data
  1983. */
  1984. handleIncomingFrame(mess) {
  1985. if (this.mySock === null) {
  1986. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1987. }
  1988. const data = mess['data'];
  1989. this.bytesReceived += data.length;
  1990. this.stats_.incrementCounter('bytes_received', data.length);
  1991. this.resetKeepAlive();
  1992. if (this.frames !== null) {
  1993. // we're buffering
  1994. this.appendFrame_(data);
  1995. }
  1996. else {
  1997. // try to parse out a frame count, otherwise, assume 1 and process it
  1998. const remainingData = this.extractFrameCount_(data);
  1999. if (remainingData !== null) {
  2000. this.appendFrame_(remainingData);
  2001. }
  2002. }
  2003. }
  2004. /**
  2005. * Send a message to the server
  2006. * @param data - The JSON object to transmit
  2007. */
  2008. send(data) {
  2009. this.resetKeepAlive();
  2010. const dataStr = util.stringify(data);
  2011. this.bytesSent += dataStr.length;
  2012. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2013. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2014. //up into multiple pieces if it doesn't fit in one request.
  2015. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2016. //Send the length header
  2017. if (dataSegs.length > 1) {
  2018. this.sendString_(String(dataSegs.length));
  2019. }
  2020. //Send the actual data in segments.
  2021. for (let i = 0; i < dataSegs.length; i++) {
  2022. this.sendString_(dataSegs[i]);
  2023. }
  2024. }
  2025. shutdown_() {
  2026. this.isClosed_ = true;
  2027. if (this.keepaliveTimer) {
  2028. clearInterval(this.keepaliveTimer);
  2029. this.keepaliveTimer = null;
  2030. }
  2031. if (this.mySock) {
  2032. this.mySock.close();
  2033. this.mySock = null;
  2034. }
  2035. }
  2036. onClosed_() {
  2037. if (!this.isClosed_) {
  2038. this.log_('WebSocket is closing itself');
  2039. this.shutdown_();
  2040. // since this is an internal close, trigger the close listener
  2041. if (this.onDisconnect) {
  2042. this.onDisconnect(this.everConnected_);
  2043. this.onDisconnect = null;
  2044. }
  2045. }
  2046. }
  2047. /**
  2048. * External-facing close handler.
  2049. * Close the websocket and kill the connection.
  2050. */
  2051. close() {
  2052. if (!this.isClosed_) {
  2053. this.log_('WebSocket is being closed');
  2054. this.shutdown_();
  2055. }
  2056. }
  2057. /**
  2058. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2059. * the last activity.
  2060. */
  2061. resetKeepAlive() {
  2062. clearInterval(this.keepaliveTimer);
  2063. this.keepaliveTimer = setInterval(() => {
  2064. //If there has been no websocket activity for a while, send a no-op
  2065. if (this.mySock) {
  2066. this.sendString_('0');
  2067. }
  2068. this.resetKeepAlive();
  2069. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2070. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2071. }
  2072. /**
  2073. * Send a string over the websocket.
  2074. *
  2075. * @param str - String to send.
  2076. */
  2077. sendString_(str) {
  2078. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2079. // calls for some unknown reason. We treat these as an error and disconnect.
  2080. // See https://app.asana.com/0/58926111402292/68021340250410
  2081. try {
  2082. this.mySock.send(str);
  2083. }
  2084. catch (e) {
  2085. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2086. setTimeout(this.onClosed_.bind(this), 0);
  2087. }
  2088. }
  2089. }
  2090. /**
  2091. * Number of response before we consider the connection "healthy."
  2092. */
  2093. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2094. /**
  2095. * Time to wait for the connection te become healthy before giving up.
  2096. */
  2097. WebSocketConnection.healthyTimeout = 30000;
  2098. /**
  2099. * @license
  2100. * Copyright 2017 Google LLC
  2101. *
  2102. * Licensed under the Apache License, Version 2.0 (the "License");
  2103. * you may not use this file except in compliance with the License.
  2104. * You may obtain a copy of the License at
  2105. *
  2106. * http://www.apache.org/licenses/LICENSE-2.0
  2107. *
  2108. * Unless required by applicable law or agreed to in writing, software
  2109. * distributed under the License is distributed on an "AS IS" BASIS,
  2110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2111. * See the License for the specific language governing permissions and
  2112. * limitations under the License.
  2113. */
  2114. /**
  2115. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2116. * lifecycle.
  2117. *
  2118. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2119. * they are available.
  2120. */
  2121. class TransportManager {
  2122. /**
  2123. * @param repoInfo - Metadata around the namespace we're connecting to
  2124. */
  2125. constructor(repoInfo) {
  2126. this.initTransports_(repoInfo);
  2127. }
  2128. static get ALL_TRANSPORTS() {
  2129. return [BrowserPollConnection, WebSocketConnection];
  2130. }
  2131. /**
  2132. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2133. * TransportManager has already set up transports_
  2134. */
  2135. static get IS_TRANSPORT_INITIALIZED() {
  2136. return this.globalTransportInitialized_;
  2137. }
  2138. initTransports_(repoInfo) {
  2139. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2140. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2141. if (repoInfo.webSocketOnly) {
  2142. if (!isWebSocketsAvailable) {
  2143. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2144. }
  2145. isSkipPollConnection = true;
  2146. }
  2147. if (isSkipPollConnection) {
  2148. this.transports_ = [WebSocketConnection];
  2149. }
  2150. else {
  2151. const transports = (this.transports_ = []);
  2152. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2153. if (transport && transport['isAvailable']()) {
  2154. transports.push(transport);
  2155. }
  2156. }
  2157. TransportManager.globalTransportInitialized_ = true;
  2158. }
  2159. }
  2160. /**
  2161. * @returns The constructor for the initial transport to use
  2162. */
  2163. initialTransport() {
  2164. if (this.transports_.length > 0) {
  2165. return this.transports_[0];
  2166. }
  2167. else {
  2168. throw new Error('No transports available');
  2169. }
  2170. }
  2171. /**
  2172. * @returns The constructor for the next transport, or null
  2173. */
  2174. upgradeTransport() {
  2175. if (this.transports_.length > 1) {
  2176. return this.transports_[1];
  2177. }
  2178. else {
  2179. return null;
  2180. }
  2181. }
  2182. }
  2183. // Keeps track of whether the TransportManager has already chosen a transport to use
  2184. TransportManager.globalTransportInitialized_ = false;
  2185. /**
  2186. * @license
  2187. * Copyright 2017 Google LLC
  2188. *
  2189. * Licensed under the Apache License, Version 2.0 (the "License");
  2190. * you may not use this file except in compliance with the License.
  2191. * You may obtain a copy of the License at
  2192. *
  2193. * http://www.apache.org/licenses/LICENSE-2.0
  2194. *
  2195. * Unless required by applicable law or agreed to in writing, software
  2196. * distributed under the License is distributed on an "AS IS" BASIS,
  2197. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2198. * See the License for the specific language governing permissions and
  2199. * limitations under the License.
  2200. */
  2201. // Abort upgrade attempt if it takes longer than 60s.
  2202. const UPGRADE_TIMEOUT = 60000;
  2203. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2204. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2205. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2206. // 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)
  2207. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2208. // but we've sent/received enough bytes, we don't cancel the connection.
  2209. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2210. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2211. const MESSAGE_TYPE = 't';
  2212. const MESSAGE_DATA = 'd';
  2213. const CONTROL_SHUTDOWN = 's';
  2214. const CONTROL_RESET = 'r';
  2215. const CONTROL_ERROR = 'e';
  2216. const CONTROL_PONG = 'o';
  2217. const SWITCH_ACK = 'a';
  2218. const END_TRANSMISSION = 'n';
  2219. const PING = 'p';
  2220. const SERVER_HELLO = 'h';
  2221. /**
  2222. * Creates a new real-time connection to the server using whichever method works
  2223. * best in the current browser.
  2224. */
  2225. class Connection {
  2226. /**
  2227. * @param id - an id for this connection
  2228. * @param repoInfo_ - the info for the endpoint to connect to
  2229. * @param applicationId_ - the Firebase App ID for this project
  2230. * @param appCheckToken_ - The App Check Token for this device.
  2231. * @param authToken_ - The auth token for this session.
  2232. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2233. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2234. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2235. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2236. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2237. */
  2238. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2239. this.id = id;
  2240. this.repoInfo_ = repoInfo_;
  2241. this.applicationId_ = applicationId_;
  2242. this.appCheckToken_ = appCheckToken_;
  2243. this.authToken_ = authToken_;
  2244. this.onMessage_ = onMessage_;
  2245. this.onReady_ = onReady_;
  2246. this.onDisconnect_ = onDisconnect_;
  2247. this.onKill_ = onKill_;
  2248. this.lastSessionId = lastSessionId;
  2249. this.connectionCount = 0;
  2250. this.pendingDataMessages = [];
  2251. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2252. this.log_ = logWrapper('c:' + this.id + ':');
  2253. this.transportManager_ = new TransportManager(repoInfo_);
  2254. this.log_('Connection created');
  2255. this.start_();
  2256. }
  2257. /**
  2258. * Starts a connection attempt
  2259. */
  2260. start_() {
  2261. const conn = this.transportManager_.initialTransport();
  2262. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2263. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2264. // can consider the transport healthy.
  2265. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2266. const onMessageReceived = this.connReceiver_(this.conn_);
  2267. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2268. this.tx_ = this.conn_;
  2269. this.rx_ = this.conn_;
  2270. this.secondaryConn_ = null;
  2271. this.isHealthy_ = false;
  2272. /*
  2273. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2274. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2275. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2276. * still have the context of your originating frame.
  2277. */
  2278. setTimeout(() => {
  2279. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2280. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2281. }, Math.floor(0));
  2282. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2283. if (healthyTimeoutMS > 0) {
  2284. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2285. this.healthyTimeout_ = null;
  2286. if (!this.isHealthy_) {
  2287. if (this.conn_ &&
  2288. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2289. this.log_('Connection exceeded healthy timeout but has received ' +
  2290. this.conn_.bytesReceived +
  2291. ' bytes. Marking connection healthy.');
  2292. this.isHealthy_ = true;
  2293. this.conn_.markConnectionHealthy();
  2294. }
  2295. else if (this.conn_ &&
  2296. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2297. this.log_('Connection exceeded healthy timeout but has sent ' +
  2298. this.conn_.bytesSent +
  2299. ' bytes. Leaving connection alive.');
  2300. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2301. // the server.
  2302. }
  2303. else {
  2304. this.log_('Closing unhealthy connection after timeout.');
  2305. this.close();
  2306. }
  2307. }
  2308. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2309. }, Math.floor(healthyTimeoutMS));
  2310. }
  2311. }
  2312. nextTransportId_() {
  2313. return 'c:' + this.id + ':' + this.connectionCount++;
  2314. }
  2315. disconnReceiver_(conn) {
  2316. return everConnected => {
  2317. if (conn === this.conn_) {
  2318. this.onConnectionLost_(everConnected);
  2319. }
  2320. else if (conn === this.secondaryConn_) {
  2321. this.log_('Secondary connection lost.');
  2322. this.onSecondaryConnectionLost_();
  2323. }
  2324. else {
  2325. this.log_('closing an old connection');
  2326. }
  2327. };
  2328. }
  2329. connReceiver_(conn) {
  2330. return (message) => {
  2331. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2332. if (conn === this.rx_) {
  2333. this.onPrimaryMessageReceived_(message);
  2334. }
  2335. else if (conn === this.secondaryConn_) {
  2336. this.onSecondaryMessageReceived_(message);
  2337. }
  2338. else {
  2339. this.log_('message on old connection');
  2340. }
  2341. }
  2342. };
  2343. }
  2344. /**
  2345. * @param dataMsg - An arbitrary data message to be sent to the server
  2346. */
  2347. sendRequest(dataMsg) {
  2348. // wrap in a data message envelope and send it on
  2349. const msg = { t: 'd', d: dataMsg };
  2350. this.sendData_(msg);
  2351. }
  2352. tryCleanupConnection() {
  2353. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2354. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2355. this.conn_ = this.secondaryConn_;
  2356. this.secondaryConn_ = null;
  2357. // the server will shutdown the old connection
  2358. }
  2359. }
  2360. onSecondaryControl_(controlData) {
  2361. if (MESSAGE_TYPE in controlData) {
  2362. const cmd = controlData[MESSAGE_TYPE];
  2363. if (cmd === SWITCH_ACK) {
  2364. this.upgradeIfSecondaryHealthy_();
  2365. }
  2366. else if (cmd === CONTROL_RESET) {
  2367. // Most likely the session wasn't valid. Abandon the switch attempt
  2368. this.log_('Got a reset on secondary, closing it');
  2369. this.secondaryConn_.close();
  2370. // If we were already using this connection for something, than we need to fully close
  2371. if (this.tx_ === this.secondaryConn_ ||
  2372. this.rx_ === this.secondaryConn_) {
  2373. this.close();
  2374. }
  2375. }
  2376. else if (cmd === CONTROL_PONG) {
  2377. this.log_('got pong on secondary.');
  2378. this.secondaryResponsesRequired_--;
  2379. this.upgradeIfSecondaryHealthy_();
  2380. }
  2381. }
  2382. }
  2383. onSecondaryMessageReceived_(parsedData) {
  2384. const layer = requireKey('t', parsedData);
  2385. const data = requireKey('d', parsedData);
  2386. if (layer === 'c') {
  2387. this.onSecondaryControl_(data);
  2388. }
  2389. else if (layer === 'd') {
  2390. // got a data message, but we're still second connection. Need to buffer it up
  2391. this.pendingDataMessages.push(data);
  2392. }
  2393. else {
  2394. throw new Error('Unknown protocol layer: ' + layer);
  2395. }
  2396. }
  2397. upgradeIfSecondaryHealthy_() {
  2398. if (this.secondaryResponsesRequired_ <= 0) {
  2399. this.log_('Secondary connection is healthy.');
  2400. this.isHealthy_ = true;
  2401. this.secondaryConn_.markConnectionHealthy();
  2402. this.proceedWithUpgrade_();
  2403. }
  2404. else {
  2405. // Send a ping to make sure the connection is healthy.
  2406. this.log_('sending ping on secondary.');
  2407. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2408. }
  2409. }
  2410. proceedWithUpgrade_() {
  2411. // tell this connection to consider itself open
  2412. this.secondaryConn_.start();
  2413. // send ack
  2414. this.log_('sending client ack on secondary');
  2415. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2416. // send end packet on primary transport, switch to sending on this one
  2417. // can receive on this one, buffer responses until end received on primary transport
  2418. this.log_('Ending transmission on primary');
  2419. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2420. this.tx_ = this.secondaryConn_;
  2421. this.tryCleanupConnection();
  2422. }
  2423. onPrimaryMessageReceived_(parsedData) {
  2424. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2425. const layer = requireKey('t', parsedData);
  2426. const data = requireKey('d', parsedData);
  2427. if (layer === 'c') {
  2428. this.onControl_(data);
  2429. }
  2430. else if (layer === 'd') {
  2431. this.onDataMessage_(data);
  2432. }
  2433. }
  2434. onDataMessage_(message) {
  2435. this.onPrimaryResponse_();
  2436. // We don't do anything with data messages, just kick them up a level
  2437. this.onMessage_(message);
  2438. }
  2439. onPrimaryResponse_() {
  2440. if (!this.isHealthy_) {
  2441. this.primaryResponsesRequired_--;
  2442. if (this.primaryResponsesRequired_ <= 0) {
  2443. this.log_('Primary connection is healthy.');
  2444. this.isHealthy_ = true;
  2445. this.conn_.markConnectionHealthy();
  2446. }
  2447. }
  2448. }
  2449. onControl_(controlData) {
  2450. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2451. if (MESSAGE_DATA in controlData) {
  2452. const payload = controlData[MESSAGE_DATA];
  2453. if (cmd === SERVER_HELLO) {
  2454. const handshakePayload = Object.assign({}, payload);
  2455. if (this.repoInfo_.isUsingEmulator) {
  2456. // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.
  2457. handshakePayload.h = this.repoInfo_.host;
  2458. }
  2459. this.onHandshake_(handshakePayload);
  2460. }
  2461. else if (cmd === END_TRANSMISSION) {
  2462. this.log_('recvd end transmission on primary');
  2463. this.rx_ = this.secondaryConn_;
  2464. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2465. this.onDataMessage_(this.pendingDataMessages[i]);
  2466. }
  2467. this.pendingDataMessages = [];
  2468. this.tryCleanupConnection();
  2469. }
  2470. else if (cmd === CONTROL_SHUTDOWN) {
  2471. // This was previously the 'onKill' callback passed to the lower-level connection
  2472. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2473. this.onConnectionShutdown_(payload);
  2474. }
  2475. else if (cmd === CONTROL_RESET) {
  2476. // payload in this case is the host we should contact
  2477. this.onReset_(payload);
  2478. }
  2479. else if (cmd === CONTROL_ERROR) {
  2480. error('Server Error: ' + payload);
  2481. }
  2482. else if (cmd === CONTROL_PONG) {
  2483. this.log_('got pong on primary.');
  2484. this.onPrimaryResponse_();
  2485. this.sendPingOnPrimaryIfNecessary_();
  2486. }
  2487. else {
  2488. error('Unknown control packet command: ' + cmd);
  2489. }
  2490. }
  2491. }
  2492. /**
  2493. * @param handshake - The handshake data returned from the server
  2494. */
  2495. onHandshake_(handshake) {
  2496. const timestamp = handshake.ts;
  2497. const version = handshake.v;
  2498. const host = handshake.h;
  2499. this.sessionId = handshake.s;
  2500. this.repoInfo_.host = host;
  2501. // if we've already closed the connection, then don't bother trying to progress further
  2502. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2503. this.conn_.start();
  2504. this.onConnectionEstablished_(this.conn_, timestamp);
  2505. if (PROTOCOL_VERSION !== version) {
  2506. warn('Protocol version mismatch detected');
  2507. }
  2508. // TODO: do we want to upgrade? when? maybe a delay?
  2509. this.tryStartUpgrade_();
  2510. }
  2511. }
  2512. tryStartUpgrade_() {
  2513. const conn = this.transportManager_.upgradeTransport();
  2514. if (conn) {
  2515. this.startUpgrade_(conn);
  2516. }
  2517. }
  2518. startUpgrade_(conn) {
  2519. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2520. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2521. // can consider the transport healthy.
  2522. this.secondaryResponsesRequired_ =
  2523. conn['responsesRequiredToBeHealthy'] || 0;
  2524. const onMessage = this.connReceiver_(this.secondaryConn_);
  2525. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2526. this.secondaryConn_.open(onMessage, onDisconnect);
  2527. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2528. setTimeoutNonBlocking(() => {
  2529. if (this.secondaryConn_) {
  2530. this.log_('Timed out trying to upgrade.');
  2531. this.secondaryConn_.close();
  2532. }
  2533. }, Math.floor(UPGRADE_TIMEOUT));
  2534. }
  2535. onReset_(host) {
  2536. this.log_('Reset packet received. New host: ' + host);
  2537. this.repoInfo_.host = host;
  2538. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2539. // We don't currently support resets after the connection has already been established
  2540. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2541. this.close();
  2542. }
  2543. else {
  2544. // Close whatever connections we have open and start again.
  2545. this.closeConnections_();
  2546. this.start_();
  2547. }
  2548. }
  2549. onConnectionEstablished_(conn, timestamp) {
  2550. this.log_('Realtime connection established.');
  2551. this.conn_ = conn;
  2552. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2553. if (this.onReady_) {
  2554. this.onReady_(timestamp, this.sessionId);
  2555. this.onReady_ = null;
  2556. }
  2557. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2558. // send some pings.
  2559. if (this.primaryResponsesRequired_ === 0) {
  2560. this.log_('Primary connection is healthy.');
  2561. this.isHealthy_ = true;
  2562. }
  2563. else {
  2564. setTimeoutNonBlocking(() => {
  2565. this.sendPingOnPrimaryIfNecessary_();
  2566. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2567. }
  2568. }
  2569. sendPingOnPrimaryIfNecessary_() {
  2570. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2571. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2572. this.log_('sending ping on primary.');
  2573. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2574. }
  2575. }
  2576. onSecondaryConnectionLost_() {
  2577. const conn = this.secondaryConn_;
  2578. this.secondaryConn_ = null;
  2579. if (this.tx_ === conn || this.rx_ === conn) {
  2580. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2581. this.close();
  2582. }
  2583. }
  2584. /**
  2585. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2586. * we should flush the host cache
  2587. */
  2588. onConnectionLost_(everConnected) {
  2589. this.conn_ = null;
  2590. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2591. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2592. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2593. this.log_('Realtime connection failed.');
  2594. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2595. if (this.repoInfo_.isCacheableHost()) {
  2596. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2597. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2598. this.repoInfo_.internalHost = this.repoInfo_.host;
  2599. }
  2600. }
  2601. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2602. this.log_('Realtime connection lost.');
  2603. }
  2604. this.close();
  2605. }
  2606. onConnectionShutdown_(reason) {
  2607. this.log_('Connection shutdown command received. Shutting down...');
  2608. if (this.onKill_) {
  2609. this.onKill_(reason);
  2610. this.onKill_ = null;
  2611. }
  2612. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2613. // so clear the callback.
  2614. this.onDisconnect_ = null;
  2615. this.close();
  2616. }
  2617. sendData_(data) {
  2618. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2619. throw 'Connection is not connected';
  2620. }
  2621. else {
  2622. this.tx_.send(data);
  2623. }
  2624. }
  2625. /**
  2626. * Cleans up this connection, calling the appropriate callbacks
  2627. */
  2628. close() {
  2629. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2630. this.log_('Closing realtime connection.');
  2631. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2632. this.closeConnections_();
  2633. if (this.onDisconnect_) {
  2634. this.onDisconnect_();
  2635. this.onDisconnect_ = null;
  2636. }
  2637. }
  2638. }
  2639. closeConnections_() {
  2640. this.log_('Shutting down all connections');
  2641. if (this.conn_) {
  2642. this.conn_.close();
  2643. this.conn_ = null;
  2644. }
  2645. if (this.secondaryConn_) {
  2646. this.secondaryConn_.close();
  2647. this.secondaryConn_ = null;
  2648. }
  2649. if (this.healthyTimeout_) {
  2650. clearTimeout(this.healthyTimeout_);
  2651. this.healthyTimeout_ = null;
  2652. }
  2653. }
  2654. }
  2655. /**
  2656. * @license
  2657. * Copyright 2017 Google LLC
  2658. *
  2659. * Licensed under the Apache License, Version 2.0 (the "License");
  2660. * you may not use this file except in compliance with the License.
  2661. * You may obtain a copy of the License at
  2662. *
  2663. * http://www.apache.org/licenses/LICENSE-2.0
  2664. *
  2665. * Unless required by applicable law or agreed to in writing, software
  2666. * distributed under the License is distributed on an "AS IS" BASIS,
  2667. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2668. * See the License for the specific language governing permissions and
  2669. * limitations under the License.
  2670. */
  2671. /**
  2672. * Interface defining the set of actions that can be performed against the Firebase server
  2673. * (basically corresponds to our wire protocol).
  2674. *
  2675. * @interface
  2676. */
  2677. class ServerActions {
  2678. put(pathString, data, onComplete, hash) { }
  2679. merge(pathString, data, onComplete, hash) { }
  2680. /**
  2681. * Refreshes the auth token for the current connection.
  2682. * @param token - The authentication token
  2683. */
  2684. refreshAuthToken(token) { }
  2685. /**
  2686. * Refreshes the app check token for the current connection.
  2687. * @param token The app check token
  2688. */
  2689. refreshAppCheckToken(token) { }
  2690. onDisconnectPut(pathString, data, onComplete) { }
  2691. onDisconnectMerge(pathString, data, onComplete) { }
  2692. onDisconnectCancel(pathString, onComplete) { }
  2693. reportStats(stats) { }
  2694. }
  2695. /**
  2696. * @license
  2697. * Copyright 2017 Google LLC
  2698. *
  2699. * Licensed under the Apache License, Version 2.0 (the "License");
  2700. * you may not use this file except in compliance with the License.
  2701. * You may obtain a copy of the License at
  2702. *
  2703. * http://www.apache.org/licenses/LICENSE-2.0
  2704. *
  2705. * Unless required by applicable law or agreed to in writing, software
  2706. * distributed under the License is distributed on an "AS IS" BASIS,
  2707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2708. * See the License for the specific language governing permissions and
  2709. * limitations under the License.
  2710. */
  2711. /**
  2712. * Base class to be used if you want to emit events. Call the constructor with
  2713. * the set of allowed event names.
  2714. */
  2715. class EventEmitter {
  2716. constructor(allowedEvents_) {
  2717. this.allowedEvents_ = allowedEvents_;
  2718. this.listeners_ = {};
  2719. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2720. }
  2721. /**
  2722. * To be called by derived classes to trigger events.
  2723. */
  2724. trigger(eventType, ...varArgs) {
  2725. if (Array.isArray(this.listeners_[eventType])) {
  2726. // Clone the list, since callbacks could add/remove listeners.
  2727. const listeners = [...this.listeners_[eventType]];
  2728. for (let i = 0; i < listeners.length; i++) {
  2729. listeners[i].callback.apply(listeners[i].context, varArgs);
  2730. }
  2731. }
  2732. }
  2733. on(eventType, callback, context) {
  2734. this.validateEventType_(eventType);
  2735. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2736. this.listeners_[eventType].push({ callback, context });
  2737. const eventData = this.getInitialEvent(eventType);
  2738. if (eventData) {
  2739. callback.apply(context, eventData);
  2740. }
  2741. }
  2742. off(eventType, callback, context) {
  2743. this.validateEventType_(eventType);
  2744. const listeners = this.listeners_[eventType] || [];
  2745. for (let i = 0; i < listeners.length; i++) {
  2746. if (listeners[i].callback === callback &&
  2747. (!context || context === listeners[i].context)) {
  2748. listeners.splice(i, 1);
  2749. return;
  2750. }
  2751. }
  2752. }
  2753. validateEventType_(eventType) {
  2754. util.assert(this.allowedEvents_.find(et => {
  2755. return et === eventType;
  2756. }), 'Unknown event: ' + eventType);
  2757. }
  2758. }
  2759. /**
  2760. * @license
  2761. * Copyright 2017 Google LLC
  2762. *
  2763. * Licensed under the Apache License, Version 2.0 (the "License");
  2764. * you may not use this file except in compliance with the License.
  2765. * You may obtain a copy of the License at
  2766. *
  2767. * http://www.apache.org/licenses/LICENSE-2.0
  2768. *
  2769. * Unless required by applicable law or agreed to in writing, software
  2770. * distributed under the License is distributed on an "AS IS" BASIS,
  2771. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2772. * See the License for the specific language governing permissions and
  2773. * limitations under the License.
  2774. */
  2775. /**
  2776. * Monitors online state (as reported by window.online/offline events).
  2777. *
  2778. * The expectation is that this could have many false positives (thinks we are online
  2779. * when we're not), but no false negatives. So we can safely use it to determine when
  2780. * we definitely cannot reach the internet.
  2781. */
  2782. class OnlineMonitor extends EventEmitter {
  2783. constructor() {
  2784. super(['online']);
  2785. this.online_ = true;
  2786. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2787. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2788. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2789. // for Cordova.
  2790. if (typeof window !== 'undefined' &&
  2791. typeof window.addEventListener !== 'undefined' &&
  2792. !util.isMobileCordova()) {
  2793. window.addEventListener('online', () => {
  2794. if (!this.online_) {
  2795. this.online_ = true;
  2796. this.trigger('online', true);
  2797. }
  2798. }, false);
  2799. window.addEventListener('offline', () => {
  2800. if (this.online_) {
  2801. this.online_ = false;
  2802. this.trigger('online', false);
  2803. }
  2804. }, false);
  2805. }
  2806. }
  2807. static getInstance() {
  2808. return new OnlineMonitor();
  2809. }
  2810. getInitialEvent(eventType) {
  2811. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2812. return [this.online_];
  2813. }
  2814. currentlyOnline() {
  2815. return this.online_;
  2816. }
  2817. }
  2818. /**
  2819. * @license
  2820. * Copyright 2017 Google LLC
  2821. *
  2822. * Licensed under the Apache License, Version 2.0 (the "License");
  2823. * you may not use this file except in compliance with the License.
  2824. * You may obtain a copy of the License at
  2825. *
  2826. * http://www.apache.org/licenses/LICENSE-2.0
  2827. *
  2828. * Unless required by applicable law or agreed to in writing, software
  2829. * distributed under the License is distributed on an "AS IS" BASIS,
  2830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2831. * See the License for the specific language governing permissions and
  2832. * limitations under the License.
  2833. */
  2834. /** Maximum key depth. */
  2835. const MAX_PATH_DEPTH = 32;
  2836. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2837. const MAX_PATH_LENGTH_BYTES = 768;
  2838. /**
  2839. * An immutable object representing a parsed path. It's immutable so that you
  2840. * can pass them around to other functions without worrying about them changing
  2841. * it.
  2842. */
  2843. class Path {
  2844. /**
  2845. * @param pathOrString - Path string to parse, or another path, or the raw
  2846. * tokens array
  2847. */
  2848. constructor(pathOrString, pieceNum) {
  2849. if (pieceNum === void 0) {
  2850. this.pieces_ = pathOrString.split('/');
  2851. // Remove empty pieces.
  2852. let copyTo = 0;
  2853. for (let i = 0; i < this.pieces_.length; i++) {
  2854. if (this.pieces_[i].length > 0) {
  2855. this.pieces_[copyTo] = this.pieces_[i];
  2856. copyTo++;
  2857. }
  2858. }
  2859. this.pieces_.length = copyTo;
  2860. this.pieceNum_ = 0;
  2861. }
  2862. else {
  2863. this.pieces_ = pathOrString;
  2864. this.pieceNum_ = pieceNum;
  2865. }
  2866. }
  2867. toString() {
  2868. let pathString = '';
  2869. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2870. if (this.pieces_[i] !== '') {
  2871. pathString += '/' + this.pieces_[i];
  2872. }
  2873. }
  2874. return pathString || '/';
  2875. }
  2876. }
  2877. function newEmptyPath() {
  2878. return new Path('');
  2879. }
  2880. function pathGetFront(path) {
  2881. if (path.pieceNum_ >= path.pieces_.length) {
  2882. return null;
  2883. }
  2884. return path.pieces_[path.pieceNum_];
  2885. }
  2886. /**
  2887. * @returns The number of segments in this path
  2888. */
  2889. function pathGetLength(path) {
  2890. return path.pieces_.length - path.pieceNum_;
  2891. }
  2892. function pathPopFront(path) {
  2893. let pieceNum = path.pieceNum_;
  2894. if (pieceNum < path.pieces_.length) {
  2895. pieceNum++;
  2896. }
  2897. return new Path(path.pieces_, pieceNum);
  2898. }
  2899. function pathGetBack(path) {
  2900. if (path.pieceNum_ < path.pieces_.length) {
  2901. return path.pieces_[path.pieces_.length - 1];
  2902. }
  2903. return null;
  2904. }
  2905. function pathToUrlEncodedString(path) {
  2906. let pathString = '';
  2907. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2908. if (path.pieces_[i] !== '') {
  2909. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2910. }
  2911. }
  2912. return pathString || '/';
  2913. }
  2914. /**
  2915. * Shallow copy of the parts of the path.
  2916. *
  2917. */
  2918. function pathSlice(path, begin = 0) {
  2919. return path.pieces_.slice(path.pieceNum_ + begin);
  2920. }
  2921. function pathParent(path) {
  2922. if (path.pieceNum_ >= path.pieces_.length) {
  2923. return null;
  2924. }
  2925. const pieces = [];
  2926. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2927. pieces.push(path.pieces_[i]);
  2928. }
  2929. return new Path(pieces, 0);
  2930. }
  2931. function pathChild(path, childPathObj) {
  2932. const pieces = [];
  2933. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2934. pieces.push(path.pieces_[i]);
  2935. }
  2936. if (childPathObj instanceof Path) {
  2937. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2938. pieces.push(childPathObj.pieces_[i]);
  2939. }
  2940. }
  2941. else {
  2942. const childPieces = childPathObj.split('/');
  2943. for (let i = 0; i < childPieces.length; i++) {
  2944. if (childPieces[i].length > 0) {
  2945. pieces.push(childPieces[i]);
  2946. }
  2947. }
  2948. }
  2949. return new Path(pieces, 0);
  2950. }
  2951. /**
  2952. * @returns True if there are no segments in this path
  2953. */
  2954. function pathIsEmpty(path) {
  2955. return path.pieceNum_ >= path.pieces_.length;
  2956. }
  2957. /**
  2958. * @returns The path from outerPath to innerPath
  2959. */
  2960. function newRelativePath(outerPath, innerPath) {
  2961. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2962. if (outer === null) {
  2963. return innerPath;
  2964. }
  2965. else if (outer === inner) {
  2966. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2967. }
  2968. else {
  2969. throw new Error('INTERNAL ERROR: innerPath (' +
  2970. innerPath +
  2971. ') is not within ' +
  2972. 'outerPath (' +
  2973. outerPath +
  2974. ')');
  2975. }
  2976. }
  2977. /**
  2978. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2979. */
  2980. function pathCompare(left, right) {
  2981. const leftKeys = pathSlice(left, 0);
  2982. const rightKeys = pathSlice(right, 0);
  2983. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2984. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2985. if (cmp !== 0) {
  2986. return cmp;
  2987. }
  2988. }
  2989. if (leftKeys.length === rightKeys.length) {
  2990. return 0;
  2991. }
  2992. return leftKeys.length < rightKeys.length ? -1 : 1;
  2993. }
  2994. /**
  2995. * @returns true if paths are the same.
  2996. */
  2997. function pathEquals(path, other) {
  2998. if (pathGetLength(path) !== pathGetLength(other)) {
  2999. return false;
  3000. }
  3001. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3002. if (path.pieces_[i] !== other.pieces_[j]) {
  3003. return false;
  3004. }
  3005. }
  3006. return true;
  3007. }
  3008. /**
  3009. * @returns True if this path is a parent of (or the same as) other
  3010. */
  3011. function pathContains(path, other) {
  3012. let i = path.pieceNum_;
  3013. let j = other.pieceNum_;
  3014. if (pathGetLength(path) > pathGetLength(other)) {
  3015. return false;
  3016. }
  3017. while (i < path.pieces_.length) {
  3018. if (path.pieces_[i] !== other.pieces_[j]) {
  3019. return false;
  3020. }
  3021. ++i;
  3022. ++j;
  3023. }
  3024. return true;
  3025. }
  3026. /**
  3027. * Dynamic (mutable) path used to count path lengths.
  3028. *
  3029. * This class is used to efficiently check paths for valid
  3030. * length (in UTF8 bytes) and depth (used in path validation).
  3031. *
  3032. * Throws Error exception if path is ever invalid.
  3033. *
  3034. * The definition of a path always begins with '/'.
  3035. */
  3036. class ValidationPath {
  3037. /**
  3038. * @param path - Initial Path.
  3039. * @param errorPrefix_ - Prefix for any error messages.
  3040. */
  3041. constructor(path, errorPrefix_) {
  3042. this.errorPrefix_ = errorPrefix_;
  3043. this.parts_ = pathSlice(path, 0);
  3044. /** Initialize to number of '/' chars needed in path. */
  3045. this.byteLength_ = Math.max(1, this.parts_.length);
  3046. for (let i = 0; i < this.parts_.length; i++) {
  3047. this.byteLength_ += util.stringLength(this.parts_[i]);
  3048. }
  3049. validationPathCheckValid(this);
  3050. }
  3051. }
  3052. function validationPathPush(validationPath, child) {
  3053. // Count the needed '/'
  3054. if (validationPath.parts_.length > 0) {
  3055. validationPath.byteLength_ += 1;
  3056. }
  3057. validationPath.parts_.push(child);
  3058. validationPath.byteLength_ += util.stringLength(child);
  3059. validationPathCheckValid(validationPath);
  3060. }
  3061. function validationPathPop(validationPath) {
  3062. const last = validationPath.parts_.pop();
  3063. validationPath.byteLength_ -= util.stringLength(last);
  3064. // Un-count the previous '/'
  3065. if (validationPath.parts_.length > 0) {
  3066. validationPath.byteLength_ -= 1;
  3067. }
  3068. }
  3069. function validationPathCheckValid(validationPath) {
  3070. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3071. throw new Error(validationPath.errorPrefix_ +
  3072. 'has a key path longer than ' +
  3073. MAX_PATH_LENGTH_BYTES +
  3074. ' bytes (' +
  3075. validationPath.byteLength_ +
  3076. ').');
  3077. }
  3078. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3079. throw new Error(validationPath.errorPrefix_ +
  3080. 'path specified exceeds the maximum depth that can be written (' +
  3081. MAX_PATH_DEPTH +
  3082. ') or object contains a cycle ' +
  3083. validationPathToErrorString(validationPath));
  3084. }
  3085. }
  3086. /**
  3087. * String for use in error messages - uses '.' notation for path.
  3088. */
  3089. function validationPathToErrorString(validationPath) {
  3090. if (validationPath.parts_.length === 0) {
  3091. return '';
  3092. }
  3093. return "in property '" + validationPath.parts_.join('.') + "'";
  3094. }
  3095. /**
  3096. * @license
  3097. * Copyright 2017 Google LLC
  3098. *
  3099. * Licensed under the Apache License, Version 2.0 (the "License");
  3100. * you may not use this file except in compliance with the License.
  3101. * You may obtain a copy of the License at
  3102. *
  3103. * http://www.apache.org/licenses/LICENSE-2.0
  3104. *
  3105. * Unless required by applicable law or agreed to in writing, software
  3106. * distributed under the License is distributed on an "AS IS" BASIS,
  3107. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3108. * See the License for the specific language governing permissions and
  3109. * limitations under the License.
  3110. */
  3111. class VisibilityMonitor extends EventEmitter {
  3112. constructor() {
  3113. super(['visible']);
  3114. let hidden;
  3115. let visibilityChange;
  3116. if (typeof document !== 'undefined' &&
  3117. typeof document.addEventListener !== 'undefined') {
  3118. if (typeof document['hidden'] !== 'undefined') {
  3119. // Opera 12.10 and Firefox 18 and later support
  3120. visibilityChange = 'visibilitychange';
  3121. hidden = 'hidden';
  3122. }
  3123. else if (typeof document['mozHidden'] !== 'undefined') {
  3124. visibilityChange = 'mozvisibilitychange';
  3125. hidden = 'mozHidden';
  3126. }
  3127. else if (typeof document['msHidden'] !== 'undefined') {
  3128. visibilityChange = 'msvisibilitychange';
  3129. hidden = 'msHidden';
  3130. }
  3131. else if (typeof document['webkitHidden'] !== 'undefined') {
  3132. visibilityChange = 'webkitvisibilitychange';
  3133. hidden = 'webkitHidden';
  3134. }
  3135. }
  3136. // Initially, we always assume we are visible. This ensures that in browsers
  3137. // without page visibility support or in cases where we are never visible
  3138. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3139. // reconnects
  3140. this.visible_ = true;
  3141. if (visibilityChange) {
  3142. document.addEventListener(visibilityChange, () => {
  3143. const visible = !document[hidden];
  3144. if (visible !== this.visible_) {
  3145. this.visible_ = visible;
  3146. this.trigger('visible', visible);
  3147. }
  3148. }, false);
  3149. }
  3150. }
  3151. static getInstance() {
  3152. return new VisibilityMonitor();
  3153. }
  3154. getInitialEvent(eventType) {
  3155. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3156. return [this.visible_];
  3157. }
  3158. }
  3159. /**
  3160. * @license
  3161. * Copyright 2017 Google LLC
  3162. *
  3163. * Licensed under the Apache License, Version 2.0 (the "License");
  3164. * you may not use this file except in compliance with the License.
  3165. * You may obtain a copy of the License at
  3166. *
  3167. * http://www.apache.org/licenses/LICENSE-2.0
  3168. *
  3169. * Unless required by applicable law or agreed to in writing, software
  3170. * distributed under the License is distributed on an "AS IS" BASIS,
  3171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3172. * See the License for the specific language governing permissions and
  3173. * limitations under the License.
  3174. */
  3175. const RECONNECT_MIN_DELAY = 1000;
  3176. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3177. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3178. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3179. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3180. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3181. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3182. const INVALID_TOKEN_THRESHOLD = 3;
  3183. /**
  3184. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3185. *
  3186. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3187. * in quotes to make sure the closure compiler does not minify them.
  3188. */
  3189. class PersistentConnection extends ServerActions {
  3190. /**
  3191. * @param repoInfo_ - Data about the namespace we are connecting to
  3192. * @param applicationId_ - The Firebase App ID for this project
  3193. * @param onDataUpdate_ - A callback for new data from the server
  3194. */
  3195. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3196. super();
  3197. this.repoInfo_ = repoInfo_;
  3198. this.applicationId_ = applicationId_;
  3199. this.onDataUpdate_ = onDataUpdate_;
  3200. this.onConnectStatus_ = onConnectStatus_;
  3201. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3202. this.authTokenProvider_ = authTokenProvider_;
  3203. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3204. this.authOverride_ = authOverride_;
  3205. // Used for diagnostic logging.
  3206. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3207. this.log_ = logWrapper('p:' + this.id + ':');
  3208. this.interruptReasons_ = {};
  3209. this.listens = new Map();
  3210. this.outstandingPuts_ = [];
  3211. this.outstandingGets_ = [];
  3212. this.outstandingPutCount_ = 0;
  3213. this.outstandingGetCount_ = 0;
  3214. this.onDisconnectRequestQueue_ = [];
  3215. this.connected_ = false;
  3216. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3217. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3218. this.securityDebugCallback_ = null;
  3219. this.lastSessionId = null;
  3220. this.establishConnectionTimer_ = null;
  3221. this.visible_ = false;
  3222. // Before we get connected, we keep a queue of pending messages to send.
  3223. this.requestCBHash_ = {};
  3224. this.requestNumber_ = 0;
  3225. this.realtime_ = null;
  3226. this.authToken_ = null;
  3227. this.appCheckToken_ = null;
  3228. this.forceTokenRefresh_ = false;
  3229. this.invalidAuthTokenCount_ = 0;
  3230. this.invalidAppCheckTokenCount_ = 0;
  3231. this.firstConnection_ = true;
  3232. this.lastConnectionAttemptTime_ = null;
  3233. this.lastConnectionEstablishedTime_ = null;
  3234. if (authOverride_ && !util.isNodeSdk()) {
  3235. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3236. }
  3237. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3238. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3239. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3240. }
  3241. }
  3242. sendRequest(action, body, onResponse) {
  3243. const curReqNum = ++this.requestNumber_;
  3244. const msg = { r: curReqNum, a: action, b: body };
  3245. this.log_(util.stringify(msg));
  3246. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3247. this.realtime_.sendRequest(msg);
  3248. if (onResponse) {
  3249. this.requestCBHash_[curReqNum] = onResponse;
  3250. }
  3251. }
  3252. get(query) {
  3253. this.initConnection_();
  3254. const deferred = new util.Deferred();
  3255. const request = {
  3256. p: query._path.toString(),
  3257. q: query._queryObject
  3258. };
  3259. const outstandingGet = {
  3260. action: 'g',
  3261. request,
  3262. onComplete: (message) => {
  3263. const payload = message['d'];
  3264. if (message['s'] === 'ok') {
  3265. deferred.resolve(payload);
  3266. }
  3267. else {
  3268. deferred.reject(payload);
  3269. }
  3270. }
  3271. };
  3272. this.outstandingGets_.push(outstandingGet);
  3273. this.outstandingGetCount_++;
  3274. const index = this.outstandingGets_.length - 1;
  3275. if (this.connected_) {
  3276. this.sendGet_(index);
  3277. }
  3278. return deferred.promise;
  3279. }
  3280. listen(query, currentHashFn, tag, onComplete) {
  3281. this.initConnection_();
  3282. const queryId = query._queryIdentifier;
  3283. const pathString = query._path.toString();
  3284. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3285. if (!this.listens.has(pathString)) {
  3286. this.listens.set(pathString, new Map());
  3287. }
  3288. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3289. util.assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3290. const listenSpec = {
  3291. onComplete,
  3292. hashFn: currentHashFn,
  3293. query,
  3294. tag
  3295. };
  3296. this.listens.get(pathString).set(queryId, listenSpec);
  3297. if (this.connected_) {
  3298. this.sendListen_(listenSpec);
  3299. }
  3300. }
  3301. sendGet_(index) {
  3302. const get = this.outstandingGets_[index];
  3303. this.sendRequest('g', get.request, (message) => {
  3304. delete this.outstandingGets_[index];
  3305. this.outstandingGetCount_--;
  3306. if (this.outstandingGetCount_ === 0) {
  3307. this.outstandingGets_ = [];
  3308. }
  3309. if (get.onComplete) {
  3310. get.onComplete(message);
  3311. }
  3312. });
  3313. }
  3314. sendListen_(listenSpec) {
  3315. const query = listenSpec.query;
  3316. const pathString = query._path.toString();
  3317. const queryId = query._queryIdentifier;
  3318. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3319. const req = { /*path*/ p: pathString };
  3320. const action = 'q';
  3321. // Only bother to send query if it's non-default.
  3322. if (listenSpec.tag) {
  3323. req['q'] = query._queryObject;
  3324. req['t'] = listenSpec.tag;
  3325. }
  3326. req[ /*hash*/'h'] = listenSpec.hashFn();
  3327. this.sendRequest(action, req, (message) => {
  3328. const payload = message[ /*data*/'d'];
  3329. const status = message[ /*status*/'s'];
  3330. // print warnings in any case...
  3331. PersistentConnection.warnOnListenWarnings_(payload, query);
  3332. const currentListenSpec = this.listens.get(pathString) &&
  3333. this.listens.get(pathString).get(queryId);
  3334. // only trigger actions if the listen hasn't been removed and readded
  3335. if (currentListenSpec === listenSpec) {
  3336. this.log_('listen response', message);
  3337. if (status !== 'ok') {
  3338. this.removeListen_(pathString, queryId);
  3339. }
  3340. if (listenSpec.onComplete) {
  3341. listenSpec.onComplete(status, payload);
  3342. }
  3343. }
  3344. });
  3345. }
  3346. static warnOnListenWarnings_(payload, query) {
  3347. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3348. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3349. const warnings = util.safeGet(payload, 'w');
  3350. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3351. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3352. const indexPath = query._path.toString();
  3353. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3354. `filtered on the client. Consider adding ${indexSpec} at ` +
  3355. `${indexPath} to your security rules for better performance.`);
  3356. }
  3357. }
  3358. }
  3359. refreshAuthToken(token) {
  3360. this.authToken_ = token;
  3361. this.log_('Auth token refreshed');
  3362. if (this.authToken_) {
  3363. this.tryAuth();
  3364. }
  3365. else {
  3366. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3367. //the credential so we dont become authenticated next time we connect.
  3368. if (this.connected_) {
  3369. this.sendRequest('unauth', {}, () => { });
  3370. }
  3371. }
  3372. this.reduceReconnectDelayIfAdminCredential_(token);
  3373. }
  3374. reduceReconnectDelayIfAdminCredential_(credential) {
  3375. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3376. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3377. const isFirebaseSecret = credential && credential.length === 40;
  3378. if (isFirebaseSecret || util.isAdmin(credential)) {
  3379. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3380. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3381. }
  3382. }
  3383. refreshAppCheckToken(token) {
  3384. this.appCheckToken_ = token;
  3385. this.log_('App check token refreshed');
  3386. if (this.appCheckToken_) {
  3387. this.tryAppCheck();
  3388. }
  3389. else {
  3390. //If we're connected we want to let the server know to unauthenticate us.
  3391. //If we're not connected, simply delete the credential so we dont become
  3392. // authenticated next time we connect.
  3393. if (this.connected_) {
  3394. this.sendRequest('unappeck', {}, () => { });
  3395. }
  3396. }
  3397. }
  3398. /**
  3399. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3400. * a auth revoked (the connection is closed).
  3401. */
  3402. tryAuth() {
  3403. if (this.connected_ && this.authToken_) {
  3404. const token = this.authToken_;
  3405. const authMethod = util.isValidFormat(token) ? 'auth' : 'gauth';
  3406. const requestData = { cred: token };
  3407. if (this.authOverride_ === null) {
  3408. requestData['noauth'] = true;
  3409. }
  3410. else if (typeof this.authOverride_ === 'object') {
  3411. requestData['authvar'] = this.authOverride_;
  3412. }
  3413. this.sendRequest(authMethod, requestData, (res) => {
  3414. const status = res[ /*status*/'s'];
  3415. const data = res[ /*data*/'d'] || 'error';
  3416. if (this.authToken_ === token) {
  3417. if (status === 'ok') {
  3418. this.invalidAuthTokenCount_ = 0;
  3419. }
  3420. else {
  3421. // Triggers reconnect and force refresh for auth token
  3422. this.onAuthRevoked_(status, data);
  3423. }
  3424. }
  3425. });
  3426. }
  3427. }
  3428. /**
  3429. * Attempts to authenticate with the given token. If the authentication
  3430. * attempt fails, it's triggered like the token was revoked (the connection is
  3431. * closed).
  3432. */
  3433. tryAppCheck() {
  3434. if (this.connected_ && this.appCheckToken_) {
  3435. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3436. const status = res[ /*status*/'s'];
  3437. const data = res[ /*data*/'d'] || 'error';
  3438. if (status === 'ok') {
  3439. this.invalidAppCheckTokenCount_ = 0;
  3440. }
  3441. else {
  3442. this.onAppCheckRevoked_(status, data);
  3443. }
  3444. });
  3445. }
  3446. }
  3447. /**
  3448. * @inheritDoc
  3449. */
  3450. unlisten(query, tag) {
  3451. const pathString = query._path.toString();
  3452. const queryId = query._queryIdentifier;
  3453. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3454. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3455. const listen = this.removeListen_(pathString, queryId);
  3456. if (listen && this.connected_) {
  3457. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3458. }
  3459. }
  3460. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3461. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3462. const req = { /*path*/ p: pathString };
  3463. const action = 'n';
  3464. // Only bother sending queryId if it's non-default.
  3465. if (tag) {
  3466. req['q'] = queryObj;
  3467. req['t'] = tag;
  3468. }
  3469. this.sendRequest(action, req);
  3470. }
  3471. onDisconnectPut(pathString, data, onComplete) {
  3472. this.initConnection_();
  3473. if (this.connected_) {
  3474. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3475. }
  3476. else {
  3477. this.onDisconnectRequestQueue_.push({
  3478. pathString,
  3479. action: 'o',
  3480. data,
  3481. onComplete
  3482. });
  3483. }
  3484. }
  3485. onDisconnectMerge(pathString, data, onComplete) {
  3486. this.initConnection_();
  3487. if (this.connected_) {
  3488. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3489. }
  3490. else {
  3491. this.onDisconnectRequestQueue_.push({
  3492. pathString,
  3493. action: 'om',
  3494. data,
  3495. onComplete
  3496. });
  3497. }
  3498. }
  3499. onDisconnectCancel(pathString, onComplete) {
  3500. this.initConnection_();
  3501. if (this.connected_) {
  3502. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3503. }
  3504. else {
  3505. this.onDisconnectRequestQueue_.push({
  3506. pathString,
  3507. action: 'oc',
  3508. data: null,
  3509. onComplete
  3510. });
  3511. }
  3512. }
  3513. sendOnDisconnect_(action, pathString, data, onComplete) {
  3514. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3515. this.log_('onDisconnect ' + action, request);
  3516. this.sendRequest(action, request, (response) => {
  3517. if (onComplete) {
  3518. setTimeout(() => {
  3519. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3520. }, Math.floor(0));
  3521. }
  3522. });
  3523. }
  3524. put(pathString, data, onComplete, hash) {
  3525. this.putInternal('p', pathString, data, onComplete, hash);
  3526. }
  3527. merge(pathString, data, onComplete, hash) {
  3528. this.putInternal('m', pathString, data, onComplete, hash);
  3529. }
  3530. putInternal(action, pathString, data, onComplete, hash) {
  3531. this.initConnection_();
  3532. const request = {
  3533. /*path*/ p: pathString,
  3534. /*data*/ d: data
  3535. };
  3536. if (hash !== undefined) {
  3537. request[ /*hash*/'h'] = hash;
  3538. }
  3539. // TODO: Only keep track of the most recent put for a given path?
  3540. this.outstandingPuts_.push({
  3541. action,
  3542. request,
  3543. onComplete
  3544. });
  3545. this.outstandingPutCount_++;
  3546. const index = this.outstandingPuts_.length - 1;
  3547. if (this.connected_) {
  3548. this.sendPut_(index);
  3549. }
  3550. else {
  3551. this.log_('Buffering put: ' + pathString);
  3552. }
  3553. }
  3554. sendPut_(index) {
  3555. const action = this.outstandingPuts_[index].action;
  3556. const request = this.outstandingPuts_[index].request;
  3557. const onComplete = this.outstandingPuts_[index].onComplete;
  3558. this.outstandingPuts_[index].queued = this.connected_;
  3559. this.sendRequest(action, request, (message) => {
  3560. this.log_(action + ' response', message);
  3561. delete this.outstandingPuts_[index];
  3562. this.outstandingPutCount_--;
  3563. // Clean up array occasionally.
  3564. if (this.outstandingPutCount_ === 0) {
  3565. this.outstandingPuts_ = [];
  3566. }
  3567. if (onComplete) {
  3568. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3569. }
  3570. });
  3571. }
  3572. reportStats(stats) {
  3573. // If we're not connected, we just drop the stats.
  3574. if (this.connected_) {
  3575. const request = { /*counters*/ c: stats };
  3576. this.log_('reportStats', request);
  3577. this.sendRequest(/*stats*/ 's', request, result => {
  3578. const status = result[ /*status*/'s'];
  3579. if (status !== 'ok') {
  3580. const errorReason = result[ /* data */'d'];
  3581. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3582. }
  3583. });
  3584. }
  3585. }
  3586. onDataMessage_(message) {
  3587. if ('r' in message) {
  3588. // this is a response
  3589. this.log_('from server: ' + util.stringify(message));
  3590. const reqNum = message['r'];
  3591. const onResponse = this.requestCBHash_[reqNum];
  3592. if (onResponse) {
  3593. delete this.requestCBHash_[reqNum];
  3594. onResponse(message[ /*body*/'b']);
  3595. }
  3596. }
  3597. else if ('error' in message) {
  3598. throw 'A server-side error has occurred: ' + message['error'];
  3599. }
  3600. else if ('a' in message) {
  3601. // a and b are action and body, respectively
  3602. this.onDataPush_(message['a'], message['b']);
  3603. }
  3604. }
  3605. onDataPush_(action, body) {
  3606. this.log_('handleServerMessage', action, body);
  3607. if (action === 'd') {
  3608. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3609. /*isMerge*/ false, body['t']);
  3610. }
  3611. else if (action === 'm') {
  3612. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3613. /*isMerge=*/ true, body['t']);
  3614. }
  3615. else if (action === 'c') {
  3616. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3617. }
  3618. else if (action === 'ac') {
  3619. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3620. }
  3621. else if (action === 'apc') {
  3622. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3623. }
  3624. else if (action === 'sd') {
  3625. this.onSecurityDebugPacket_(body);
  3626. }
  3627. else {
  3628. error('Unrecognized action received from server: ' +
  3629. util.stringify(action) +
  3630. '\nAre you using the latest client?');
  3631. }
  3632. }
  3633. onReady_(timestamp, sessionId) {
  3634. this.log_('connection ready');
  3635. this.connected_ = true;
  3636. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3637. this.handleTimestamp_(timestamp);
  3638. this.lastSessionId = sessionId;
  3639. if (this.firstConnection_) {
  3640. this.sendConnectStats_();
  3641. }
  3642. this.restoreState_();
  3643. this.firstConnection_ = false;
  3644. this.onConnectStatus_(true);
  3645. }
  3646. scheduleConnect_(timeout) {
  3647. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3648. if (this.establishConnectionTimer_) {
  3649. clearTimeout(this.establishConnectionTimer_);
  3650. }
  3651. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3652. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3653. this.establishConnectionTimer_ = setTimeout(() => {
  3654. this.establishConnectionTimer_ = null;
  3655. this.establishConnection_();
  3656. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3657. }, Math.floor(timeout));
  3658. }
  3659. initConnection_() {
  3660. if (!this.realtime_ && this.firstConnection_) {
  3661. this.scheduleConnect_(0);
  3662. }
  3663. }
  3664. onVisible_(visible) {
  3665. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3666. if (visible &&
  3667. !this.visible_ &&
  3668. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3669. this.log_('Window became visible. Reducing delay.');
  3670. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3671. if (!this.realtime_) {
  3672. this.scheduleConnect_(0);
  3673. }
  3674. }
  3675. this.visible_ = visible;
  3676. }
  3677. onOnline_(online) {
  3678. if (online) {
  3679. this.log_('Browser went online.');
  3680. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3681. if (!this.realtime_) {
  3682. this.scheduleConnect_(0);
  3683. }
  3684. }
  3685. else {
  3686. this.log_('Browser went offline. Killing connection.');
  3687. if (this.realtime_) {
  3688. this.realtime_.close();
  3689. }
  3690. }
  3691. }
  3692. onRealtimeDisconnect_() {
  3693. this.log_('data client disconnected');
  3694. this.connected_ = false;
  3695. this.realtime_ = null;
  3696. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3697. this.cancelSentTransactions_();
  3698. // Clear out the pending requests.
  3699. this.requestCBHash_ = {};
  3700. if (this.shouldReconnect_()) {
  3701. if (!this.visible_) {
  3702. this.log_("Window isn't visible. Delaying reconnect.");
  3703. this.reconnectDelay_ = this.maxReconnectDelay_;
  3704. this.lastConnectionAttemptTime_ = new Date().getTime();
  3705. }
  3706. else if (this.lastConnectionEstablishedTime_) {
  3707. // If we've been connected long enough, reset reconnect delay to minimum.
  3708. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3709. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3710. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3711. }
  3712. this.lastConnectionEstablishedTime_ = null;
  3713. }
  3714. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3715. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3716. reconnectDelay = Math.random() * reconnectDelay;
  3717. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3718. this.scheduleConnect_(reconnectDelay);
  3719. // Adjust reconnect delay for next time.
  3720. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3721. }
  3722. this.onConnectStatus_(false);
  3723. }
  3724. async establishConnection_() {
  3725. if (this.shouldReconnect_()) {
  3726. this.log_('Making a connection attempt');
  3727. this.lastConnectionAttemptTime_ = new Date().getTime();
  3728. this.lastConnectionEstablishedTime_ = null;
  3729. const onDataMessage = this.onDataMessage_.bind(this);
  3730. const onReady = this.onReady_.bind(this);
  3731. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3732. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3733. const lastSessionId = this.lastSessionId;
  3734. let canceled = false;
  3735. let connection = null;
  3736. const closeFn = function () {
  3737. if (connection) {
  3738. connection.close();
  3739. }
  3740. else {
  3741. canceled = true;
  3742. onDisconnect();
  3743. }
  3744. };
  3745. const sendRequestFn = function (msg) {
  3746. util.assert(connection, "sendRequest call when we're not connected not allowed.");
  3747. connection.sendRequest(msg);
  3748. };
  3749. this.realtime_ = {
  3750. close: closeFn,
  3751. sendRequest: sendRequestFn
  3752. };
  3753. const forceRefresh = this.forceTokenRefresh_;
  3754. this.forceTokenRefresh_ = false;
  3755. try {
  3756. // First fetch auth and app check token, and establish connection after
  3757. // fetching the token was successful
  3758. const [authToken, appCheckToken] = await Promise.all([
  3759. this.authTokenProvider_.getToken(forceRefresh),
  3760. this.appCheckTokenProvider_.getToken(forceRefresh)
  3761. ]);
  3762. if (!canceled) {
  3763. log('getToken() completed. Creating connection.');
  3764. this.authToken_ = authToken && authToken.accessToken;
  3765. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3766. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3767. /* onKill= */ reason => {
  3768. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3769. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3770. }, lastSessionId);
  3771. }
  3772. else {
  3773. log('getToken() completed but was canceled');
  3774. }
  3775. }
  3776. catch (error) {
  3777. this.log_('Failed to get token: ' + error);
  3778. if (!canceled) {
  3779. if (this.repoInfo_.nodeAdmin) {
  3780. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3781. // But getToken() may also just have temporarily failed, so we still want to
  3782. // continue retrying.
  3783. warn(error);
  3784. }
  3785. closeFn();
  3786. }
  3787. }
  3788. }
  3789. }
  3790. interrupt(reason) {
  3791. log('Interrupting connection for reason: ' + reason);
  3792. this.interruptReasons_[reason] = true;
  3793. if (this.realtime_) {
  3794. this.realtime_.close();
  3795. }
  3796. else {
  3797. if (this.establishConnectionTimer_) {
  3798. clearTimeout(this.establishConnectionTimer_);
  3799. this.establishConnectionTimer_ = null;
  3800. }
  3801. if (this.connected_) {
  3802. this.onRealtimeDisconnect_();
  3803. }
  3804. }
  3805. }
  3806. resume(reason) {
  3807. log('Resuming connection for reason: ' + reason);
  3808. delete this.interruptReasons_[reason];
  3809. if (util.isEmpty(this.interruptReasons_)) {
  3810. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3811. if (!this.realtime_) {
  3812. this.scheduleConnect_(0);
  3813. }
  3814. }
  3815. }
  3816. handleTimestamp_(timestamp) {
  3817. const delta = timestamp - new Date().getTime();
  3818. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3819. }
  3820. cancelSentTransactions_() {
  3821. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3822. const put = this.outstandingPuts_[i];
  3823. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3824. if (put.onComplete) {
  3825. put.onComplete('disconnect');
  3826. }
  3827. delete this.outstandingPuts_[i];
  3828. this.outstandingPutCount_--;
  3829. }
  3830. }
  3831. // Clean up array occasionally.
  3832. if (this.outstandingPutCount_ === 0) {
  3833. this.outstandingPuts_ = [];
  3834. }
  3835. }
  3836. onListenRevoked_(pathString, query) {
  3837. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3838. let queryId;
  3839. if (!query) {
  3840. queryId = 'default';
  3841. }
  3842. else {
  3843. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3844. }
  3845. const listen = this.removeListen_(pathString, queryId);
  3846. if (listen && listen.onComplete) {
  3847. listen.onComplete('permission_denied');
  3848. }
  3849. }
  3850. removeListen_(pathString, queryId) {
  3851. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3852. let listen;
  3853. if (this.listens.has(normalizedPathString)) {
  3854. const map = this.listens.get(normalizedPathString);
  3855. listen = map.get(queryId);
  3856. map.delete(queryId);
  3857. if (map.size === 0) {
  3858. this.listens.delete(normalizedPathString);
  3859. }
  3860. }
  3861. else {
  3862. // all listens for this path has already been removed
  3863. listen = undefined;
  3864. }
  3865. return listen;
  3866. }
  3867. onAuthRevoked_(statusCode, explanation) {
  3868. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3869. this.authToken_ = null;
  3870. this.forceTokenRefresh_ = true;
  3871. this.realtime_.close();
  3872. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3873. // We'll wait a couple times before logging the warning / increasing the
  3874. // retry period since oauth tokens will report as "invalid" if they're
  3875. // just expired. Plus there may be transient issues that resolve themselves.
  3876. this.invalidAuthTokenCount_++;
  3877. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3878. // Set a long reconnect delay because recovery is unlikely
  3879. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3880. // Notify the auth token provider that the token is invalid, which will log
  3881. // a warning
  3882. this.authTokenProvider_.notifyForInvalidToken();
  3883. }
  3884. }
  3885. }
  3886. onAppCheckRevoked_(statusCode, explanation) {
  3887. log('App check token revoked: ' + statusCode + '/' + explanation);
  3888. this.appCheckToken_ = null;
  3889. this.forceTokenRefresh_ = true;
  3890. // Note: We don't close the connection as the developer may not have
  3891. // enforcement enabled. The backend closes connections with enforcements.
  3892. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3893. // We'll wait a couple times before logging the warning / increasing the
  3894. // retry period since oauth tokens will report as "invalid" if they're
  3895. // just expired. Plus there may be transient issues that resolve themselves.
  3896. this.invalidAppCheckTokenCount_++;
  3897. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3898. this.appCheckTokenProvider_.notifyForInvalidToken();
  3899. }
  3900. }
  3901. }
  3902. onSecurityDebugPacket_(body) {
  3903. if (this.securityDebugCallback_) {
  3904. this.securityDebugCallback_(body);
  3905. }
  3906. else {
  3907. if ('msg' in body) {
  3908. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3909. }
  3910. }
  3911. }
  3912. restoreState_() {
  3913. //Re-authenticate ourselves if we have a credential stored.
  3914. this.tryAuth();
  3915. this.tryAppCheck();
  3916. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3917. // make sure to send listens before puts.
  3918. for (const queries of this.listens.values()) {
  3919. for (const listenSpec of queries.values()) {
  3920. this.sendListen_(listenSpec);
  3921. }
  3922. }
  3923. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3924. if (this.outstandingPuts_[i]) {
  3925. this.sendPut_(i);
  3926. }
  3927. }
  3928. while (this.onDisconnectRequestQueue_.length) {
  3929. const request = this.onDisconnectRequestQueue_.shift();
  3930. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3931. }
  3932. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3933. if (this.outstandingGets_[i]) {
  3934. this.sendGet_(i);
  3935. }
  3936. }
  3937. }
  3938. /**
  3939. * Sends client stats for first connection
  3940. */
  3941. sendConnectStats_() {
  3942. const stats = {};
  3943. let clientName = 'js';
  3944. if (util.isNodeSdk()) {
  3945. if (this.repoInfo_.nodeAdmin) {
  3946. clientName = 'admin_node';
  3947. }
  3948. else {
  3949. clientName = 'node';
  3950. }
  3951. }
  3952. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3953. if (util.isMobileCordova()) {
  3954. stats['framework.cordova'] = 1;
  3955. }
  3956. else if (util.isReactNative()) {
  3957. stats['framework.reactnative'] = 1;
  3958. }
  3959. this.reportStats(stats);
  3960. }
  3961. shouldReconnect_() {
  3962. const online = OnlineMonitor.getInstance().currentlyOnline();
  3963. return util.isEmpty(this.interruptReasons_) && online;
  3964. }
  3965. }
  3966. PersistentConnection.nextPersistentConnectionId_ = 0;
  3967. /**
  3968. * Counter for number of connections created. Mainly used for tagging in the logs
  3969. */
  3970. PersistentConnection.nextConnectionId_ = 0;
  3971. /**
  3972. * @license
  3973. * Copyright 2017 Google LLC
  3974. *
  3975. * Licensed under the Apache License, Version 2.0 (the "License");
  3976. * you may not use this file except in compliance with the License.
  3977. * You may obtain a copy of the License at
  3978. *
  3979. * http://www.apache.org/licenses/LICENSE-2.0
  3980. *
  3981. * Unless required by applicable law or agreed to in writing, software
  3982. * distributed under the License is distributed on an "AS IS" BASIS,
  3983. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3984. * See the License for the specific language governing permissions and
  3985. * limitations under the License.
  3986. */
  3987. class NamedNode {
  3988. constructor(name, node) {
  3989. this.name = name;
  3990. this.node = node;
  3991. }
  3992. static Wrap(name, node) {
  3993. return new NamedNode(name, node);
  3994. }
  3995. }
  3996. /**
  3997. * @license
  3998. * Copyright 2017 Google LLC
  3999. *
  4000. * Licensed under the Apache License, Version 2.0 (the "License");
  4001. * you may not use this file except in compliance with the License.
  4002. * You may obtain a copy of the License at
  4003. *
  4004. * http://www.apache.org/licenses/LICENSE-2.0
  4005. *
  4006. * Unless required by applicable law or agreed to in writing, software
  4007. * distributed under the License is distributed on an "AS IS" BASIS,
  4008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4009. * See the License for the specific language governing permissions and
  4010. * limitations under the License.
  4011. */
  4012. class Index {
  4013. /**
  4014. * @returns A standalone comparison function for
  4015. * this index
  4016. */
  4017. getCompare() {
  4018. return this.compare.bind(this);
  4019. }
  4020. /**
  4021. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4022. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4023. *
  4024. *
  4025. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4026. */
  4027. indexedValueChanged(oldNode, newNode) {
  4028. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4029. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4030. return this.compare(oldWrapped, newWrapped) !== 0;
  4031. }
  4032. /**
  4033. * @returns a node wrapper that will sort equal to or less than
  4034. * any other node wrapper, using this index
  4035. */
  4036. minPost() {
  4037. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4038. return NamedNode.MIN;
  4039. }
  4040. }
  4041. /**
  4042. * @license
  4043. * Copyright 2017 Google LLC
  4044. *
  4045. * Licensed under the Apache License, Version 2.0 (the "License");
  4046. * you may not use this file except in compliance with the License.
  4047. * You may obtain a copy of the License at
  4048. *
  4049. * http://www.apache.org/licenses/LICENSE-2.0
  4050. *
  4051. * Unless required by applicable law or agreed to in writing, software
  4052. * distributed under the License is distributed on an "AS IS" BASIS,
  4053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4054. * See the License for the specific language governing permissions and
  4055. * limitations under the License.
  4056. */
  4057. let __EMPTY_NODE;
  4058. class KeyIndex extends Index {
  4059. static get __EMPTY_NODE() {
  4060. return __EMPTY_NODE;
  4061. }
  4062. static set __EMPTY_NODE(val) {
  4063. __EMPTY_NODE = val;
  4064. }
  4065. compare(a, b) {
  4066. return nameCompare(a.name, b.name);
  4067. }
  4068. isDefinedOn(node) {
  4069. // We could probably return true here (since every node has a key), but it's never called
  4070. // so just leaving unimplemented for now.
  4071. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4072. }
  4073. indexedValueChanged(oldNode, newNode) {
  4074. return false; // The key for a node never changes.
  4075. }
  4076. minPost() {
  4077. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4078. return NamedNode.MIN;
  4079. }
  4080. maxPost() {
  4081. // TODO: This should really be created once and cached in a static property, but
  4082. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4083. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4084. }
  4085. makePost(indexValue, name) {
  4086. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4087. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4088. return new NamedNode(indexValue, __EMPTY_NODE);
  4089. }
  4090. /**
  4091. * @returns String representation for inclusion in a query spec
  4092. */
  4093. toString() {
  4094. return '.key';
  4095. }
  4096. }
  4097. const KEY_INDEX = new KeyIndex();
  4098. /**
  4099. * @license
  4100. * Copyright 2017 Google LLC
  4101. *
  4102. * Licensed under the Apache License, Version 2.0 (the "License");
  4103. * you may not use this file except in compliance with the License.
  4104. * You may obtain a copy of the License at
  4105. *
  4106. * http://www.apache.org/licenses/LICENSE-2.0
  4107. *
  4108. * Unless required by applicable law or agreed to in writing, software
  4109. * distributed under the License is distributed on an "AS IS" BASIS,
  4110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4111. * See the License for the specific language governing permissions and
  4112. * limitations under the License.
  4113. */
  4114. /**
  4115. * An iterator over an LLRBNode.
  4116. */
  4117. class SortedMapIterator {
  4118. /**
  4119. * @param node - Node to iterate.
  4120. * @param isReverse_ - Whether or not to iterate in reverse
  4121. */
  4122. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4123. this.isReverse_ = isReverse_;
  4124. this.resultGenerator_ = resultGenerator_;
  4125. this.nodeStack_ = [];
  4126. let cmp = 1;
  4127. while (!node.isEmpty()) {
  4128. node = node;
  4129. cmp = startKey ? comparator(node.key, startKey) : 1;
  4130. // flip the comparison if we're going in reverse
  4131. if (isReverse_) {
  4132. cmp *= -1;
  4133. }
  4134. if (cmp < 0) {
  4135. // This node is less than our start key. ignore it
  4136. if (this.isReverse_) {
  4137. node = node.left;
  4138. }
  4139. else {
  4140. node = node.right;
  4141. }
  4142. }
  4143. else if (cmp === 0) {
  4144. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4145. this.nodeStack_.push(node);
  4146. break;
  4147. }
  4148. else {
  4149. // This node is greater than our start key, add it to the stack and move to the next one
  4150. this.nodeStack_.push(node);
  4151. if (this.isReverse_) {
  4152. node = node.right;
  4153. }
  4154. else {
  4155. node = node.left;
  4156. }
  4157. }
  4158. }
  4159. }
  4160. getNext() {
  4161. if (this.nodeStack_.length === 0) {
  4162. return null;
  4163. }
  4164. let node = this.nodeStack_.pop();
  4165. let result;
  4166. if (this.resultGenerator_) {
  4167. result = this.resultGenerator_(node.key, node.value);
  4168. }
  4169. else {
  4170. result = { key: node.key, value: node.value };
  4171. }
  4172. if (this.isReverse_) {
  4173. node = node.left;
  4174. while (!node.isEmpty()) {
  4175. this.nodeStack_.push(node);
  4176. node = node.right;
  4177. }
  4178. }
  4179. else {
  4180. node = node.right;
  4181. while (!node.isEmpty()) {
  4182. this.nodeStack_.push(node);
  4183. node = node.left;
  4184. }
  4185. }
  4186. return result;
  4187. }
  4188. hasNext() {
  4189. return this.nodeStack_.length > 0;
  4190. }
  4191. peek() {
  4192. if (this.nodeStack_.length === 0) {
  4193. return null;
  4194. }
  4195. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4196. if (this.resultGenerator_) {
  4197. return this.resultGenerator_(node.key, node.value);
  4198. }
  4199. else {
  4200. return { key: node.key, value: node.value };
  4201. }
  4202. }
  4203. }
  4204. /**
  4205. * Represents a node in a Left-leaning Red-Black tree.
  4206. */
  4207. class LLRBNode {
  4208. /**
  4209. * @param key - Key associated with this node.
  4210. * @param value - Value associated with this node.
  4211. * @param color - Whether this node is red.
  4212. * @param left - Left child.
  4213. * @param right - Right child.
  4214. */
  4215. constructor(key, value, color, left, right) {
  4216. this.key = key;
  4217. this.value = value;
  4218. this.color = color != null ? color : LLRBNode.RED;
  4219. this.left =
  4220. left != null ? left : SortedMap.EMPTY_NODE;
  4221. this.right =
  4222. right != null ? right : SortedMap.EMPTY_NODE;
  4223. }
  4224. /**
  4225. * Returns a copy of the current node, optionally replacing pieces of it.
  4226. *
  4227. * @param key - New key for the node, or null.
  4228. * @param value - New value for the node, or null.
  4229. * @param color - New color for the node, or null.
  4230. * @param left - New left child for the node, or null.
  4231. * @param right - New right child for the node, or null.
  4232. * @returns The node copy.
  4233. */
  4234. copy(key, value, color, left, right) {
  4235. 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);
  4236. }
  4237. /**
  4238. * @returns The total number of nodes in the tree.
  4239. */
  4240. count() {
  4241. return this.left.count() + 1 + this.right.count();
  4242. }
  4243. /**
  4244. * @returns True if the tree is empty.
  4245. */
  4246. isEmpty() {
  4247. return false;
  4248. }
  4249. /**
  4250. * Traverses the tree in key order and calls the specified action function
  4251. * for each node.
  4252. *
  4253. * @param action - Callback function to be called for each
  4254. * node. If it returns true, traversal is aborted.
  4255. * @returns The first truthy value returned by action, or the last falsey
  4256. * value returned by action
  4257. */
  4258. inorderTraversal(action) {
  4259. return (this.left.inorderTraversal(action) ||
  4260. !!action(this.key, this.value) ||
  4261. this.right.inorderTraversal(action));
  4262. }
  4263. /**
  4264. * Traverses the tree in reverse key order and calls the specified action function
  4265. * for each node.
  4266. *
  4267. * @param action - Callback function to be called for each
  4268. * node. If it returns true, traversal is aborted.
  4269. * @returns True if traversal was aborted.
  4270. */
  4271. reverseTraversal(action) {
  4272. return (this.right.reverseTraversal(action) ||
  4273. action(this.key, this.value) ||
  4274. this.left.reverseTraversal(action));
  4275. }
  4276. /**
  4277. * @returns The minimum node in the tree.
  4278. */
  4279. min_() {
  4280. if (this.left.isEmpty()) {
  4281. return this;
  4282. }
  4283. else {
  4284. return this.left.min_();
  4285. }
  4286. }
  4287. /**
  4288. * @returns The maximum key in the tree.
  4289. */
  4290. minKey() {
  4291. return this.min_().key;
  4292. }
  4293. /**
  4294. * @returns The maximum key in the tree.
  4295. */
  4296. maxKey() {
  4297. if (this.right.isEmpty()) {
  4298. return this.key;
  4299. }
  4300. else {
  4301. return this.right.maxKey();
  4302. }
  4303. }
  4304. /**
  4305. * @param key - Key to insert.
  4306. * @param value - Value to insert.
  4307. * @param comparator - Comparator.
  4308. * @returns New tree, with the key/value added.
  4309. */
  4310. insert(key, value, comparator) {
  4311. let n = this;
  4312. const cmp = comparator(key, n.key);
  4313. if (cmp < 0) {
  4314. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4315. }
  4316. else if (cmp === 0) {
  4317. n = n.copy(null, value, null, null, null);
  4318. }
  4319. else {
  4320. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4321. }
  4322. return n.fixUp_();
  4323. }
  4324. /**
  4325. * @returns New tree, with the minimum key removed.
  4326. */
  4327. removeMin_() {
  4328. if (this.left.isEmpty()) {
  4329. return SortedMap.EMPTY_NODE;
  4330. }
  4331. let n = this;
  4332. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4333. n = n.moveRedLeft_();
  4334. }
  4335. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4336. return n.fixUp_();
  4337. }
  4338. /**
  4339. * @param key - The key of the item to remove.
  4340. * @param comparator - Comparator.
  4341. * @returns New tree, with the specified item removed.
  4342. */
  4343. remove(key, comparator) {
  4344. let n, smallest;
  4345. n = this;
  4346. if (comparator(key, n.key) < 0) {
  4347. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4348. n = n.moveRedLeft_();
  4349. }
  4350. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4351. }
  4352. else {
  4353. if (n.left.isRed_()) {
  4354. n = n.rotateRight_();
  4355. }
  4356. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4357. n = n.moveRedRight_();
  4358. }
  4359. if (comparator(key, n.key) === 0) {
  4360. if (n.right.isEmpty()) {
  4361. return SortedMap.EMPTY_NODE;
  4362. }
  4363. else {
  4364. smallest = n.right.min_();
  4365. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4366. }
  4367. }
  4368. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4369. }
  4370. return n.fixUp_();
  4371. }
  4372. /**
  4373. * @returns Whether this is a RED node.
  4374. */
  4375. isRed_() {
  4376. return this.color;
  4377. }
  4378. /**
  4379. * @returns New tree after performing any needed rotations.
  4380. */
  4381. fixUp_() {
  4382. let n = this;
  4383. if (n.right.isRed_() && !n.left.isRed_()) {
  4384. n = n.rotateLeft_();
  4385. }
  4386. if (n.left.isRed_() && n.left.left.isRed_()) {
  4387. n = n.rotateRight_();
  4388. }
  4389. if (n.left.isRed_() && n.right.isRed_()) {
  4390. n = n.colorFlip_();
  4391. }
  4392. return n;
  4393. }
  4394. /**
  4395. * @returns New tree, after moveRedLeft.
  4396. */
  4397. moveRedLeft_() {
  4398. let n = this.colorFlip_();
  4399. if (n.right.left.isRed_()) {
  4400. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4401. n = n.rotateLeft_();
  4402. n = n.colorFlip_();
  4403. }
  4404. return n;
  4405. }
  4406. /**
  4407. * @returns New tree, after moveRedRight.
  4408. */
  4409. moveRedRight_() {
  4410. let n = this.colorFlip_();
  4411. if (n.left.left.isRed_()) {
  4412. n = n.rotateRight_();
  4413. n = n.colorFlip_();
  4414. }
  4415. return n;
  4416. }
  4417. /**
  4418. * @returns New tree, after rotateLeft.
  4419. */
  4420. rotateLeft_() {
  4421. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4422. return this.right.copy(null, null, this.color, nl, null);
  4423. }
  4424. /**
  4425. * @returns New tree, after rotateRight.
  4426. */
  4427. rotateRight_() {
  4428. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4429. return this.left.copy(null, null, this.color, null, nr);
  4430. }
  4431. /**
  4432. * @returns Newt ree, after colorFlip.
  4433. */
  4434. colorFlip_() {
  4435. const left = this.left.copy(null, null, !this.left.color, null, null);
  4436. const right = this.right.copy(null, null, !this.right.color, null, null);
  4437. return this.copy(null, null, !this.color, left, right);
  4438. }
  4439. /**
  4440. * For testing.
  4441. *
  4442. * @returns True if all is well.
  4443. */
  4444. checkMaxDepth_() {
  4445. const blackDepth = this.check_();
  4446. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4447. }
  4448. check_() {
  4449. if (this.isRed_() && this.left.isRed_()) {
  4450. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4451. }
  4452. if (this.right.isRed_()) {
  4453. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4454. }
  4455. const blackDepth = this.left.check_();
  4456. if (blackDepth !== this.right.check_()) {
  4457. throw new Error('Black depths differ');
  4458. }
  4459. else {
  4460. return blackDepth + (this.isRed_() ? 0 : 1);
  4461. }
  4462. }
  4463. }
  4464. LLRBNode.RED = true;
  4465. LLRBNode.BLACK = false;
  4466. /**
  4467. * Represents an empty node (a leaf node in the Red-Black Tree).
  4468. */
  4469. class LLRBEmptyNode {
  4470. /**
  4471. * Returns a copy of the current node.
  4472. *
  4473. * @returns The node copy.
  4474. */
  4475. copy(key, value, color, left, right) {
  4476. return this;
  4477. }
  4478. /**
  4479. * Returns a copy of the tree, with the specified key/value added.
  4480. *
  4481. * @param key - Key to be added.
  4482. * @param value - Value to be added.
  4483. * @param comparator - Comparator.
  4484. * @returns New tree, with item added.
  4485. */
  4486. insert(key, value, comparator) {
  4487. return new LLRBNode(key, value, null);
  4488. }
  4489. /**
  4490. * Returns a copy of the tree, with the specified key removed.
  4491. *
  4492. * @param key - The key to remove.
  4493. * @param comparator - Comparator.
  4494. * @returns New tree, with item removed.
  4495. */
  4496. remove(key, comparator) {
  4497. return this;
  4498. }
  4499. /**
  4500. * @returns The total number of nodes in the tree.
  4501. */
  4502. count() {
  4503. return 0;
  4504. }
  4505. /**
  4506. * @returns True if the tree is empty.
  4507. */
  4508. isEmpty() {
  4509. return true;
  4510. }
  4511. /**
  4512. * Traverses the tree in key order and calls the specified action function
  4513. * for each node.
  4514. *
  4515. * @param action - Callback function to be called for each
  4516. * node. If it returns true, traversal is aborted.
  4517. * @returns True if traversal was aborted.
  4518. */
  4519. inorderTraversal(action) {
  4520. return false;
  4521. }
  4522. /**
  4523. * Traverses the tree in reverse key order and calls the specified action function
  4524. * for each node.
  4525. *
  4526. * @param action - Callback function to be called for each
  4527. * node. If it returns true, traversal is aborted.
  4528. * @returns True if traversal was aborted.
  4529. */
  4530. reverseTraversal(action) {
  4531. return false;
  4532. }
  4533. minKey() {
  4534. return null;
  4535. }
  4536. maxKey() {
  4537. return null;
  4538. }
  4539. check_() {
  4540. return 0;
  4541. }
  4542. /**
  4543. * @returns Whether this node is red.
  4544. */
  4545. isRed_() {
  4546. return false;
  4547. }
  4548. }
  4549. /**
  4550. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4551. * tree.
  4552. */
  4553. class SortedMap {
  4554. /**
  4555. * @param comparator_ - Key comparator.
  4556. * @param root_ - Optional root node for the map.
  4557. */
  4558. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4559. this.comparator_ = comparator_;
  4560. this.root_ = root_;
  4561. }
  4562. /**
  4563. * Returns a copy of the map, with the specified key/value added or replaced.
  4564. * (TODO: We should perhaps rename this method to 'put')
  4565. *
  4566. * @param key - Key to be added.
  4567. * @param value - Value to be added.
  4568. * @returns New map, with item added.
  4569. */
  4570. insert(key, value) {
  4571. return new SortedMap(this.comparator_, this.root_
  4572. .insert(key, value, this.comparator_)
  4573. .copy(null, null, LLRBNode.BLACK, null, null));
  4574. }
  4575. /**
  4576. * Returns a copy of the map, with the specified key removed.
  4577. *
  4578. * @param key - The key to remove.
  4579. * @returns New map, with item removed.
  4580. */
  4581. remove(key) {
  4582. return new SortedMap(this.comparator_, this.root_
  4583. .remove(key, this.comparator_)
  4584. .copy(null, null, LLRBNode.BLACK, null, null));
  4585. }
  4586. /**
  4587. * Returns the value of the node with the given key, or null.
  4588. *
  4589. * @param key - The key to look up.
  4590. * @returns The value of the node with the given key, or null if the
  4591. * key doesn't exist.
  4592. */
  4593. get(key) {
  4594. let cmp;
  4595. let node = this.root_;
  4596. while (!node.isEmpty()) {
  4597. cmp = this.comparator_(key, node.key);
  4598. if (cmp === 0) {
  4599. return node.value;
  4600. }
  4601. else if (cmp < 0) {
  4602. node = node.left;
  4603. }
  4604. else if (cmp > 0) {
  4605. node = node.right;
  4606. }
  4607. }
  4608. return null;
  4609. }
  4610. /**
  4611. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4612. * @param key - The key to find the predecessor of
  4613. * @returns The predecessor key.
  4614. */
  4615. getPredecessorKey(key) {
  4616. let cmp, node = this.root_, rightParent = null;
  4617. while (!node.isEmpty()) {
  4618. cmp = this.comparator_(key, node.key);
  4619. if (cmp === 0) {
  4620. if (!node.left.isEmpty()) {
  4621. node = node.left;
  4622. while (!node.right.isEmpty()) {
  4623. node = node.right;
  4624. }
  4625. return node.key;
  4626. }
  4627. else if (rightParent) {
  4628. return rightParent.key;
  4629. }
  4630. else {
  4631. return null; // first item.
  4632. }
  4633. }
  4634. else if (cmp < 0) {
  4635. node = node.left;
  4636. }
  4637. else if (cmp > 0) {
  4638. rightParent = node;
  4639. node = node.right;
  4640. }
  4641. }
  4642. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4643. }
  4644. /**
  4645. * @returns True if the map is empty.
  4646. */
  4647. isEmpty() {
  4648. return this.root_.isEmpty();
  4649. }
  4650. /**
  4651. * @returns The total number of nodes in the map.
  4652. */
  4653. count() {
  4654. return this.root_.count();
  4655. }
  4656. /**
  4657. * @returns The minimum key in the map.
  4658. */
  4659. minKey() {
  4660. return this.root_.minKey();
  4661. }
  4662. /**
  4663. * @returns The maximum key in the map.
  4664. */
  4665. maxKey() {
  4666. return this.root_.maxKey();
  4667. }
  4668. /**
  4669. * Traverses the map in key order and calls the specified action function
  4670. * for each key/value pair.
  4671. *
  4672. * @param action - Callback function to be called
  4673. * for each key/value pair. If action returns true, traversal is aborted.
  4674. * @returns The first truthy value returned by action, or the last falsey
  4675. * value returned by action
  4676. */
  4677. inorderTraversal(action) {
  4678. return this.root_.inorderTraversal(action);
  4679. }
  4680. /**
  4681. * Traverses the map in reverse key order and calls the specified action function
  4682. * for each key/value pair.
  4683. *
  4684. * @param action - Callback function to be called
  4685. * for each key/value pair. If action returns true, traversal is aborted.
  4686. * @returns True if the traversal was aborted.
  4687. */
  4688. reverseTraversal(action) {
  4689. return this.root_.reverseTraversal(action);
  4690. }
  4691. /**
  4692. * Returns an iterator over the SortedMap.
  4693. * @returns The iterator.
  4694. */
  4695. getIterator(resultGenerator) {
  4696. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4697. }
  4698. getIteratorFrom(key, resultGenerator) {
  4699. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4700. }
  4701. getReverseIteratorFrom(key, resultGenerator) {
  4702. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4703. }
  4704. getReverseIterator(resultGenerator) {
  4705. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4706. }
  4707. }
  4708. /**
  4709. * Always use the same empty node, to reduce memory.
  4710. */
  4711. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4712. /**
  4713. * @license
  4714. * Copyright 2017 Google LLC
  4715. *
  4716. * Licensed under the Apache License, Version 2.0 (the "License");
  4717. * you may not use this file except in compliance with the License.
  4718. * You may obtain a copy of the License at
  4719. *
  4720. * http://www.apache.org/licenses/LICENSE-2.0
  4721. *
  4722. * Unless required by applicable law or agreed to in writing, software
  4723. * distributed under the License is distributed on an "AS IS" BASIS,
  4724. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4725. * See the License for the specific language governing permissions and
  4726. * limitations under the License.
  4727. */
  4728. function NAME_ONLY_COMPARATOR(left, right) {
  4729. return nameCompare(left.name, right.name);
  4730. }
  4731. function NAME_COMPARATOR(left, right) {
  4732. return nameCompare(left, right);
  4733. }
  4734. /**
  4735. * @license
  4736. * Copyright 2017 Google LLC
  4737. *
  4738. * Licensed under the Apache License, Version 2.0 (the "License");
  4739. * you may not use this file except in compliance with the License.
  4740. * You may obtain a copy of the License at
  4741. *
  4742. * http://www.apache.org/licenses/LICENSE-2.0
  4743. *
  4744. * Unless required by applicable law or agreed to in writing, software
  4745. * distributed under the License is distributed on an "AS IS" BASIS,
  4746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4747. * See the License for the specific language governing permissions and
  4748. * limitations under the License.
  4749. */
  4750. let MAX_NODE$2;
  4751. function setMaxNode$1(val) {
  4752. MAX_NODE$2 = val;
  4753. }
  4754. const priorityHashText = function (priority) {
  4755. if (typeof priority === 'number') {
  4756. return 'number:' + doubleToIEEE754String(priority);
  4757. }
  4758. else {
  4759. return 'string:' + priority;
  4760. }
  4761. };
  4762. /**
  4763. * Validates that a priority snapshot Node is valid.
  4764. */
  4765. const validatePriorityNode = function (priorityNode) {
  4766. if (priorityNode.isLeafNode()) {
  4767. const val = priorityNode.val();
  4768. util.assert(typeof val === 'string' ||
  4769. typeof val === 'number' ||
  4770. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4771. }
  4772. else {
  4773. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4774. }
  4775. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4776. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4777. };
  4778. /**
  4779. * @license
  4780. * Copyright 2017 Google LLC
  4781. *
  4782. * Licensed under the Apache License, Version 2.0 (the "License");
  4783. * you may not use this file except in compliance with the License.
  4784. * You may obtain a copy of the License at
  4785. *
  4786. * http://www.apache.org/licenses/LICENSE-2.0
  4787. *
  4788. * Unless required by applicable law or agreed to in writing, software
  4789. * distributed under the License is distributed on an "AS IS" BASIS,
  4790. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4791. * See the License for the specific language governing permissions and
  4792. * limitations under the License.
  4793. */
  4794. let __childrenNodeConstructor;
  4795. /**
  4796. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4797. * implements Node and stores the value of the node (a string,
  4798. * number, or boolean) accessible via getValue().
  4799. */
  4800. class LeafNode {
  4801. /**
  4802. * @param value_ - The value to store in this leaf node. The object type is
  4803. * possible in the event of a deferred value
  4804. * @param priorityNode_ - The priority of this node.
  4805. */
  4806. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4807. this.value_ = value_;
  4808. this.priorityNode_ = priorityNode_;
  4809. this.lazyHash_ = null;
  4810. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4811. validatePriorityNode(this.priorityNode_);
  4812. }
  4813. static set __childrenNodeConstructor(val) {
  4814. __childrenNodeConstructor = val;
  4815. }
  4816. static get __childrenNodeConstructor() {
  4817. return __childrenNodeConstructor;
  4818. }
  4819. /** @inheritDoc */
  4820. isLeafNode() {
  4821. return true;
  4822. }
  4823. /** @inheritDoc */
  4824. getPriority() {
  4825. return this.priorityNode_;
  4826. }
  4827. /** @inheritDoc */
  4828. updatePriority(newPriorityNode) {
  4829. return new LeafNode(this.value_, newPriorityNode);
  4830. }
  4831. /** @inheritDoc */
  4832. getImmediateChild(childName) {
  4833. // Hack to treat priority as a regular child
  4834. if (childName === '.priority') {
  4835. return this.priorityNode_;
  4836. }
  4837. else {
  4838. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4839. }
  4840. }
  4841. /** @inheritDoc */
  4842. getChild(path) {
  4843. if (pathIsEmpty(path)) {
  4844. return this;
  4845. }
  4846. else if (pathGetFront(path) === '.priority') {
  4847. return this.priorityNode_;
  4848. }
  4849. else {
  4850. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4851. }
  4852. }
  4853. hasChild() {
  4854. return false;
  4855. }
  4856. /** @inheritDoc */
  4857. getPredecessorChildName(childName, childNode) {
  4858. return null;
  4859. }
  4860. /** @inheritDoc */
  4861. updateImmediateChild(childName, newChildNode) {
  4862. if (childName === '.priority') {
  4863. return this.updatePriority(newChildNode);
  4864. }
  4865. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4866. return this;
  4867. }
  4868. else {
  4869. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4870. }
  4871. }
  4872. /** @inheritDoc */
  4873. updateChild(path, newChildNode) {
  4874. const front = pathGetFront(path);
  4875. if (front === null) {
  4876. return newChildNode;
  4877. }
  4878. else if (newChildNode.isEmpty() && front !== '.priority') {
  4879. return this;
  4880. }
  4881. else {
  4882. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4883. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4884. }
  4885. }
  4886. /** @inheritDoc */
  4887. isEmpty() {
  4888. return false;
  4889. }
  4890. /** @inheritDoc */
  4891. numChildren() {
  4892. return 0;
  4893. }
  4894. /** @inheritDoc */
  4895. forEachChild(index, action) {
  4896. return false;
  4897. }
  4898. val(exportFormat) {
  4899. if (exportFormat && !this.getPriority().isEmpty()) {
  4900. return {
  4901. '.value': this.getValue(),
  4902. '.priority': this.getPriority().val()
  4903. };
  4904. }
  4905. else {
  4906. return this.getValue();
  4907. }
  4908. }
  4909. /** @inheritDoc */
  4910. hash() {
  4911. if (this.lazyHash_ === null) {
  4912. let toHash = '';
  4913. if (!this.priorityNode_.isEmpty()) {
  4914. toHash +=
  4915. 'priority:' +
  4916. priorityHashText(this.priorityNode_.val()) +
  4917. ':';
  4918. }
  4919. const type = typeof this.value_;
  4920. toHash += type + ':';
  4921. if (type === 'number') {
  4922. toHash += doubleToIEEE754String(this.value_);
  4923. }
  4924. else {
  4925. toHash += this.value_;
  4926. }
  4927. this.lazyHash_ = sha1(toHash);
  4928. }
  4929. return this.lazyHash_;
  4930. }
  4931. /**
  4932. * Returns the value of the leaf node.
  4933. * @returns The value of the node.
  4934. */
  4935. getValue() {
  4936. return this.value_;
  4937. }
  4938. compareTo(other) {
  4939. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4940. return 1;
  4941. }
  4942. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4943. return -1;
  4944. }
  4945. else {
  4946. util.assert(other.isLeafNode(), 'Unknown node type');
  4947. return this.compareToLeafNode_(other);
  4948. }
  4949. }
  4950. /**
  4951. * Comparison specifically for two leaf nodes
  4952. */
  4953. compareToLeafNode_(otherLeaf) {
  4954. const otherLeafType = typeof otherLeaf.value_;
  4955. const thisLeafType = typeof this.value_;
  4956. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4957. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4958. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4959. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4960. if (otherIndex === thisIndex) {
  4961. // Same type, compare values
  4962. if (thisLeafType === 'object') {
  4963. // Deferred value nodes are all equal, but we should also never get to this point...
  4964. return 0;
  4965. }
  4966. else {
  4967. // Note that this works because true > false, all others are number or string comparisons
  4968. if (this.value_ < otherLeaf.value_) {
  4969. return -1;
  4970. }
  4971. else if (this.value_ === otherLeaf.value_) {
  4972. return 0;
  4973. }
  4974. else {
  4975. return 1;
  4976. }
  4977. }
  4978. }
  4979. else {
  4980. return thisIndex - otherIndex;
  4981. }
  4982. }
  4983. withIndex() {
  4984. return this;
  4985. }
  4986. isIndexed() {
  4987. return true;
  4988. }
  4989. equals(other) {
  4990. if (other === this) {
  4991. return true;
  4992. }
  4993. else if (other.isLeafNode()) {
  4994. const otherLeaf = other;
  4995. return (this.value_ === otherLeaf.value_ &&
  4996. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4997. }
  4998. else {
  4999. return false;
  5000. }
  5001. }
  5002. }
  5003. /**
  5004. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5005. * the same type, the comparison falls back to their value
  5006. */
  5007. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5008. /**
  5009. * @license
  5010. * Copyright 2017 Google LLC
  5011. *
  5012. * Licensed under the Apache License, Version 2.0 (the "License");
  5013. * you may not use this file except in compliance with the License.
  5014. * You may obtain a copy of the License at
  5015. *
  5016. * http://www.apache.org/licenses/LICENSE-2.0
  5017. *
  5018. * Unless required by applicable law or agreed to in writing, software
  5019. * distributed under the License is distributed on an "AS IS" BASIS,
  5020. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5021. * See the License for the specific language governing permissions and
  5022. * limitations under the License.
  5023. */
  5024. let nodeFromJSON$1;
  5025. let MAX_NODE$1;
  5026. function setNodeFromJSON(val) {
  5027. nodeFromJSON$1 = val;
  5028. }
  5029. function setMaxNode(val) {
  5030. MAX_NODE$1 = val;
  5031. }
  5032. class PriorityIndex extends Index {
  5033. compare(a, b) {
  5034. const aPriority = a.node.getPriority();
  5035. const bPriority = b.node.getPriority();
  5036. const indexCmp = aPriority.compareTo(bPriority);
  5037. if (indexCmp === 0) {
  5038. return nameCompare(a.name, b.name);
  5039. }
  5040. else {
  5041. return indexCmp;
  5042. }
  5043. }
  5044. isDefinedOn(node) {
  5045. return !node.getPriority().isEmpty();
  5046. }
  5047. indexedValueChanged(oldNode, newNode) {
  5048. return !oldNode.getPriority().equals(newNode.getPriority());
  5049. }
  5050. minPost() {
  5051. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5052. return NamedNode.MIN;
  5053. }
  5054. maxPost() {
  5055. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5056. }
  5057. makePost(indexValue, name) {
  5058. const priorityNode = nodeFromJSON$1(indexValue);
  5059. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5060. }
  5061. /**
  5062. * @returns String representation for inclusion in a query spec
  5063. */
  5064. toString() {
  5065. return '.priority';
  5066. }
  5067. }
  5068. const PRIORITY_INDEX = new PriorityIndex();
  5069. /**
  5070. * @license
  5071. * Copyright 2017 Google LLC
  5072. *
  5073. * Licensed under the Apache License, Version 2.0 (the "License");
  5074. * you may not use this file except in compliance with the License.
  5075. * You may obtain a copy of the License at
  5076. *
  5077. * http://www.apache.org/licenses/LICENSE-2.0
  5078. *
  5079. * Unless required by applicable law or agreed to in writing, software
  5080. * distributed under the License is distributed on an "AS IS" BASIS,
  5081. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5082. * See the License for the specific language governing permissions and
  5083. * limitations under the License.
  5084. */
  5085. const LOG_2 = Math.log(2);
  5086. class Base12Num {
  5087. constructor(length) {
  5088. const logBase2 = (num) =>
  5089. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5090. parseInt((Math.log(num) / LOG_2), 10);
  5091. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5092. this.count = logBase2(length + 1);
  5093. this.current_ = this.count - 1;
  5094. const mask = bitMask(this.count);
  5095. this.bits_ = (length + 1) & mask;
  5096. }
  5097. nextBitIsOne() {
  5098. //noinspection JSBitwiseOperatorUsage
  5099. const result = !(this.bits_ & (0x1 << this.current_));
  5100. this.current_--;
  5101. return result;
  5102. }
  5103. }
  5104. /**
  5105. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5106. * function
  5107. *
  5108. * Uses the algorithm described in the paper linked here:
  5109. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5110. *
  5111. * @param childList - Unsorted list of children
  5112. * @param cmp - The comparison method to be used
  5113. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5114. * type is not NamedNode
  5115. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5116. */
  5117. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5118. childList.sort(cmp);
  5119. const buildBalancedTree = function (low, high) {
  5120. const length = high - low;
  5121. let namedNode;
  5122. let key;
  5123. if (length === 0) {
  5124. return null;
  5125. }
  5126. else if (length === 1) {
  5127. namedNode = childList[low];
  5128. key = keyFn ? keyFn(namedNode) : namedNode;
  5129. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5130. }
  5131. else {
  5132. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5133. const middle = parseInt((length / 2), 10) + low;
  5134. const left = buildBalancedTree(low, middle);
  5135. const right = buildBalancedTree(middle + 1, high);
  5136. namedNode = childList[middle];
  5137. key = keyFn ? keyFn(namedNode) : namedNode;
  5138. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5139. }
  5140. };
  5141. const buildFrom12Array = function (base12) {
  5142. let node = null;
  5143. let root = null;
  5144. let index = childList.length;
  5145. const buildPennant = function (chunkSize, color) {
  5146. const low = index - chunkSize;
  5147. const high = index;
  5148. index -= chunkSize;
  5149. const childTree = buildBalancedTree(low + 1, high);
  5150. const namedNode = childList[low];
  5151. const key = keyFn ? keyFn(namedNode) : namedNode;
  5152. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5153. };
  5154. const attachPennant = function (pennant) {
  5155. if (node) {
  5156. node.left = pennant;
  5157. node = pennant;
  5158. }
  5159. else {
  5160. root = pennant;
  5161. node = pennant;
  5162. }
  5163. };
  5164. for (let i = 0; i < base12.count; ++i) {
  5165. const isOne = base12.nextBitIsOne();
  5166. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5167. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5168. if (isOne) {
  5169. buildPennant(chunkSize, LLRBNode.BLACK);
  5170. }
  5171. else {
  5172. // current == 2
  5173. buildPennant(chunkSize, LLRBNode.BLACK);
  5174. buildPennant(chunkSize, LLRBNode.RED);
  5175. }
  5176. }
  5177. return root;
  5178. };
  5179. const base12 = new Base12Num(childList.length);
  5180. const root = buildFrom12Array(base12);
  5181. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5182. return new SortedMap(mapSortFn || cmp, root);
  5183. };
  5184. /**
  5185. * @license
  5186. * Copyright 2017 Google LLC
  5187. *
  5188. * Licensed under the Apache License, Version 2.0 (the "License");
  5189. * you may not use this file except in compliance with the License.
  5190. * You may obtain a copy of the License at
  5191. *
  5192. * http://www.apache.org/licenses/LICENSE-2.0
  5193. *
  5194. * Unless required by applicable law or agreed to in writing, software
  5195. * distributed under the License is distributed on an "AS IS" BASIS,
  5196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5197. * See the License for the specific language governing permissions and
  5198. * limitations under the License.
  5199. */
  5200. let _defaultIndexMap;
  5201. const fallbackObject = {};
  5202. class IndexMap {
  5203. constructor(indexes_, indexSet_) {
  5204. this.indexes_ = indexes_;
  5205. this.indexSet_ = indexSet_;
  5206. }
  5207. /**
  5208. * The default IndexMap for nodes without a priority
  5209. */
  5210. static get Default() {
  5211. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5212. _defaultIndexMap =
  5213. _defaultIndexMap ||
  5214. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5215. return _defaultIndexMap;
  5216. }
  5217. get(indexKey) {
  5218. const sortedMap = util.safeGet(this.indexes_, indexKey);
  5219. if (!sortedMap) {
  5220. throw new Error('No index defined for ' + indexKey);
  5221. }
  5222. if (sortedMap instanceof SortedMap) {
  5223. return sortedMap;
  5224. }
  5225. else {
  5226. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5227. // regular child map
  5228. return null;
  5229. }
  5230. }
  5231. hasIndex(indexDefinition) {
  5232. return util.contains(this.indexSet_, indexDefinition.toString());
  5233. }
  5234. addIndex(indexDefinition, existingChildren) {
  5235. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5236. const childList = [];
  5237. let sawIndexedValue = false;
  5238. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5239. let next = iter.getNext();
  5240. while (next) {
  5241. sawIndexedValue =
  5242. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5243. childList.push(next);
  5244. next = iter.getNext();
  5245. }
  5246. let newIndex;
  5247. if (sawIndexedValue) {
  5248. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5249. }
  5250. else {
  5251. newIndex = fallbackObject;
  5252. }
  5253. const indexName = indexDefinition.toString();
  5254. const newIndexSet = Object.assign({}, this.indexSet_);
  5255. newIndexSet[indexName] = indexDefinition;
  5256. const newIndexes = Object.assign({}, this.indexes_);
  5257. newIndexes[indexName] = newIndex;
  5258. return new IndexMap(newIndexes, newIndexSet);
  5259. }
  5260. /**
  5261. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5262. */
  5263. addToIndexes(namedNode, existingChildren) {
  5264. const newIndexes = util.map(this.indexes_, (indexedChildren, indexName) => {
  5265. const index = util.safeGet(this.indexSet_, indexName);
  5266. util.assert(index, 'Missing index implementation for ' + indexName);
  5267. if (indexedChildren === fallbackObject) {
  5268. // Check to see if we need to index everything
  5269. if (index.isDefinedOn(namedNode.node)) {
  5270. // We need to build this index
  5271. const childList = [];
  5272. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5273. let next = iter.getNext();
  5274. while (next) {
  5275. if (next.name !== namedNode.name) {
  5276. childList.push(next);
  5277. }
  5278. next = iter.getNext();
  5279. }
  5280. childList.push(namedNode);
  5281. return buildChildSet(childList, index.getCompare());
  5282. }
  5283. else {
  5284. // No change, this remains a fallback
  5285. return fallbackObject;
  5286. }
  5287. }
  5288. else {
  5289. const existingSnap = existingChildren.get(namedNode.name);
  5290. let newChildren = indexedChildren;
  5291. if (existingSnap) {
  5292. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5293. }
  5294. return newChildren.insert(namedNode, namedNode.node);
  5295. }
  5296. });
  5297. return new IndexMap(newIndexes, this.indexSet_);
  5298. }
  5299. /**
  5300. * Create a new IndexMap instance with the given value removed
  5301. */
  5302. removeFromIndexes(namedNode, existingChildren) {
  5303. const newIndexes = util.map(this.indexes_, (indexedChildren) => {
  5304. if (indexedChildren === fallbackObject) {
  5305. // This is the fallback. Just return it, nothing to do in this case
  5306. return indexedChildren;
  5307. }
  5308. else {
  5309. const existingSnap = existingChildren.get(namedNode.name);
  5310. if (existingSnap) {
  5311. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5312. }
  5313. else {
  5314. // No record of this child
  5315. return indexedChildren;
  5316. }
  5317. }
  5318. });
  5319. return new IndexMap(newIndexes, this.indexSet_);
  5320. }
  5321. }
  5322. /**
  5323. * @license
  5324. * Copyright 2017 Google LLC
  5325. *
  5326. * Licensed under the Apache License, Version 2.0 (the "License");
  5327. * you may not use this file except in compliance with the License.
  5328. * You may obtain a copy of the License at
  5329. *
  5330. * http://www.apache.org/licenses/LICENSE-2.0
  5331. *
  5332. * Unless required by applicable law or agreed to in writing, software
  5333. * distributed under the License is distributed on an "AS IS" BASIS,
  5334. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5335. * See the License for the specific language governing permissions and
  5336. * limitations under the License.
  5337. */
  5338. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5339. let EMPTY_NODE;
  5340. /**
  5341. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5342. * (i.e. nodes with children). It implements Node and stores the
  5343. * list of children in the children property, sorted by child name.
  5344. */
  5345. class ChildrenNode {
  5346. /**
  5347. * @param children_ - List of children of this node..
  5348. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5349. */
  5350. constructor(children_, priorityNode_, indexMap_) {
  5351. this.children_ = children_;
  5352. this.priorityNode_ = priorityNode_;
  5353. this.indexMap_ = indexMap_;
  5354. this.lazyHash_ = null;
  5355. /**
  5356. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5357. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5358. * class instead of an empty ChildrenNode.
  5359. */
  5360. if (this.priorityNode_) {
  5361. validatePriorityNode(this.priorityNode_);
  5362. }
  5363. if (this.children_.isEmpty()) {
  5364. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5365. }
  5366. }
  5367. static get EMPTY_NODE() {
  5368. return (EMPTY_NODE ||
  5369. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5370. }
  5371. /** @inheritDoc */
  5372. isLeafNode() {
  5373. return false;
  5374. }
  5375. /** @inheritDoc */
  5376. getPriority() {
  5377. return this.priorityNode_ || EMPTY_NODE;
  5378. }
  5379. /** @inheritDoc */
  5380. updatePriority(newPriorityNode) {
  5381. if (this.children_.isEmpty()) {
  5382. // Don't allow priorities on empty nodes
  5383. return this;
  5384. }
  5385. else {
  5386. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5387. }
  5388. }
  5389. /** @inheritDoc */
  5390. getImmediateChild(childName) {
  5391. // Hack to treat priority as a regular child
  5392. if (childName === '.priority') {
  5393. return this.getPriority();
  5394. }
  5395. else {
  5396. const child = this.children_.get(childName);
  5397. return child === null ? EMPTY_NODE : child;
  5398. }
  5399. }
  5400. /** @inheritDoc */
  5401. getChild(path) {
  5402. const front = pathGetFront(path);
  5403. if (front === null) {
  5404. return this;
  5405. }
  5406. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5407. }
  5408. /** @inheritDoc */
  5409. hasChild(childName) {
  5410. return this.children_.get(childName) !== null;
  5411. }
  5412. /** @inheritDoc */
  5413. updateImmediateChild(childName, newChildNode) {
  5414. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5415. if (childName === '.priority') {
  5416. return this.updatePriority(newChildNode);
  5417. }
  5418. else {
  5419. const namedNode = new NamedNode(childName, newChildNode);
  5420. let newChildren, newIndexMap;
  5421. if (newChildNode.isEmpty()) {
  5422. newChildren = this.children_.remove(childName);
  5423. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5424. }
  5425. else {
  5426. newChildren = this.children_.insert(childName, newChildNode);
  5427. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5428. }
  5429. const newPriority = newChildren.isEmpty()
  5430. ? EMPTY_NODE
  5431. : this.priorityNode_;
  5432. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5433. }
  5434. }
  5435. /** @inheritDoc */
  5436. updateChild(path, newChildNode) {
  5437. const front = pathGetFront(path);
  5438. if (front === null) {
  5439. return newChildNode;
  5440. }
  5441. else {
  5442. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5443. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5444. return this.updateImmediateChild(front, newImmediateChild);
  5445. }
  5446. }
  5447. /** @inheritDoc */
  5448. isEmpty() {
  5449. return this.children_.isEmpty();
  5450. }
  5451. /** @inheritDoc */
  5452. numChildren() {
  5453. return this.children_.count();
  5454. }
  5455. /** @inheritDoc */
  5456. val(exportFormat) {
  5457. if (this.isEmpty()) {
  5458. return null;
  5459. }
  5460. const obj = {};
  5461. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5462. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5463. obj[key] = childNode.val(exportFormat);
  5464. numKeys++;
  5465. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5466. maxKey = Math.max(maxKey, Number(key));
  5467. }
  5468. else {
  5469. allIntegerKeys = false;
  5470. }
  5471. });
  5472. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5473. // convert to array.
  5474. const array = [];
  5475. // eslint-disable-next-line guard-for-in
  5476. for (const key in obj) {
  5477. array[key] = obj[key];
  5478. }
  5479. return array;
  5480. }
  5481. else {
  5482. if (exportFormat && !this.getPriority().isEmpty()) {
  5483. obj['.priority'] = this.getPriority().val();
  5484. }
  5485. return obj;
  5486. }
  5487. }
  5488. /** @inheritDoc */
  5489. hash() {
  5490. if (this.lazyHash_ === null) {
  5491. let toHash = '';
  5492. if (!this.getPriority().isEmpty()) {
  5493. toHash +=
  5494. 'priority:' +
  5495. priorityHashText(this.getPriority().val()) +
  5496. ':';
  5497. }
  5498. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5499. const childHash = childNode.hash();
  5500. if (childHash !== '') {
  5501. toHash += ':' + key + ':' + childHash;
  5502. }
  5503. });
  5504. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5505. }
  5506. return this.lazyHash_;
  5507. }
  5508. /** @inheritDoc */
  5509. getPredecessorChildName(childName, childNode, index) {
  5510. const idx = this.resolveIndex_(index);
  5511. if (idx) {
  5512. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5513. return predecessor ? predecessor.name : null;
  5514. }
  5515. else {
  5516. return this.children_.getPredecessorKey(childName);
  5517. }
  5518. }
  5519. getFirstChildName(indexDefinition) {
  5520. const idx = this.resolveIndex_(indexDefinition);
  5521. if (idx) {
  5522. const minKey = idx.minKey();
  5523. return minKey && minKey.name;
  5524. }
  5525. else {
  5526. return this.children_.minKey();
  5527. }
  5528. }
  5529. getFirstChild(indexDefinition) {
  5530. const minKey = this.getFirstChildName(indexDefinition);
  5531. if (minKey) {
  5532. return new NamedNode(minKey, this.children_.get(minKey));
  5533. }
  5534. else {
  5535. return null;
  5536. }
  5537. }
  5538. /**
  5539. * Given an index, return the key name of the largest value we have, according to that index
  5540. */
  5541. getLastChildName(indexDefinition) {
  5542. const idx = this.resolveIndex_(indexDefinition);
  5543. if (idx) {
  5544. const maxKey = idx.maxKey();
  5545. return maxKey && maxKey.name;
  5546. }
  5547. else {
  5548. return this.children_.maxKey();
  5549. }
  5550. }
  5551. getLastChild(indexDefinition) {
  5552. const maxKey = this.getLastChildName(indexDefinition);
  5553. if (maxKey) {
  5554. return new NamedNode(maxKey, this.children_.get(maxKey));
  5555. }
  5556. else {
  5557. return null;
  5558. }
  5559. }
  5560. forEachChild(index, action) {
  5561. const idx = this.resolveIndex_(index);
  5562. if (idx) {
  5563. return idx.inorderTraversal(wrappedNode => {
  5564. return action(wrappedNode.name, wrappedNode.node);
  5565. });
  5566. }
  5567. else {
  5568. return this.children_.inorderTraversal(action);
  5569. }
  5570. }
  5571. getIterator(indexDefinition) {
  5572. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5573. }
  5574. getIteratorFrom(startPost, indexDefinition) {
  5575. const idx = this.resolveIndex_(indexDefinition);
  5576. if (idx) {
  5577. return idx.getIteratorFrom(startPost, key => key);
  5578. }
  5579. else {
  5580. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5581. let next = iterator.peek();
  5582. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5583. iterator.getNext();
  5584. next = iterator.peek();
  5585. }
  5586. return iterator;
  5587. }
  5588. }
  5589. getReverseIterator(indexDefinition) {
  5590. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5591. }
  5592. getReverseIteratorFrom(endPost, indexDefinition) {
  5593. const idx = this.resolveIndex_(indexDefinition);
  5594. if (idx) {
  5595. return idx.getReverseIteratorFrom(endPost, key => {
  5596. return key;
  5597. });
  5598. }
  5599. else {
  5600. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5601. let next = iterator.peek();
  5602. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5603. iterator.getNext();
  5604. next = iterator.peek();
  5605. }
  5606. return iterator;
  5607. }
  5608. }
  5609. compareTo(other) {
  5610. if (this.isEmpty()) {
  5611. if (other.isEmpty()) {
  5612. return 0;
  5613. }
  5614. else {
  5615. return -1;
  5616. }
  5617. }
  5618. else if (other.isLeafNode() || other.isEmpty()) {
  5619. return 1;
  5620. }
  5621. else if (other === MAX_NODE) {
  5622. return -1;
  5623. }
  5624. else {
  5625. // Must be another node with children.
  5626. return 0;
  5627. }
  5628. }
  5629. withIndex(indexDefinition) {
  5630. if (indexDefinition === KEY_INDEX ||
  5631. this.indexMap_.hasIndex(indexDefinition)) {
  5632. return this;
  5633. }
  5634. else {
  5635. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5636. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5637. }
  5638. }
  5639. isIndexed(index) {
  5640. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5641. }
  5642. equals(other) {
  5643. if (other === this) {
  5644. return true;
  5645. }
  5646. else if (other.isLeafNode()) {
  5647. return false;
  5648. }
  5649. else {
  5650. const otherChildrenNode = other;
  5651. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5652. return false;
  5653. }
  5654. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5655. const thisIter = this.getIterator(PRIORITY_INDEX);
  5656. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5657. let thisCurrent = thisIter.getNext();
  5658. let otherCurrent = otherIter.getNext();
  5659. while (thisCurrent && otherCurrent) {
  5660. if (thisCurrent.name !== otherCurrent.name ||
  5661. !thisCurrent.node.equals(otherCurrent.node)) {
  5662. return false;
  5663. }
  5664. thisCurrent = thisIter.getNext();
  5665. otherCurrent = otherIter.getNext();
  5666. }
  5667. return thisCurrent === null && otherCurrent === null;
  5668. }
  5669. else {
  5670. return false;
  5671. }
  5672. }
  5673. }
  5674. /**
  5675. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5676. * instead.
  5677. *
  5678. */
  5679. resolveIndex_(indexDefinition) {
  5680. if (indexDefinition === KEY_INDEX) {
  5681. return null;
  5682. }
  5683. else {
  5684. return this.indexMap_.get(indexDefinition.toString());
  5685. }
  5686. }
  5687. }
  5688. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5689. class MaxNode extends ChildrenNode {
  5690. constructor() {
  5691. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5692. }
  5693. compareTo(other) {
  5694. if (other === this) {
  5695. return 0;
  5696. }
  5697. else {
  5698. return 1;
  5699. }
  5700. }
  5701. equals(other) {
  5702. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5703. return other === this;
  5704. }
  5705. getPriority() {
  5706. return this;
  5707. }
  5708. getImmediateChild(childName) {
  5709. return ChildrenNode.EMPTY_NODE;
  5710. }
  5711. isEmpty() {
  5712. return false;
  5713. }
  5714. }
  5715. /**
  5716. * Marker that will sort higher than any other snapshot.
  5717. */
  5718. const MAX_NODE = new MaxNode();
  5719. Object.defineProperties(NamedNode, {
  5720. MIN: {
  5721. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5722. },
  5723. MAX: {
  5724. value: new NamedNode(MAX_NAME, MAX_NODE)
  5725. }
  5726. });
  5727. /**
  5728. * Reference Extensions
  5729. */
  5730. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5731. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5732. setMaxNode$1(MAX_NODE);
  5733. setMaxNode(MAX_NODE);
  5734. /**
  5735. * @license
  5736. * Copyright 2017 Google LLC
  5737. *
  5738. * Licensed under the Apache License, Version 2.0 (the "License");
  5739. * you may not use this file except in compliance with the License.
  5740. * You may obtain a copy of the License at
  5741. *
  5742. * http://www.apache.org/licenses/LICENSE-2.0
  5743. *
  5744. * Unless required by applicable law or agreed to in writing, software
  5745. * distributed under the License is distributed on an "AS IS" BASIS,
  5746. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5747. * See the License for the specific language governing permissions and
  5748. * limitations under the License.
  5749. */
  5750. const USE_HINZE = true;
  5751. /**
  5752. * Constructs a snapshot node representing the passed JSON and returns it.
  5753. * @param json - JSON to create a node for.
  5754. * @param priority - Optional priority to use. This will be ignored if the
  5755. * passed JSON contains a .priority property.
  5756. */
  5757. function nodeFromJSON(json, priority = null) {
  5758. if (json === null) {
  5759. return ChildrenNode.EMPTY_NODE;
  5760. }
  5761. if (typeof json === 'object' && '.priority' in json) {
  5762. priority = json['.priority'];
  5763. }
  5764. util.assert(priority === null ||
  5765. typeof priority === 'string' ||
  5766. typeof priority === 'number' ||
  5767. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5768. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5769. json = json['.value'];
  5770. }
  5771. // Valid leaf nodes include non-objects or server-value wrapper objects
  5772. if (typeof json !== 'object' || '.sv' in json) {
  5773. const jsonLeaf = json;
  5774. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5775. }
  5776. if (!(json instanceof Array) && USE_HINZE) {
  5777. const children = [];
  5778. let childrenHavePriority = false;
  5779. const hinzeJsonObj = json;
  5780. each(hinzeJsonObj, (key, child) => {
  5781. if (key.substring(0, 1) !== '.') {
  5782. // Ignore metadata nodes
  5783. const childNode = nodeFromJSON(child);
  5784. if (!childNode.isEmpty()) {
  5785. childrenHavePriority =
  5786. childrenHavePriority || !childNode.getPriority().isEmpty();
  5787. children.push(new NamedNode(key, childNode));
  5788. }
  5789. }
  5790. });
  5791. if (children.length === 0) {
  5792. return ChildrenNode.EMPTY_NODE;
  5793. }
  5794. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5795. if (childrenHavePriority) {
  5796. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5797. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5798. }
  5799. else {
  5800. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5801. }
  5802. }
  5803. else {
  5804. let node = ChildrenNode.EMPTY_NODE;
  5805. each(json, (key, childData) => {
  5806. if (util.contains(json, key)) {
  5807. if (key.substring(0, 1) !== '.') {
  5808. // ignore metadata nodes.
  5809. const childNode = nodeFromJSON(childData);
  5810. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5811. node = node.updateImmediateChild(key, childNode);
  5812. }
  5813. }
  5814. }
  5815. });
  5816. return node.updatePriority(nodeFromJSON(priority));
  5817. }
  5818. }
  5819. setNodeFromJSON(nodeFromJSON);
  5820. /**
  5821. * @license
  5822. * Copyright 2017 Google LLC
  5823. *
  5824. * Licensed under the Apache License, Version 2.0 (the "License");
  5825. * you may not use this file except in compliance with the License.
  5826. * You may obtain a copy of the License at
  5827. *
  5828. * http://www.apache.org/licenses/LICENSE-2.0
  5829. *
  5830. * Unless required by applicable law or agreed to in writing, software
  5831. * distributed under the License is distributed on an "AS IS" BASIS,
  5832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5833. * See the License for the specific language governing permissions and
  5834. * limitations under the License.
  5835. */
  5836. class PathIndex extends Index {
  5837. constructor(indexPath_) {
  5838. super();
  5839. this.indexPath_ = indexPath_;
  5840. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5841. }
  5842. extractChild(snap) {
  5843. return snap.getChild(this.indexPath_);
  5844. }
  5845. isDefinedOn(node) {
  5846. return !node.getChild(this.indexPath_).isEmpty();
  5847. }
  5848. compare(a, b) {
  5849. const aChild = this.extractChild(a.node);
  5850. const bChild = this.extractChild(b.node);
  5851. const indexCmp = aChild.compareTo(bChild);
  5852. if (indexCmp === 0) {
  5853. return nameCompare(a.name, b.name);
  5854. }
  5855. else {
  5856. return indexCmp;
  5857. }
  5858. }
  5859. makePost(indexValue, name) {
  5860. const valueNode = nodeFromJSON(indexValue);
  5861. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5862. return new NamedNode(name, node);
  5863. }
  5864. maxPost() {
  5865. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5866. return new NamedNode(MAX_NAME, node);
  5867. }
  5868. toString() {
  5869. return pathSlice(this.indexPath_, 0).join('/');
  5870. }
  5871. }
  5872. /**
  5873. * @license
  5874. * Copyright 2017 Google LLC
  5875. *
  5876. * Licensed under the Apache License, Version 2.0 (the "License");
  5877. * you may not use this file except in compliance with the License.
  5878. * You may obtain a copy of the License at
  5879. *
  5880. * http://www.apache.org/licenses/LICENSE-2.0
  5881. *
  5882. * Unless required by applicable law or agreed to in writing, software
  5883. * distributed under the License is distributed on an "AS IS" BASIS,
  5884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5885. * See the License for the specific language governing permissions and
  5886. * limitations under the License.
  5887. */
  5888. class ValueIndex extends Index {
  5889. compare(a, b) {
  5890. const indexCmp = a.node.compareTo(b.node);
  5891. if (indexCmp === 0) {
  5892. return nameCompare(a.name, b.name);
  5893. }
  5894. else {
  5895. return indexCmp;
  5896. }
  5897. }
  5898. isDefinedOn(node) {
  5899. return true;
  5900. }
  5901. indexedValueChanged(oldNode, newNode) {
  5902. return !oldNode.equals(newNode);
  5903. }
  5904. minPost() {
  5905. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5906. return NamedNode.MIN;
  5907. }
  5908. maxPost() {
  5909. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5910. return NamedNode.MAX;
  5911. }
  5912. makePost(indexValue, name) {
  5913. const valueNode = nodeFromJSON(indexValue);
  5914. return new NamedNode(name, valueNode);
  5915. }
  5916. /**
  5917. * @returns String representation for inclusion in a query spec
  5918. */
  5919. toString() {
  5920. return '.value';
  5921. }
  5922. }
  5923. const VALUE_INDEX = new ValueIndex();
  5924. /**
  5925. * @license
  5926. * Copyright 2017 Google LLC
  5927. *
  5928. * Licensed under the Apache License, Version 2.0 (the "License");
  5929. * you may not use this file except in compliance with the License.
  5930. * You may obtain a copy of the License at
  5931. *
  5932. * http://www.apache.org/licenses/LICENSE-2.0
  5933. *
  5934. * Unless required by applicable law or agreed to in writing, software
  5935. * distributed under the License is distributed on an "AS IS" BASIS,
  5936. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5937. * See the License for the specific language governing permissions and
  5938. * limitations under the License.
  5939. */
  5940. function changeValue(snapshotNode) {
  5941. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5942. }
  5943. function changeChildAdded(childName, snapshotNode) {
  5944. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5945. }
  5946. function changeChildRemoved(childName, snapshotNode) {
  5947. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5948. }
  5949. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5950. return {
  5951. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5952. snapshotNode,
  5953. childName,
  5954. oldSnap
  5955. };
  5956. }
  5957. function changeChildMoved(childName, snapshotNode) {
  5958. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5959. }
  5960. /**
  5961. * @license
  5962. * Copyright 2017 Google LLC
  5963. *
  5964. * Licensed under the Apache License, Version 2.0 (the "License");
  5965. * you may not use this file except in compliance with the License.
  5966. * You may obtain a copy of the License at
  5967. *
  5968. * http://www.apache.org/licenses/LICENSE-2.0
  5969. *
  5970. * Unless required by applicable law or agreed to in writing, software
  5971. * distributed under the License is distributed on an "AS IS" BASIS,
  5972. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5973. * See the License for the specific language governing permissions and
  5974. * limitations under the License.
  5975. */
  5976. /**
  5977. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5978. */
  5979. class IndexedFilter {
  5980. constructor(index_) {
  5981. this.index_ = index_;
  5982. }
  5983. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5984. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5985. const oldChild = snap.getImmediateChild(key);
  5986. // Check if anything actually changed.
  5987. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5988. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5989. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5990. // to avoid treating these cases as "nothing changed."
  5991. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5992. // Nothing changed.
  5993. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5994. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5995. return snap;
  5996. }
  5997. }
  5998. if (optChangeAccumulator != null) {
  5999. if (newChild.isEmpty()) {
  6000. if (snap.hasChild(key)) {
  6001. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6002. }
  6003. else {
  6004. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6005. }
  6006. }
  6007. else if (oldChild.isEmpty()) {
  6008. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6009. }
  6010. else {
  6011. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6012. }
  6013. }
  6014. if (snap.isLeafNode() && newChild.isEmpty()) {
  6015. return snap;
  6016. }
  6017. else {
  6018. // Make sure the node is indexed
  6019. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6020. }
  6021. }
  6022. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6023. if (optChangeAccumulator != null) {
  6024. if (!oldSnap.isLeafNode()) {
  6025. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6026. if (!newSnap.hasChild(key)) {
  6027. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6028. }
  6029. });
  6030. }
  6031. if (!newSnap.isLeafNode()) {
  6032. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6033. if (oldSnap.hasChild(key)) {
  6034. const oldChild = oldSnap.getImmediateChild(key);
  6035. if (!oldChild.equals(childNode)) {
  6036. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6037. }
  6038. }
  6039. else {
  6040. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6041. }
  6042. });
  6043. }
  6044. }
  6045. return newSnap.withIndex(this.index_);
  6046. }
  6047. updatePriority(oldSnap, newPriority) {
  6048. if (oldSnap.isEmpty()) {
  6049. return ChildrenNode.EMPTY_NODE;
  6050. }
  6051. else {
  6052. return oldSnap.updatePriority(newPriority);
  6053. }
  6054. }
  6055. filtersNodes() {
  6056. return false;
  6057. }
  6058. getIndexedFilter() {
  6059. return this;
  6060. }
  6061. getIndex() {
  6062. return this.index_;
  6063. }
  6064. }
  6065. /**
  6066. * @license
  6067. * Copyright 2017 Google LLC
  6068. *
  6069. * Licensed under the Apache License, Version 2.0 (the "License");
  6070. * you may not use this file except in compliance with the License.
  6071. * You may obtain a copy of the License at
  6072. *
  6073. * http://www.apache.org/licenses/LICENSE-2.0
  6074. *
  6075. * Unless required by applicable law or agreed to in writing, software
  6076. * distributed under the License is distributed on an "AS IS" BASIS,
  6077. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6078. * See the License for the specific language governing permissions and
  6079. * limitations under the License.
  6080. */
  6081. /**
  6082. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6083. */
  6084. class RangedFilter {
  6085. constructor(params) {
  6086. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6087. this.index_ = params.getIndex();
  6088. this.startPost_ = RangedFilter.getStartPost_(params);
  6089. this.endPost_ = RangedFilter.getEndPost_(params);
  6090. this.startIsInclusive_ = !params.startAfterSet_;
  6091. this.endIsInclusive_ = !params.endBeforeSet_;
  6092. }
  6093. getStartPost() {
  6094. return this.startPost_;
  6095. }
  6096. getEndPost() {
  6097. return this.endPost_;
  6098. }
  6099. matches(node) {
  6100. const isWithinStart = this.startIsInclusive_
  6101. ? this.index_.compare(this.getStartPost(), node) <= 0
  6102. : this.index_.compare(this.getStartPost(), node) < 0;
  6103. const isWithinEnd = this.endIsInclusive_
  6104. ? this.index_.compare(node, this.getEndPost()) <= 0
  6105. : this.index_.compare(node, this.getEndPost()) < 0;
  6106. return isWithinStart && isWithinEnd;
  6107. }
  6108. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6109. if (!this.matches(new NamedNode(key, newChild))) {
  6110. newChild = ChildrenNode.EMPTY_NODE;
  6111. }
  6112. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6113. }
  6114. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6115. if (newSnap.isLeafNode()) {
  6116. // Make sure we have a children node with the correct index, not a leaf node;
  6117. newSnap = ChildrenNode.EMPTY_NODE;
  6118. }
  6119. let filtered = newSnap.withIndex(this.index_);
  6120. // Don't support priorities on queries
  6121. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6122. const self = this;
  6123. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6124. if (!self.matches(new NamedNode(key, childNode))) {
  6125. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6126. }
  6127. });
  6128. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6129. }
  6130. updatePriority(oldSnap, newPriority) {
  6131. // Don't support priorities on queries
  6132. return oldSnap;
  6133. }
  6134. filtersNodes() {
  6135. return true;
  6136. }
  6137. getIndexedFilter() {
  6138. return this.indexedFilter_;
  6139. }
  6140. getIndex() {
  6141. return this.index_;
  6142. }
  6143. static getStartPost_(params) {
  6144. if (params.hasStart()) {
  6145. const startName = params.getIndexStartName();
  6146. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6147. }
  6148. else {
  6149. return params.getIndex().minPost();
  6150. }
  6151. }
  6152. static getEndPost_(params) {
  6153. if (params.hasEnd()) {
  6154. const endName = params.getIndexEndName();
  6155. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6156. }
  6157. else {
  6158. return params.getIndex().maxPost();
  6159. }
  6160. }
  6161. }
  6162. /**
  6163. * @license
  6164. * Copyright 2017 Google LLC
  6165. *
  6166. * Licensed under the Apache License, Version 2.0 (the "License");
  6167. * you may not use this file except in compliance with the License.
  6168. * You may obtain a copy of the License at
  6169. *
  6170. * http://www.apache.org/licenses/LICENSE-2.0
  6171. *
  6172. * Unless required by applicable law or agreed to in writing, software
  6173. * distributed under the License is distributed on an "AS IS" BASIS,
  6174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6175. * See the License for the specific language governing permissions and
  6176. * limitations under the License.
  6177. */
  6178. /**
  6179. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6180. */
  6181. class LimitedFilter {
  6182. constructor(params) {
  6183. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6184. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6185. this.withinStartPost = (node) => {
  6186. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6187. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6188. };
  6189. this.withinEndPost = (node) => {
  6190. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6191. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6192. };
  6193. this.rangedFilter_ = new RangedFilter(params);
  6194. this.index_ = params.getIndex();
  6195. this.limit_ = params.getLimit();
  6196. this.reverse_ = !params.isViewFromLeft();
  6197. this.startIsInclusive_ = !params.startAfterSet_;
  6198. this.endIsInclusive_ = !params.endBeforeSet_;
  6199. }
  6200. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6201. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6202. newChild = ChildrenNode.EMPTY_NODE;
  6203. }
  6204. if (snap.getImmediateChild(key).equals(newChild)) {
  6205. // No change
  6206. return snap;
  6207. }
  6208. else if (snap.numChildren() < this.limit_) {
  6209. return this.rangedFilter_
  6210. .getIndexedFilter()
  6211. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6212. }
  6213. else {
  6214. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6215. }
  6216. }
  6217. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6218. let filtered;
  6219. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6220. // Make sure we have a children node with the correct index, not a leaf node;
  6221. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6222. }
  6223. else {
  6224. if (this.limit_ * 2 < newSnap.numChildren() &&
  6225. newSnap.isIndexed(this.index_)) {
  6226. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6227. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6228. // anchor to the startPost, endPost, or last element as appropriate
  6229. let iterator;
  6230. if (this.reverse_) {
  6231. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6232. }
  6233. else {
  6234. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6235. }
  6236. let count = 0;
  6237. while (iterator.hasNext() && count < this.limit_) {
  6238. const next = iterator.getNext();
  6239. if (!this.withinDirectionalStart(next)) {
  6240. // if we have not reached the start, skip to the next element
  6241. continue;
  6242. }
  6243. else if (!this.withinDirectionalEnd(next)) {
  6244. // if we have reached the end, stop adding elements
  6245. break;
  6246. }
  6247. else {
  6248. filtered = filtered.updateImmediateChild(next.name, next.node);
  6249. count++;
  6250. }
  6251. }
  6252. }
  6253. else {
  6254. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6255. filtered = newSnap.withIndex(this.index_);
  6256. // Don't support priorities on queries
  6257. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6258. let iterator;
  6259. if (this.reverse_) {
  6260. iterator = filtered.getReverseIterator(this.index_);
  6261. }
  6262. else {
  6263. iterator = filtered.getIterator(this.index_);
  6264. }
  6265. let count = 0;
  6266. while (iterator.hasNext()) {
  6267. const next = iterator.getNext();
  6268. const inRange = count < this.limit_ &&
  6269. this.withinDirectionalStart(next) &&
  6270. this.withinDirectionalEnd(next);
  6271. if (inRange) {
  6272. count++;
  6273. }
  6274. else {
  6275. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6276. }
  6277. }
  6278. }
  6279. }
  6280. return this.rangedFilter_
  6281. .getIndexedFilter()
  6282. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6283. }
  6284. updatePriority(oldSnap, newPriority) {
  6285. // Don't support priorities on queries
  6286. return oldSnap;
  6287. }
  6288. filtersNodes() {
  6289. return true;
  6290. }
  6291. getIndexedFilter() {
  6292. return this.rangedFilter_.getIndexedFilter();
  6293. }
  6294. getIndex() {
  6295. return this.index_;
  6296. }
  6297. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6298. // TODO: rename all cache stuff etc to general snap terminology
  6299. let cmp;
  6300. if (this.reverse_) {
  6301. const indexCmp = this.index_.getCompare();
  6302. cmp = (a, b) => indexCmp(b, a);
  6303. }
  6304. else {
  6305. cmp = this.index_.getCompare();
  6306. }
  6307. const oldEventCache = snap;
  6308. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6309. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6310. const windowBoundary = this.reverse_
  6311. ? oldEventCache.getFirstChild(this.index_)
  6312. : oldEventCache.getLastChild(this.index_);
  6313. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6314. if (oldEventCache.hasChild(childKey)) {
  6315. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6316. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6317. while (nextChild != null &&
  6318. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6319. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6320. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6321. // the limited filter...
  6322. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6323. }
  6324. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6325. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6326. if (remainsInWindow) {
  6327. if (changeAccumulator != null) {
  6328. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6329. }
  6330. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6331. }
  6332. else {
  6333. if (changeAccumulator != null) {
  6334. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6335. }
  6336. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6337. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6338. if (nextChildInRange) {
  6339. if (changeAccumulator != null) {
  6340. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6341. }
  6342. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6343. }
  6344. else {
  6345. return newEventCache;
  6346. }
  6347. }
  6348. }
  6349. else if (childSnap.isEmpty()) {
  6350. // we're deleting a node, but it was not in the window, so ignore it
  6351. return snap;
  6352. }
  6353. else if (inRange) {
  6354. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6355. if (changeAccumulator != null) {
  6356. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6357. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6358. }
  6359. return oldEventCache
  6360. .updateImmediateChild(childKey, childSnap)
  6361. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6362. }
  6363. else {
  6364. return snap;
  6365. }
  6366. }
  6367. else {
  6368. return snap;
  6369. }
  6370. }
  6371. }
  6372. /**
  6373. * @license
  6374. * Copyright 2017 Google LLC
  6375. *
  6376. * Licensed under the Apache License, Version 2.0 (the "License");
  6377. * you may not use this file except in compliance with the License.
  6378. * You may obtain a copy of the License at
  6379. *
  6380. * http://www.apache.org/licenses/LICENSE-2.0
  6381. *
  6382. * Unless required by applicable law or agreed to in writing, software
  6383. * distributed under the License is distributed on an "AS IS" BASIS,
  6384. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6385. * See the License for the specific language governing permissions and
  6386. * limitations under the License.
  6387. */
  6388. /**
  6389. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6390. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6391. * user-facing API level, so it is not done here.
  6392. *
  6393. * @internal
  6394. */
  6395. class QueryParams {
  6396. constructor() {
  6397. this.limitSet_ = false;
  6398. this.startSet_ = false;
  6399. this.startNameSet_ = false;
  6400. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6401. this.endSet_ = false;
  6402. this.endNameSet_ = false;
  6403. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6404. this.limit_ = 0;
  6405. this.viewFrom_ = '';
  6406. this.indexStartValue_ = null;
  6407. this.indexStartName_ = '';
  6408. this.indexEndValue_ = null;
  6409. this.indexEndName_ = '';
  6410. this.index_ = PRIORITY_INDEX;
  6411. }
  6412. hasStart() {
  6413. return this.startSet_;
  6414. }
  6415. /**
  6416. * @returns True if it would return from left.
  6417. */
  6418. isViewFromLeft() {
  6419. if (this.viewFrom_ === '') {
  6420. // limit(), rather than limitToFirst or limitToLast was called.
  6421. // This means that only one of startSet_ and endSet_ is true. Use them
  6422. // to calculate which side of the view to anchor to. If neither is set,
  6423. // anchor to the end.
  6424. return this.startSet_;
  6425. }
  6426. else {
  6427. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6428. }
  6429. }
  6430. /**
  6431. * Only valid to call if hasStart() returns true
  6432. */
  6433. getIndexStartValue() {
  6434. util.assert(this.startSet_, 'Only valid if start has been set');
  6435. return this.indexStartValue_;
  6436. }
  6437. /**
  6438. * Only valid to call if hasStart() returns true.
  6439. * Returns the starting key name for the range defined by these query parameters
  6440. */
  6441. getIndexStartName() {
  6442. util.assert(this.startSet_, 'Only valid if start has been set');
  6443. if (this.startNameSet_) {
  6444. return this.indexStartName_;
  6445. }
  6446. else {
  6447. return MIN_NAME;
  6448. }
  6449. }
  6450. hasEnd() {
  6451. return this.endSet_;
  6452. }
  6453. /**
  6454. * Only valid to call if hasEnd() returns true.
  6455. */
  6456. getIndexEndValue() {
  6457. util.assert(this.endSet_, 'Only valid if end has been set');
  6458. return this.indexEndValue_;
  6459. }
  6460. /**
  6461. * Only valid to call if hasEnd() returns true.
  6462. * Returns the end key name for the range defined by these query parameters
  6463. */
  6464. getIndexEndName() {
  6465. util.assert(this.endSet_, 'Only valid if end has been set');
  6466. if (this.endNameSet_) {
  6467. return this.indexEndName_;
  6468. }
  6469. else {
  6470. return MAX_NAME;
  6471. }
  6472. }
  6473. hasLimit() {
  6474. return this.limitSet_;
  6475. }
  6476. /**
  6477. * @returns True if a limit has been set and it has been explicitly anchored
  6478. */
  6479. hasAnchoredLimit() {
  6480. return this.limitSet_ && this.viewFrom_ !== '';
  6481. }
  6482. /**
  6483. * Only valid to call if hasLimit() returns true
  6484. */
  6485. getLimit() {
  6486. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6487. return this.limit_;
  6488. }
  6489. getIndex() {
  6490. return this.index_;
  6491. }
  6492. loadsAllData() {
  6493. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6494. }
  6495. isDefault() {
  6496. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6497. }
  6498. copy() {
  6499. const copy = new QueryParams();
  6500. copy.limitSet_ = this.limitSet_;
  6501. copy.limit_ = this.limit_;
  6502. copy.startSet_ = this.startSet_;
  6503. copy.startAfterSet_ = this.startAfterSet_;
  6504. copy.indexStartValue_ = this.indexStartValue_;
  6505. copy.startNameSet_ = this.startNameSet_;
  6506. copy.indexStartName_ = this.indexStartName_;
  6507. copy.endSet_ = this.endSet_;
  6508. copy.endBeforeSet_ = this.endBeforeSet_;
  6509. copy.indexEndValue_ = this.indexEndValue_;
  6510. copy.endNameSet_ = this.endNameSet_;
  6511. copy.indexEndName_ = this.indexEndName_;
  6512. copy.index_ = this.index_;
  6513. copy.viewFrom_ = this.viewFrom_;
  6514. return copy;
  6515. }
  6516. }
  6517. function queryParamsGetNodeFilter(queryParams) {
  6518. if (queryParams.loadsAllData()) {
  6519. return new IndexedFilter(queryParams.getIndex());
  6520. }
  6521. else if (queryParams.hasLimit()) {
  6522. return new LimitedFilter(queryParams);
  6523. }
  6524. else {
  6525. return new RangedFilter(queryParams);
  6526. }
  6527. }
  6528. function queryParamsLimitToFirst(queryParams, newLimit) {
  6529. const newParams = queryParams.copy();
  6530. newParams.limitSet_ = true;
  6531. newParams.limit_ = newLimit;
  6532. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6533. return newParams;
  6534. }
  6535. function queryParamsLimitToLast(queryParams, newLimit) {
  6536. const newParams = queryParams.copy();
  6537. newParams.limitSet_ = true;
  6538. newParams.limit_ = newLimit;
  6539. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6540. return newParams;
  6541. }
  6542. function queryParamsStartAt(queryParams, indexValue, key) {
  6543. const newParams = queryParams.copy();
  6544. newParams.startSet_ = true;
  6545. if (indexValue === undefined) {
  6546. indexValue = null;
  6547. }
  6548. newParams.indexStartValue_ = indexValue;
  6549. if (key != null) {
  6550. newParams.startNameSet_ = true;
  6551. newParams.indexStartName_ = key;
  6552. }
  6553. else {
  6554. newParams.startNameSet_ = false;
  6555. newParams.indexStartName_ = '';
  6556. }
  6557. return newParams;
  6558. }
  6559. function queryParamsStartAfter(queryParams, indexValue, key) {
  6560. let params;
  6561. if (queryParams.index_ === KEY_INDEX || !!key) {
  6562. params = queryParamsStartAt(queryParams, indexValue, key);
  6563. }
  6564. else {
  6565. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6566. }
  6567. params.startAfterSet_ = true;
  6568. return params;
  6569. }
  6570. function queryParamsEndAt(queryParams, indexValue, key) {
  6571. const newParams = queryParams.copy();
  6572. newParams.endSet_ = true;
  6573. if (indexValue === undefined) {
  6574. indexValue = null;
  6575. }
  6576. newParams.indexEndValue_ = indexValue;
  6577. if (key !== undefined) {
  6578. newParams.endNameSet_ = true;
  6579. newParams.indexEndName_ = key;
  6580. }
  6581. else {
  6582. newParams.endNameSet_ = false;
  6583. newParams.indexEndName_ = '';
  6584. }
  6585. return newParams;
  6586. }
  6587. function queryParamsEndBefore(queryParams, indexValue, key) {
  6588. let params;
  6589. if (queryParams.index_ === KEY_INDEX || !!key) {
  6590. params = queryParamsEndAt(queryParams, indexValue, key);
  6591. }
  6592. else {
  6593. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6594. }
  6595. params.endBeforeSet_ = true;
  6596. return params;
  6597. }
  6598. function queryParamsOrderBy(queryParams, index) {
  6599. const newParams = queryParams.copy();
  6600. newParams.index_ = index;
  6601. return newParams;
  6602. }
  6603. /**
  6604. * Returns a set of REST query string parameters representing this query.
  6605. *
  6606. * @returns query string parameters
  6607. */
  6608. function queryParamsToRestQueryStringParameters(queryParams) {
  6609. const qs = {};
  6610. if (queryParams.isDefault()) {
  6611. return qs;
  6612. }
  6613. let orderBy;
  6614. if (queryParams.index_ === PRIORITY_INDEX) {
  6615. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6616. }
  6617. else if (queryParams.index_ === VALUE_INDEX) {
  6618. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6619. }
  6620. else if (queryParams.index_ === KEY_INDEX) {
  6621. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6622. }
  6623. else {
  6624. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6625. orderBy = queryParams.index_.toString();
  6626. }
  6627. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6628. if (queryParams.startSet_) {
  6629. const startParam = queryParams.startAfterSet_
  6630. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6631. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6632. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6633. if (queryParams.startNameSet_) {
  6634. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6635. }
  6636. }
  6637. if (queryParams.endSet_) {
  6638. const endParam = queryParams.endBeforeSet_
  6639. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6640. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6641. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6642. if (queryParams.endNameSet_) {
  6643. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6644. }
  6645. }
  6646. if (queryParams.limitSet_) {
  6647. if (queryParams.isViewFromLeft()) {
  6648. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6649. }
  6650. else {
  6651. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6652. }
  6653. }
  6654. return qs;
  6655. }
  6656. function queryParamsGetQueryObject(queryParams) {
  6657. const obj = {};
  6658. if (queryParams.startSet_) {
  6659. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6660. queryParams.indexStartValue_;
  6661. if (queryParams.startNameSet_) {
  6662. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6663. queryParams.indexStartName_;
  6664. }
  6665. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6666. !queryParams.startAfterSet_;
  6667. }
  6668. if (queryParams.endSet_) {
  6669. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6670. if (queryParams.endNameSet_) {
  6671. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6672. }
  6673. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6674. !queryParams.endBeforeSet_;
  6675. }
  6676. if (queryParams.limitSet_) {
  6677. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6678. let viewFrom = queryParams.viewFrom_;
  6679. if (viewFrom === '') {
  6680. if (queryParams.isViewFromLeft()) {
  6681. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6682. }
  6683. else {
  6684. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6685. }
  6686. }
  6687. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6688. }
  6689. // For now, priority index is the default, so we only specify if it's some other index
  6690. if (queryParams.index_ !== PRIORITY_INDEX) {
  6691. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6692. }
  6693. return obj;
  6694. }
  6695. /**
  6696. * @license
  6697. * Copyright 2017 Google LLC
  6698. *
  6699. * Licensed under the Apache License, Version 2.0 (the "License");
  6700. * you may not use this file except in compliance with the License.
  6701. * You may obtain a copy of the License at
  6702. *
  6703. * http://www.apache.org/licenses/LICENSE-2.0
  6704. *
  6705. * Unless required by applicable law or agreed to in writing, software
  6706. * distributed under the License is distributed on an "AS IS" BASIS,
  6707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6708. * See the License for the specific language governing permissions and
  6709. * limitations under the License.
  6710. */
  6711. /**
  6712. * An implementation of ServerActions that communicates with the server via REST requests.
  6713. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6714. * persistent connection (using WebSockets or long-polling)
  6715. */
  6716. class ReadonlyRestClient extends ServerActions {
  6717. /**
  6718. * @param repoInfo_ - Data about the namespace we are connecting to
  6719. * @param onDataUpdate_ - A callback for new data from the server
  6720. */
  6721. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6722. super();
  6723. this.repoInfo_ = repoInfo_;
  6724. this.onDataUpdate_ = onDataUpdate_;
  6725. this.authTokenProvider_ = authTokenProvider_;
  6726. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6727. /** @private {function(...[*])} */
  6728. this.log_ = logWrapper('p:rest:');
  6729. /**
  6730. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6731. * that's been removed. :-/
  6732. */
  6733. this.listens_ = {};
  6734. }
  6735. reportStats(stats) {
  6736. throw new Error('Method not implemented.');
  6737. }
  6738. static getListenId_(query, tag) {
  6739. if (tag !== undefined) {
  6740. return 'tag$' + tag;
  6741. }
  6742. else {
  6743. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6744. return query._path.toString();
  6745. }
  6746. }
  6747. /** @inheritDoc */
  6748. listen(query, currentHashFn, tag, onComplete) {
  6749. const pathString = query._path.toString();
  6750. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6751. // Mark this listener so we can tell if it's removed.
  6752. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6753. const thisListen = {};
  6754. this.listens_[listenId] = thisListen;
  6755. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6756. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6757. let data = result;
  6758. if (error === 404) {
  6759. data = null;
  6760. error = null;
  6761. }
  6762. if (error === null) {
  6763. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6764. }
  6765. if (util.safeGet(this.listens_, listenId) === thisListen) {
  6766. let status;
  6767. if (!error) {
  6768. status = 'ok';
  6769. }
  6770. else if (error === 401) {
  6771. status = 'permission_denied';
  6772. }
  6773. else {
  6774. status = 'rest_error:' + error;
  6775. }
  6776. onComplete(status, null);
  6777. }
  6778. });
  6779. }
  6780. /** @inheritDoc */
  6781. unlisten(query, tag) {
  6782. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6783. delete this.listens_[listenId];
  6784. }
  6785. get(query) {
  6786. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6787. const pathString = query._path.toString();
  6788. const deferred = new util.Deferred();
  6789. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6790. let data = result;
  6791. if (error === 404) {
  6792. data = null;
  6793. error = null;
  6794. }
  6795. if (error === null) {
  6796. this.onDataUpdate_(pathString, data,
  6797. /*isMerge=*/ false,
  6798. /*tag=*/ null);
  6799. deferred.resolve(data);
  6800. }
  6801. else {
  6802. deferred.reject(new Error(data));
  6803. }
  6804. });
  6805. return deferred.promise;
  6806. }
  6807. /** @inheritDoc */
  6808. refreshAuthToken(token) {
  6809. // no-op since we just always call getToken.
  6810. }
  6811. /**
  6812. * Performs a REST request to the given path, with the provided query string parameters,
  6813. * and any auth credentials we have.
  6814. */
  6815. restRequest_(pathString, queryStringParameters = {}, callback) {
  6816. queryStringParameters['format'] = 'export';
  6817. return Promise.all([
  6818. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6819. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6820. ]).then(([authToken, appCheckToken]) => {
  6821. if (authToken && authToken.accessToken) {
  6822. queryStringParameters['auth'] = authToken.accessToken;
  6823. }
  6824. if (appCheckToken && appCheckToken.token) {
  6825. queryStringParameters['ac'] = appCheckToken.token;
  6826. }
  6827. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6828. this.repoInfo_.host +
  6829. pathString +
  6830. '?' +
  6831. 'ns=' +
  6832. this.repoInfo_.namespace +
  6833. util.querystring(queryStringParameters);
  6834. this.log_('Sending REST request for ' + url);
  6835. const xhr = new XMLHttpRequest();
  6836. xhr.onreadystatechange = () => {
  6837. if (callback && xhr.readyState === 4) {
  6838. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6839. let res = null;
  6840. if (xhr.status >= 200 && xhr.status < 300) {
  6841. try {
  6842. res = util.jsonEval(xhr.responseText);
  6843. }
  6844. catch (e) {
  6845. warn('Failed to parse JSON response for ' +
  6846. url +
  6847. ': ' +
  6848. xhr.responseText);
  6849. }
  6850. callback(null, res);
  6851. }
  6852. else {
  6853. // 401 and 404 are expected.
  6854. if (xhr.status !== 401 && xhr.status !== 404) {
  6855. warn('Got unsuccessful REST response for ' +
  6856. url +
  6857. ' Status: ' +
  6858. xhr.status);
  6859. }
  6860. callback(xhr.status);
  6861. }
  6862. callback = null;
  6863. }
  6864. };
  6865. xhr.open('GET', url, /*asynchronous=*/ true);
  6866. xhr.send();
  6867. });
  6868. }
  6869. }
  6870. /**
  6871. * @license
  6872. * Copyright 2017 Google LLC
  6873. *
  6874. * Licensed under the Apache License, Version 2.0 (the "License");
  6875. * you may not use this file except in compliance with the License.
  6876. * You may obtain a copy of the License at
  6877. *
  6878. * http://www.apache.org/licenses/LICENSE-2.0
  6879. *
  6880. * Unless required by applicable law or agreed to in writing, software
  6881. * distributed under the License is distributed on an "AS IS" BASIS,
  6882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6883. * See the License for the specific language governing permissions and
  6884. * limitations under the License.
  6885. */
  6886. /**
  6887. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6888. */
  6889. class SnapshotHolder {
  6890. constructor() {
  6891. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6892. }
  6893. getNode(path) {
  6894. return this.rootNode_.getChild(path);
  6895. }
  6896. updateSnapshot(path, newSnapshotNode) {
  6897. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6898. }
  6899. }
  6900. /**
  6901. * @license
  6902. * Copyright 2017 Google LLC
  6903. *
  6904. * Licensed under the Apache License, Version 2.0 (the "License");
  6905. * you may not use this file except in compliance with the License.
  6906. * You may obtain a copy of the License at
  6907. *
  6908. * http://www.apache.org/licenses/LICENSE-2.0
  6909. *
  6910. * Unless required by applicable law or agreed to in writing, software
  6911. * distributed under the License is distributed on an "AS IS" BASIS,
  6912. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6913. * See the License for the specific language governing permissions and
  6914. * limitations under the License.
  6915. */
  6916. function newSparseSnapshotTree() {
  6917. return {
  6918. value: null,
  6919. children: new Map()
  6920. };
  6921. }
  6922. /**
  6923. * Stores the given node at the specified path. If there is already a node
  6924. * at a shallower path, it merges the new data into that snapshot node.
  6925. *
  6926. * @param path - Path to look up snapshot for.
  6927. * @param data - The new data, or null.
  6928. */
  6929. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6930. if (pathIsEmpty(path)) {
  6931. sparseSnapshotTree.value = data;
  6932. sparseSnapshotTree.children.clear();
  6933. }
  6934. else if (sparseSnapshotTree.value !== null) {
  6935. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6936. }
  6937. else {
  6938. const childKey = pathGetFront(path);
  6939. if (!sparseSnapshotTree.children.has(childKey)) {
  6940. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6941. }
  6942. const child = sparseSnapshotTree.children.get(childKey);
  6943. path = pathPopFront(path);
  6944. sparseSnapshotTreeRemember(child, path, data);
  6945. }
  6946. }
  6947. /**
  6948. * Purge the data at path from the cache.
  6949. *
  6950. * @param path - Path to look up snapshot for.
  6951. * @returns True if this node should now be removed.
  6952. */
  6953. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6954. if (pathIsEmpty(path)) {
  6955. sparseSnapshotTree.value = null;
  6956. sparseSnapshotTree.children.clear();
  6957. return true;
  6958. }
  6959. else {
  6960. if (sparseSnapshotTree.value !== null) {
  6961. if (sparseSnapshotTree.value.isLeafNode()) {
  6962. // We're trying to forget a node that doesn't exist
  6963. return false;
  6964. }
  6965. else {
  6966. const value = sparseSnapshotTree.value;
  6967. sparseSnapshotTree.value = null;
  6968. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6969. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6970. });
  6971. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6972. }
  6973. }
  6974. else if (sparseSnapshotTree.children.size > 0) {
  6975. const childKey = pathGetFront(path);
  6976. path = pathPopFront(path);
  6977. if (sparseSnapshotTree.children.has(childKey)) {
  6978. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6979. if (safeToRemove) {
  6980. sparseSnapshotTree.children.delete(childKey);
  6981. }
  6982. }
  6983. return sparseSnapshotTree.children.size === 0;
  6984. }
  6985. else {
  6986. return true;
  6987. }
  6988. }
  6989. }
  6990. /**
  6991. * Recursively iterates through all of the stored tree and calls the
  6992. * callback on each one.
  6993. *
  6994. * @param prefixPath - Path to look up node for.
  6995. * @param func - The function to invoke for each tree.
  6996. */
  6997. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  6998. if (sparseSnapshotTree.value !== null) {
  6999. func(prefixPath, sparseSnapshotTree.value);
  7000. }
  7001. else {
  7002. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7003. const path = new Path(prefixPath.toString() + '/' + key);
  7004. sparseSnapshotTreeForEachTree(tree, path, func);
  7005. });
  7006. }
  7007. }
  7008. /**
  7009. * Iterates through each immediate child and triggers the callback.
  7010. * Only seems to be used in tests.
  7011. *
  7012. * @param func - The function to invoke for each child.
  7013. */
  7014. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7015. sparseSnapshotTree.children.forEach((tree, key) => {
  7016. func(key, tree);
  7017. });
  7018. }
  7019. /**
  7020. * @license
  7021. * Copyright 2017 Google LLC
  7022. *
  7023. * Licensed under the Apache License, Version 2.0 (the "License");
  7024. * you may not use this file except in compliance with the License.
  7025. * You may obtain a copy of the License at
  7026. *
  7027. * http://www.apache.org/licenses/LICENSE-2.0
  7028. *
  7029. * Unless required by applicable law or agreed to in writing, software
  7030. * distributed under the License is distributed on an "AS IS" BASIS,
  7031. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7032. * See the License for the specific language governing permissions and
  7033. * limitations under the License.
  7034. */
  7035. /**
  7036. * Returns the delta from the previous call to get stats.
  7037. *
  7038. * @param collection_ - The collection to "listen" to.
  7039. */
  7040. class StatsListener {
  7041. constructor(collection_) {
  7042. this.collection_ = collection_;
  7043. this.last_ = null;
  7044. }
  7045. get() {
  7046. const newStats = this.collection_.get();
  7047. const delta = Object.assign({}, newStats);
  7048. if (this.last_) {
  7049. each(this.last_, (stat, value) => {
  7050. delta[stat] = delta[stat] - value;
  7051. });
  7052. }
  7053. this.last_ = newStats;
  7054. return delta;
  7055. }
  7056. }
  7057. /**
  7058. * @license
  7059. * Copyright 2017 Google LLC
  7060. *
  7061. * Licensed under the Apache License, Version 2.0 (the "License");
  7062. * you may not use this file except in compliance with the License.
  7063. * You may obtain a copy of the License at
  7064. *
  7065. * http://www.apache.org/licenses/LICENSE-2.0
  7066. *
  7067. * Unless required by applicable law or agreed to in writing, software
  7068. * distributed under the License is distributed on an "AS IS" BASIS,
  7069. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7070. * See the License for the specific language governing permissions and
  7071. * limitations under the License.
  7072. */
  7073. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7074. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7075. // seconds to try to ensure the Firebase connection is established / settled.
  7076. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7077. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7078. // We'll continue to report stats on average every 5 minutes.
  7079. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7080. class StatsReporter {
  7081. constructor(collection, server_) {
  7082. this.server_ = server_;
  7083. this.statsToReport_ = {};
  7084. this.statsListener_ = new StatsListener(collection);
  7085. const timeout = FIRST_STATS_MIN_TIME +
  7086. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7087. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7088. }
  7089. reportStats_() {
  7090. const stats = this.statsListener_.get();
  7091. const reportedStats = {};
  7092. let haveStatsToReport = false;
  7093. each(stats, (stat, value) => {
  7094. if (value > 0 && util.contains(this.statsToReport_, stat)) {
  7095. reportedStats[stat] = value;
  7096. haveStatsToReport = true;
  7097. }
  7098. });
  7099. if (haveStatsToReport) {
  7100. this.server_.reportStats(reportedStats);
  7101. }
  7102. // queue our next run.
  7103. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7104. }
  7105. }
  7106. /**
  7107. * @license
  7108. * Copyright 2017 Google LLC
  7109. *
  7110. * Licensed under the Apache License, Version 2.0 (the "License");
  7111. * you may not use this file except in compliance with the License.
  7112. * You may obtain a copy of the License at
  7113. *
  7114. * http://www.apache.org/licenses/LICENSE-2.0
  7115. *
  7116. * Unless required by applicable law or agreed to in writing, software
  7117. * distributed under the License is distributed on an "AS IS" BASIS,
  7118. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7119. * See the License for the specific language governing permissions and
  7120. * limitations under the License.
  7121. */
  7122. /**
  7123. *
  7124. * @enum
  7125. */
  7126. var OperationType;
  7127. (function (OperationType) {
  7128. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7129. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7130. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7131. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7132. })(OperationType || (OperationType = {}));
  7133. function newOperationSourceUser() {
  7134. return {
  7135. fromUser: true,
  7136. fromServer: false,
  7137. queryId: null,
  7138. tagged: false
  7139. };
  7140. }
  7141. function newOperationSourceServer() {
  7142. return {
  7143. fromUser: false,
  7144. fromServer: true,
  7145. queryId: null,
  7146. tagged: false
  7147. };
  7148. }
  7149. function newOperationSourceServerTaggedQuery(queryId) {
  7150. return {
  7151. fromUser: false,
  7152. fromServer: true,
  7153. queryId,
  7154. tagged: true
  7155. };
  7156. }
  7157. /**
  7158. * @license
  7159. * Copyright 2017 Google LLC
  7160. *
  7161. * Licensed under the Apache License, Version 2.0 (the "License");
  7162. * you may not use this file except in compliance with the License.
  7163. * You may obtain a copy of the License at
  7164. *
  7165. * http://www.apache.org/licenses/LICENSE-2.0
  7166. *
  7167. * Unless required by applicable law or agreed to in writing, software
  7168. * distributed under the License is distributed on an "AS IS" BASIS,
  7169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7170. * See the License for the specific language governing permissions and
  7171. * limitations under the License.
  7172. */
  7173. class AckUserWrite {
  7174. /**
  7175. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7176. */
  7177. constructor(
  7178. /** @inheritDoc */ path,
  7179. /** @inheritDoc */ affectedTree,
  7180. /** @inheritDoc */ revert) {
  7181. this.path = path;
  7182. this.affectedTree = affectedTree;
  7183. this.revert = revert;
  7184. /** @inheritDoc */
  7185. this.type = OperationType.ACK_USER_WRITE;
  7186. /** @inheritDoc */
  7187. this.source = newOperationSourceUser();
  7188. }
  7189. operationForChild(childName) {
  7190. if (!pathIsEmpty(this.path)) {
  7191. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7192. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7193. }
  7194. else if (this.affectedTree.value != null) {
  7195. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7196. // All child locations are affected as well; just return same operation.
  7197. return this;
  7198. }
  7199. else {
  7200. const childTree = this.affectedTree.subtree(new Path(childName));
  7201. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7202. }
  7203. }
  7204. }
  7205. /**
  7206. * @license
  7207. * Copyright 2017 Google LLC
  7208. *
  7209. * Licensed under the Apache License, Version 2.0 (the "License");
  7210. * you may not use this file except in compliance with the License.
  7211. * You may obtain a copy of the License at
  7212. *
  7213. * http://www.apache.org/licenses/LICENSE-2.0
  7214. *
  7215. * Unless required by applicable law or agreed to in writing, software
  7216. * distributed under the License is distributed on an "AS IS" BASIS,
  7217. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7218. * See the License for the specific language governing permissions and
  7219. * limitations under the License.
  7220. */
  7221. class ListenComplete {
  7222. constructor(source, path) {
  7223. this.source = source;
  7224. this.path = path;
  7225. /** @inheritDoc */
  7226. this.type = OperationType.LISTEN_COMPLETE;
  7227. }
  7228. operationForChild(childName) {
  7229. if (pathIsEmpty(this.path)) {
  7230. return new ListenComplete(this.source, newEmptyPath());
  7231. }
  7232. else {
  7233. return new ListenComplete(this.source, pathPopFront(this.path));
  7234. }
  7235. }
  7236. }
  7237. /**
  7238. * @license
  7239. * Copyright 2017 Google LLC
  7240. *
  7241. * Licensed under the Apache License, Version 2.0 (the "License");
  7242. * you may not use this file except in compliance with the License.
  7243. * You may obtain a copy of the License at
  7244. *
  7245. * http://www.apache.org/licenses/LICENSE-2.0
  7246. *
  7247. * Unless required by applicable law or agreed to in writing, software
  7248. * distributed under the License is distributed on an "AS IS" BASIS,
  7249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7250. * See the License for the specific language governing permissions and
  7251. * limitations under the License.
  7252. */
  7253. class Overwrite {
  7254. constructor(source, path, snap) {
  7255. this.source = source;
  7256. this.path = path;
  7257. this.snap = snap;
  7258. /** @inheritDoc */
  7259. this.type = OperationType.OVERWRITE;
  7260. }
  7261. operationForChild(childName) {
  7262. if (pathIsEmpty(this.path)) {
  7263. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7264. }
  7265. else {
  7266. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7267. }
  7268. }
  7269. }
  7270. /**
  7271. * @license
  7272. * Copyright 2017 Google LLC
  7273. *
  7274. * Licensed under the Apache License, Version 2.0 (the "License");
  7275. * you may not use this file except in compliance with the License.
  7276. * You may obtain a copy of the License at
  7277. *
  7278. * http://www.apache.org/licenses/LICENSE-2.0
  7279. *
  7280. * Unless required by applicable law or agreed to in writing, software
  7281. * distributed under the License is distributed on an "AS IS" BASIS,
  7282. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7283. * See the License for the specific language governing permissions and
  7284. * limitations under the License.
  7285. */
  7286. class Merge {
  7287. constructor(
  7288. /** @inheritDoc */ source,
  7289. /** @inheritDoc */ path,
  7290. /** @inheritDoc */ children) {
  7291. this.source = source;
  7292. this.path = path;
  7293. this.children = children;
  7294. /** @inheritDoc */
  7295. this.type = OperationType.MERGE;
  7296. }
  7297. operationForChild(childName) {
  7298. if (pathIsEmpty(this.path)) {
  7299. const childTree = this.children.subtree(new Path(childName));
  7300. if (childTree.isEmpty()) {
  7301. // This child is unaffected
  7302. return null;
  7303. }
  7304. else if (childTree.value) {
  7305. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7306. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7307. }
  7308. else {
  7309. // This is a merge at a deeper level
  7310. return new Merge(this.source, newEmptyPath(), childTree);
  7311. }
  7312. }
  7313. else {
  7314. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7315. return new Merge(this.source, pathPopFront(this.path), this.children);
  7316. }
  7317. }
  7318. toString() {
  7319. return ('Operation(' +
  7320. this.path +
  7321. ': ' +
  7322. this.source.toString() +
  7323. ' merge: ' +
  7324. this.children.toString() +
  7325. ')');
  7326. }
  7327. }
  7328. /**
  7329. * @license
  7330. * Copyright 2017 Google LLC
  7331. *
  7332. * Licensed under the Apache License, Version 2.0 (the "License");
  7333. * you may not use this file except in compliance with the License.
  7334. * You may obtain a copy of the License at
  7335. *
  7336. * http://www.apache.org/licenses/LICENSE-2.0
  7337. *
  7338. * Unless required by applicable law or agreed to in writing, software
  7339. * distributed under the License is distributed on an "AS IS" BASIS,
  7340. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7341. * See the License for the specific language governing permissions and
  7342. * limitations under the License.
  7343. */
  7344. /**
  7345. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7346. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7347. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7348. * whether a node potentially had children removed due to a filter.
  7349. */
  7350. class CacheNode {
  7351. constructor(node_, fullyInitialized_, filtered_) {
  7352. this.node_ = node_;
  7353. this.fullyInitialized_ = fullyInitialized_;
  7354. this.filtered_ = filtered_;
  7355. }
  7356. /**
  7357. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7358. */
  7359. isFullyInitialized() {
  7360. return this.fullyInitialized_;
  7361. }
  7362. /**
  7363. * Returns whether this node is potentially missing children due to a filter applied to the node
  7364. */
  7365. isFiltered() {
  7366. return this.filtered_;
  7367. }
  7368. isCompleteForPath(path) {
  7369. if (pathIsEmpty(path)) {
  7370. return this.isFullyInitialized() && !this.filtered_;
  7371. }
  7372. const childKey = pathGetFront(path);
  7373. return this.isCompleteForChild(childKey);
  7374. }
  7375. isCompleteForChild(key) {
  7376. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7377. }
  7378. getNode() {
  7379. return this.node_;
  7380. }
  7381. }
  7382. /**
  7383. * @license
  7384. * Copyright 2017 Google LLC
  7385. *
  7386. * Licensed under the Apache License, Version 2.0 (the "License");
  7387. * you may not use this file except in compliance with the License.
  7388. * You may obtain a copy of the License at
  7389. *
  7390. * http://www.apache.org/licenses/LICENSE-2.0
  7391. *
  7392. * Unless required by applicable law or agreed to in writing, software
  7393. * distributed under the License is distributed on an "AS IS" BASIS,
  7394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7395. * See the License for the specific language governing permissions and
  7396. * limitations under the License.
  7397. */
  7398. /**
  7399. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7400. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7401. * for details.
  7402. *
  7403. */
  7404. class EventGenerator {
  7405. constructor(query_) {
  7406. this.query_ = query_;
  7407. this.index_ = this.query_._queryParams.getIndex();
  7408. }
  7409. }
  7410. /**
  7411. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7412. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7413. *
  7414. * Notes:
  7415. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7416. * our index.
  7417. * - prevName will be calculated based on the index ordering.
  7418. */
  7419. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7420. const events = [];
  7421. const moves = [];
  7422. changes.forEach(change => {
  7423. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7424. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7425. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7426. }
  7427. });
  7428. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7429. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7430. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7431. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7432. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7433. return events;
  7434. }
  7435. /**
  7436. * Given changes of a single change type, generate the corresponding events.
  7437. */
  7438. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7439. const filteredChanges = changes.filter(change => change.type === eventType);
  7440. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7441. filteredChanges.forEach(change => {
  7442. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7443. registrations.forEach(registration => {
  7444. if (registration.respondsTo(change.type)) {
  7445. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7446. }
  7447. });
  7448. });
  7449. }
  7450. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7451. if (change.type === 'value' || change.type === 'child_removed') {
  7452. return change;
  7453. }
  7454. else {
  7455. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7456. return change;
  7457. }
  7458. }
  7459. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7460. if (a.childName == null || b.childName == null) {
  7461. throw util.assertionError('Should only compare child_ events.');
  7462. }
  7463. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7464. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7465. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7466. }
  7467. /**
  7468. * @license
  7469. * Copyright 2017 Google LLC
  7470. *
  7471. * Licensed under the Apache License, Version 2.0 (the "License");
  7472. * you may not use this file except in compliance with the License.
  7473. * You may obtain a copy of the License at
  7474. *
  7475. * http://www.apache.org/licenses/LICENSE-2.0
  7476. *
  7477. * Unless required by applicable law or agreed to in writing, software
  7478. * distributed under the License is distributed on an "AS IS" BASIS,
  7479. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7480. * See the License for the specific language governing permissions and
  7481. * limitations under the License.
  7482. */
  7483. function newViewCache(eventCache, serverCache) {
  7484. return { eventCache, serverCache };
  7485. }
  7486. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7487. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7488. }
  7489. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7490. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7491. }
  7492. function viewCacheGetCompleteEventSnap(viewCache) {
  7493. return viewCache.eventCache.isFullyInitialized()
  7494. ? viewCache.eventCache.getNode()
  7495. : null;
  7496. }
  7497. function viewCacheGetCompleteServerSnap(viewCache) {
  7498. return viewCache.serverCache.isFullyInitialized()
  7499. ? viewCache.serverCache.getNode()
  7500. : null;
  7501. }
  7502. /**
  7503. * @license
  7504. * Copyright 2017 Google LLC
  7505. *
  7506. * Licensed under the Apache License, Version 2.0 (the "License");
  7507. * you may not use this file except in compliance with the License.
  7508. * You may obtain a copy of the License at
  7509. *
  7510. * http://www.apache.org/licenses/LICENSE-2.0
  7511. *
  7512. * Unless required by applicable law or agreed to in writing, software
  7513. * distributed under the License is distributed on an "AS IS" BASIS,
  7514. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7515. * See the License for the specific language governing permissions and
  7516. * limitations under the License.
  7517. */
  7518. let emptyChildrenSingleton;
  7519. /**
  7520. * Singleton empty children collection.
  7521. *
  7522. */
  7523. const EmptyChildren = () => {
  7524. if (!emptyChildrenSingleton) {
  7525. emptyChildrenSingleton = new SortedMap(stringCompare);
  7526. }
  7527. return emptyChildrenSingleton;
  7528. };
  7529. /**
  7530. * A tree with immutable elements.
  7531. */
  7532. class ImmutableTree {
  7533. constructor(value, children = EmptyChildren()) {
  7534. this.value = value;
  7535. this.children = children;
  7536. }
  7537. static fromObject(obj) {
  7538. let tree = new ImmutableTree(null);
  7539. each(obj, (childPath, childSnap) => {
  7540. tree = tree.set(new Path(childPath), childSnap);
  7541. });
  7542. return tree;
  7543. }
  7544. /**
  7545. * True if the value is empty and there are no children
  7546. */
  7547. isEmpty() {
  7548. return this.value === null && this.children.isEmpty();
  7549. }
  7550. /**
  7551. * Given a path and predicate, return the first node and the path to that node
  7552. * where the predicate returns true.
  7553. *
  7554. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7555. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7556. *
  7557. * @param relativePath - The remainder of the path
  7558. * @param predicate - The predicate to satisfy to return a node
  7559. */
  7560. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7561. if (this.value != null && predicate(this.value)) {
  7562. return { path: newEmptyPath(), value: this.value };
  7563. }
  7564. else {
  7565. if (pathIsEmpty(relativePath)) {
  7566. return null;
  7567. }
  7568. else {
  7569. const front = pathGetFront(relativePath);
  7570. const child = this.children.get(front);
  7571. if (child !== null) {
  7572. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7573. if (childExistingPathAndValue != null) {
  7574. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7575. return { path: fullPath, value: childExistingPathAndValue.value };
  7576. }
  7577. else {
  7578. return null;
  7579. }
  7580. }
  7581. else {
  7582. return null;
  7583. }
  7584. }
  7585. }
  7586. }
  7587. /**
  7588. * Find, if it exists, the shortest subpath of the given path that points a defined
  7589. * value in the tree
  7590. */
  7591. findRootMostValueAndPath(relativePath) {
  7592. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7593. }
  7594. /**
  7595. * @returns The subtree at the given path
  7596. */
  7597. subtree(relativePath) {
  7598. if (pathIsEmpty(relativePath)) {
  7599. return this;
  7600. }
  7601. else {
  7602. const front = pathGetFront(relativePath);
  7603. const childTree = this.children.get(front);
  7604. if (childTree !== null) {
  7605. return childTree.subtree(pathPopFront(relativePath));
  7606. }
  7607. else {
  7608. return new ImmutableTree(null);
  7609. }
  7610. }
  7611. }
  7612. /**
  7613. * Sets a value at the specified path.
  7614. *
  7615. * @param relativePath - Path to set value at.
  7616. * @param toSet - Value to set.
  7617. * @returns Resulting tree.
  7618. */
  7619. set(relativePath, toSet) {
  7620. if (pathIsEmpty(relativePath)) {
  7621. return new ImmutableTree(toSet, this.children);
  7622. }
  7623. else {
  7624. const front = pathGetFront(relativePath);
  7625. const child = this.children.get(front) || new ImmutableTree(null);
  7626. const newChild = child.set(pathPopFront(relativePath), toSet);
  7627. const newChildren = this.children.insert(front, newChild);
  7628. return new ImmutableTree(this.value, newChildren);
  7629. }
  7630. }
  7631. /**
  7632. * Removes the value at the specified path.
  7633. *
  7634. * @param relativePath - Path to value to remove.
  7635. * @returns Resulting tree.
  7636. */
  7637. remove(relativePath) {
  7638. if (pathIsEmpty(relativePath)) {
  7639. if (this.children.isEmpty()) {
  7640. return new ImmutableTree(null);
  7641. }
  7642. else {
  7643. return new ImmutableTree(null, this.children);
  7644. }
  7645. }
  7646. else {
  7647. const front = pathGetFront(relativePath);
  7648. const child = this.children.get(front);
  7649. if (child) {
  7650. const newChild = child.remove(pathPopFront(relativePath));
  7651. let newChildren;
  7652. if (newChild.isEmpty()) {
  7653. newChildren = this.children.remove(front);
  7654. }
  7655. else {
  7656. newChildren = this.children.insert(front, newChild);
  7657. }
  7658. if (this.value === null && newChildren.isEmpty()) {
  7659. return new ImmutableTree(null);
  7660. }
  7661. else {
  7662. return new ImmutableTree(this.value, newChildren);
  7663. }
  7664. }
  7665. else {
  7666. return this;
  7667. }
  7668. }
  7669. }
  7670. /**
  7671. * Gets a value from the tree.
  7672. *
  7673. * @param relativePath - Path to get value for.
  7674. * @returns Value at path, or null.
  7675. */
  7676. get(relativePath) {
  7677. if (pathIsEmpty(relativePath)) {
  7678. return this.value;
  7679. }
  7680. else {
  7681. const front = pathGetFront(relativePath);
  7682. const child = this.children.get(front);
  7683. if (child) {
  7684. return child.get(pathPopFront(relativePath));
  7685. }
  7686. else {
  7687. return null;
  7688. }
  7689. }
  7690. }
  7691. /**
  7692. * Replace the subtree at the specified path with the given new tree.
  7693. *
  7694. * @param relativePath - Path to replace subtree for.
  7695. * @param newTree - New tree.
  7696. * @returns Resulting tree.
  7697. */
  7698. setTree(relativePath, newTree) {
  7699. if (pathIsEmpty(relativePath)) {
  7700. return newTree;
  7701. }
  7702. else {
  7703. const front = pathGetFront(relativePath);
  7704. const child = this.children.get(front) || new ImmutableTree(null);
  7705. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7706. let newChildren;
  7707. if (newChild.isEmpty()) {
  7708. newChildren = this.children.remove(front);
  7709. }
  7710. else {
  7711. newChildren = this.children.insert(front, newChild);
  7712. }
  7713. return new ImmutableTree(this.value, newChildren);
  7714. }
  7715. }
  7716. /**
  7717. * Performs a depth first fold on this tree. Transforms a tree into a single
  7718. * value, given a function that operates on the path to a node, an optional
  7719. * current value, and a map of child names to folded subtrees
  7720. */
  7721. fold(fn) {
  7722. return this.fold_(newEmptyPath(), fn);
  7723. }
  7724. /**
  7725. * Recursive helper for public-facing fold() method
  7726. */
  7727. fold_(pathSoFar, fn) {
  7728. const accum = {};
  7729. this.children.inorderTraversal((childKey, childTree) => {
  7730. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7731. });
  7732. return fn(pathSoFar, this.value, accum);
  7733. }
  7734. /**
  7735. * Find the first matching value on the given path. Return the result of applying f to it.
  7736. */
  7737. findOnPath(path, f) {
  7738. return this.findOnPath_(path, newEmptyPath(), f);
  7739. }
  7740. findOnPath_(pathToFollow, pathSoFar, f) {
  7741. const result = this.value ? f(pathSoFar, this.value) : false;
  7742. if (result) {
  7743. return result;
  7744. }
  7745. else {
  7746. if (pathIsEmpty(pathToFollow)) {
  7747. return null;
  7748. }
  7749. else {
  7750. const front = pathGetFront(pathToFollow);
  7751. const nextChild = this.children.get(front);
  7752. if (nextChild) {
  7753. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7754. }
  7755. else {
  7756. return null;
  7757. }
  7758. }
  7759. }
  7760. }
  7761. foreachOnPath(path, f) {
  7762. return this.foreachOnPath_(path, newEmptyPath(), f);
  7763. }
  7764. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7765. if (pathIsEmpty(pathToFollow)) {
  7766. return this;
  7767. }
  7768. else {
  7769. if (this.value) {
  7770. f(currentRelativePath, this.value);
  7771. }
  7772. const front = pathGetFront(pathToFollow);
  7773. const nextChild = this.children.get(front);
  7774. if (nextChild) {
  7775. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7776. }
  7777. else {
  7778. return new ImmutableTree(null);
  7779. }
  7780. }
  7781. }
  7782. /**
  7783. * Calls the given function for each node in the tree that has a value.
  7784. *
  7785. * @param f - A function to be called with the path from the root of the tree to
  7786. * a node, and the value at that node. Called in depth-first order.
  7787. */
  7788. foreach(f) {
  7789. this.foreach_(newEmptyPath(), f);
  7790. }
  7791. foreach_(currentRelativePath, f) {
  7792. this.children.inorderTraversal((childName, childTree) => {
  7793. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7794. });
  7795. if (this.value) {
  7796. f(currentRelativePath, this.value);
  7797. }
  7798. }
  7799. foreachChild(f) {
  7800. this.children.inorderTraversal((childName, childTree) => {
  7801. if (childTree.value) {
  7802. f(childName, childTree.value);
  7803. }
  7804. });
  7805. }
  7806. }
  7807. /**
  7808. * @license
  7809. * Copyright 2017 Google LLC
  7810. *
  7811. * Licensed under the Apache License, Version 2.0 (the "License");
  7812. * you may not use this file except in compliance with the License.
  7813. * You may obtain a copy of the License at
  7814. *
  7815. * http://www.apache.org/licenses/LICENSE-2.0
  7816. *
  7817. * Unless required by applicable law or agreed to in writing, software
  7818. * distributed under the License is distributed on an "AS IS" BASIS,
  7819. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7820. * See the License for the specific language governing permissions and
  7821. * limitations under the License.
  7822. */
  7823. /**
  7824. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7825. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7826. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7827. * to reflect the write added.
  7828. */
  7829. class CompoundWrite {
  7830. constructor(writeTree_) {
  7831. this.writeTree_ = writeTree_;
  7832. }
  7833. static empty() {
  7834. return new CompoundWrite(new ImmutableTree(null));
  7835. }
  7836. }
  7837. function compoundWriteAddWrite(compoundWrite, path, node) {
  7838. if (pathIsEmpty(path)) {
  7839. return new CompoundWrite(new ImmutableTree(node));
  7840. }
  7841. else {
  7842. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7843. if (rootmost != null) {
  7844. const rootMostPath = rootmost.path;
  7845. let value = rootmost.value;
  7846. const relativePath = newRelativePath(rootMostPath, path);
  7847. value = value.updateChild(relativePath, node);
  7848. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7849. }
  7850. else {
  7851. const subtree = new ImmutableTree(node);
  7852. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7853. return new CompoundWrite(newWriteTree);
  7854. }
  7855. }
  7856. }
  7857. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7858. let newWrite = compoundWrite;
  7859. each(updates, (childKey, node) => {
  7860. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7861. });
  7862. return newWrite;
  7863. }
  7864. /**
  7865. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7866. * location, which must be removed by calling this method with that path.
  7867. *
  7868. * @param compoundWrite - The CompoundWrite to remove.
  7869. * @param path - The path at which a write and all deeper writes should be removed
  7870. * @returns The new CompoundWrite with the removed path
  7871. */
  7872. function compoundWriteRemoveWrite(compoundWrite, path) {
  7873. if (pathIsEmpty(path)) {
  7874. return CompoundWrite.empty();
  7875. }
  7876. else {
  7877. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7878. return new CompoundWrite(newWriteTree);
  7879. }
  7880. }
  7881. /**
  7882. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7883. * considered "complete".
  7884. *
  7885. * @param compoundWrite - The CompoundWrite to check.
  7886. * @param path - The path to check for
  7887. * @returns Whether there is a complete write at that path
  7888. */
  7889. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7890. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7891. }
  7892. /**
  7893. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7894. * writes from deeper paths, but will return child nodes from a more shallow path.
  7895. *
  7896. * @param compoundWrite - The CompoundWrite to get the node from.
  7897. * @param path - The path to get a complete write
  7898. * @returns The node if complete at that path, or null otherwise.
  7899. */
  7900. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7901. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7902. if (rootmost != null) {
  7903. return compoundWrite.writeTree_
  7904. .get(rootmost.path)
  7905. .getChild(newRelativePath(rootmost.path, path));
  7906. }
  7907. else {
  7908. return null;
  7909. }
  7910. }
  7911. /**
  7912. * Returns all children that are guaranteed to be a complete overwrite.
  7913. *
  7914. * @param compoundWrite - The CompoundWrite to get children from.
  7915. * @returns A list of all complete children.
  7916. */
  7917. function compoundWriteGetCompleteChildren(compoundWrite) {
  7918. const children = [];
  7919. const node = compoundWrite.writeTree_.value;
  7920. if (node != null) {
  7921. // If it's a leaf node, it has no children; so nothing to do.
  7922. if (!node.isLeafNode()) {
  7923. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7924. children.push(new NamedNode(childName, childNode));
  7925. });
  7926. }
  7927. }
  7928. else {
  7929. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7930. if (childTree.value != null) {
  7931. children.push(new NamedNode(childName, childTree.value));
  7932. }
  7933. });
  7934. }
  7935. return children;
  7936. }
  7937. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7938. if (pathIsEmpty(path)) {
  7939. return compoundWrite;
  7940. }
  7941. else {
  7942. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7943. if (shadowingNode != null) {
  7944. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7945. }
  7946. else {
  7947. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7948. }
  7949. }
  7950. }
  7951. /**
  7952. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7953. * @returns Whether this CompoundWrite is empty
  7954. */
  7955. function compoundWriteIsEmpty(compoundWrite) {
  7956. return compoundWrite.writeTree_.isEmpty();
  7957. }
  7958. /**
  7959. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7960. * node
  7961. * @param node - The node to apply this CompoundWrite to
  7962. * @returns The node with all writes applied
  7963. */
  7964. function compoundWriteApply(compoundWrite, node) {
  7965. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7966. }
  7967. function applySubtreeWrite(relativePath, writeTree, node) {
  7968. if (writeTree.value != null) {
  7969. // Since there a write is always a leaf, we're done here
  7970. return node.updateChild(relativePath, writeTree.value);
  7971. }
  7972. else {
  7973. let priorityWrite = null;
  7974. writeTree.children.inorderTraversal((childKey, childTree) => {
  7975. if (childKey === '.priority') {
  7976. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7977. // to apply priorities to empty nodes that are later filled
  7978. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7979. priorityWrite = childTree.value;
  7980. }
  7981. else {
  7982. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7983. }
  7984. });
  7985. // If there was a priority write, we only apply it if the node is not empty
  7986. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7987. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7988. }
  7989. return node;
  7990. }
  7991. }
  7992. /**
  7993. * @license
  7994. * Copyright 2017 Google LLC
  7995. *
  7996. * Licensed under the Apache License, Version 2.0 (the "License");
  7997. * you may not use this file except in compliance with the License.
  7998. * You may obtain a copy of the License at
  7999. *
  8000. * http://www.apache.org/licenses/LICENSE-2.0
  8001. *
  8002. * Unless required by applicable law or agreed to in writing, software
  8003. * distributed under the License is distributed on an "AS IS" BASIS,
  8004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8005. * See the License for the specific language governing permissions and
  8006. * limitations under the License.
  8007. */
  8008. /**
  8009. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8010. *
  8011. */
  8012. function writeTreeChildWrites(writeTree, path) {
  8013. return newWriteTreeRef(path, writeTree);
  8014. }
  8015. /**
  8016. * Record a new overwrite from user code.
  8017. *
  8018. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8019. */
  8020. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8021. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8022. if (visible === undefined) {
  8023. visible = true;
  8024. }
  8025. writeTree.allWrites.push({
  8026. path,
  8027. snap,
  8028. writeId,
  8029. visible
  8030. });
  8031. if (visible) {
  8032. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8033. }
  8034. writeTree.lastWriteId = writeId;
  8035. }
  8036. /**
  8037. * Record a new merge from user code.
  8038. */
  8039. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8040. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8041. writeTree.allWrites.push({
  8042. path,
  8043. children: changedChildren,
  8044. writeId,
  8045. visible: true
  8046. });
  8047. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8048. writeTree.lastWriteId = writeId;
  8049. }
  8050. function writeTreeGetWrite(writeTree, writeId) {
  8051. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8052. const record = writeTree.allWrites[i];
  8053. if (record.writeId === writeId) {
  8054. return record;
  8055. }
  8056. }
  8057. return null;
  8058. }
  8059. /**
  8060. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8061. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8062. *
  8063. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8064. * events as a result).
  8065. */
  8066. function writeTreeRemoveWrite(writeTree, writeId) {
  8067. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8068. // out of order.
  8069. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8070. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8071. const idx = writeTree.allWrites.findIndex(s => {
  8072. return s.writeId === writeId;
  8073. });
  8074. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8075. const writeToRemove = writeTree.allWrites[idx];
  8076. writeTree.allWrites.splice(idx, 1);
  8077. let removedWriteWasVisible = writeToRemove.visible;
  8078. let removedWriteOverlapsWithOtherWrites = false;
  8079. let i = writeTree.allWrites.length - 1;
  8080. while (removedWriteWasVisible && i >= 0) {
  8081. const currentWrite = writeTree.allWrites[i];
  8082. if (currentWrite.visible) {
  8083. if (i >= idx &&
  8084. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8085. // The removed write was completely shadowed by a subsequent write.
  8086. removedWriteWasVisible = false;
  8087. }
  8088. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8089. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8090. removedWriteOverlapsWithOtherWrites = true;
  8091. }
  8092. }
  8093. i--;
  8094. }
  8095. if (!removedWriteWasVisible) {
  8096. return false;
  8097. }
  8098. else if (removedWriteOverlapsWithOtherWrites) {
  8099. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8100. writeTreeResetTree_(writeTree);
  8101. return true;
  8102. }
  8103. else {
  8104. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8105. if (writeToRemove.snap) {
  8106. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8107. }
  8108. else {
  8109. const children = writeToRemove.children;
  8110. each(children, (childName) => {
  8111. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8112. });
  8113. }
  8114. return true;
  8115. }
  8116. }
  8117. function writeTreeRecordContainsPath_(writeRecord, path) {
  8118. if (writeRecord.snap) {
  8119. return pathContains(writeRecord.path, path);
  8120. }
  8121. else {
  8122. for (const childName in writeRecord.children) {
  8123. if (writeRecord.children.hasOwnProperty(childName) &&
  8124. pathContains(pathChild(writeRecord.path, childName), path)) {
  8125. return true;
  8126. }
  8127. }
  8128. return false;
  8129. }
  8130. }
  8131. /**
  8132. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8133. */
  8134. function writeTreeResetTree_(writeTree) {
  8135. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8136. if (writeTree.allWrites.length > 0) {
  8137. writeTree.lastWriteId =
  8138. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8139. }
  8140. else {
  8141. writeTree.lastWriteId = -1;
  8142. }
  8143. }
  8144. /**
  8145. * The default filter used when constructing the tree. Keep everything that's visible.
  8146. */
  8147. function writeTreeDefaultFilter_(write) {
  8148. return write.visible;
  8149. }
  8150. /**
  8151. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8152. * event data at that path.
  8153. */
  8154. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8155. let compoundWrite = CompoundWrite.empty();
  8156. for (let i = 0; i < writes.length; ++i) {
  8157. const write = writes[i];
  8158. // Theory, a later set will either:
  8159. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8160. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8161. if (filter(write)) {
  8162. const writePath = write.path;
  8163. let relativePath;
  8164. if (write.snap) {
  8165. if (pathContains(treeRoot, writePath)) {
  8166. relativePath = newRelativePath(treeRoot, writePath);
  8167. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8168. }
  8169. else if (pathContains(writePath, treeRoot)) {
  8170. relativePath = newRelativePath(writePath, treeRoot);
  8171. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8172. }
  8173. else ;
  8174. }
  8175. else if (write.children) {
  8176. if (pathContains(treeRoot, writePath)) {
  8177. relativePath = newRelativePath(treeRoot, writePath);
  8178. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8179. }
  8180. else if (pathContains(writePath, treeRoot)) {
  8181. relativePath = newRelativePath(writePath, treeRoot);
  8182. if (pathIsEmpty(relativePath)) {
  8183. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8184. }
  8185. else {
  8186. const child = util.safeGet(write.children, pathGetFront(relativePath));
  8187. if (child) {
  8188. // There exists a child in this node that matches the root path
  8189. const deepNode = child.getChild(pathPopFront(relativePath));
  8190. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8191. }
  8192. }
  8193. }
  8194. else ;
  8195. }
  8196. else {
  8197. throw util.assertionError('WriteRecord should have .snap or .children');
  8198. }
  8199. }
  8200. }
  8201. return compoundWrite;
  8202. }
  8203. /**
  8204. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8205. * writes), attempt to calculate a complete snapshot for the given path
  8206. *
  8207. * @param writeIdsToExclude - An optional set to be excluded
  8208. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8209. */
  8210. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8211. if (!writeIdsToExclude && !includeHiddenWrites) {
  8212. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8213. if (shadowingNode != null) {
  8214. return shadowingNode;
  8215. }
  8216. else {
  8217. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8218. if (compoundWriteIsEmpty(subMerge)) {
  8219. return completeServerCache;
  8220. }
  8221. else if (completeServerCache == null &&
  8222. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8223. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8224. return null;
  8225. }
  8226. else {
  8227. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8228. return compoundWriteApply(subMerge, layeredCache);
  8229. }
  8230. }
  8231. }
  8232. else {
  8233. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8234. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8235. return completeServerCache;
  8236. }
  8237. else {
  8238. // If the server cache is null, and we don't have a complete cache, we need to return null
  8239. if (!includeHiddenWrites &&
  8240. completeServerCache == null &&
  8241. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8242. return null;
  8243. }
  8244. else {
  8245. const filter = function (write) {
  8246. return ((write.visible || includeHiddenWrites) &&
  8247. (!writeIdsToExclude ||
  8248. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8249. (pathContains(write.path, treePath) ||
  8250. pathContains(treePath, write.path)));
  8251. };
  8252. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8253. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8254. return compoundWriteApply(mergeAtPath, layeredCache);
  8255. }
  8256. }
  8257. }
  8258. }
  8259. /**
  8260. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8261. * Used when creating new views, to pre-fill their complete event children snapshot.
  8262. */
  8263. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8264. let completeChildren = ChildrenNode.EMPTY_NODE;
  8265. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8266. if (topLevelSet) {
  8267. if (!topLevelSet.isLeafNode()) {
  8268. // we're shadowing everything. Return the children.
  8269. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8270. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8271. });
  8272. }
  8273. return completeChildren;
  8274. }
  8275. else if (completeServerChildren) {
  8276. // Layer any children we have on top of this
  8277. // We know we don't have a top-level set, so just enumerate existing children
  8278. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8279. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8280. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8281. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8282. });
  8283. // Add any complete children we have from the set
  8284. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8285. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8286. });
  8287. return completeChildren;
  8288. }
  8289. else {
  8290. // We don't have anything to layer on top of. Layer on any children we have
  8291. // Note that we can return an empty snap if we have a defined delete
  8292. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8293. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8294. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8295. });
  8296. return completeChildren;
  8297. }
  8298. }
  8299. /**
  8300. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8301. * applied to the event cache.
  8302. *
  8303. * Possibilities:
  8304. *
  8305. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8306. *
  8307. * 2. Some write is completely shadowing. No events to be raised
  8308. *
  8309. * 3. Is partially shadowed. Events
  8310. *
  8311. * Either existingEventSnap or existingServerSnap must exist
  8312. */
  8313. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8314. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8315. const path = pathChild(treePath, childPath);
  8316. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8317. // At this point we can probably guarantee that we're in case 2, meaning no events
  8318. // May need to check visibility while doing the findRootMostValueAndPath call
  8319. return null;
  8320. }
  8321. else {
  8322. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8323. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8324. if (compoundWriteIsEmpty(childMerge)) {
  8325. // We're not shadowing at all. Case 1
  8326. return existingServerSnap.getChild(childPath);
  8327. }
  8328. else {
  8329. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8330. // However this is tricky to find out, since user updates don't necessary change the server
  8331. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8332. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8333. // only check if the updates change the serverNode.
  8334. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8335. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8336. }
  8337. }
  8338. }
  8339. /**
  8340. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8341. * complete child for this ChildKey.
  8342. */
  8343. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8344. const path = pathChild(treePath, childKey);
  8345. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8346. if (shadowingNode != null) {
  8347. return shadowingNode;
  8348. }
  8349. else {
  8350. if (existingServerSnap.isCompleteForChild(childKey)) {
  8351. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8352. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8353. }
  8354. else {
  8355. return null;
  8356. }
  8357. }
  8358. }
  8359. /**
  8360. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8361. * a higher path, this will return the child of that write relative to the write and this path.
  8362. * Returns null if there is no write at this path.
  8363. */
  8364. function writeTreeShadowingWrite(writeTree, path) {
  8365. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8366. }
  8367. /**
  8368. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8369. * the window, but may now be in the window.
  8370. */
  8371. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8372. let toIterate;
  8373. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8374. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8375. if (shadowingNode != null) {
  8376. toIterate = shadowingNode;
  8377. }
  8378. else if (completeServerData != null) {
  8379. toIterate = compoundWriteApply(merge, completeServerData);
  8380. }
  8381. else {
  8382. // no children to iterate on
  8383. return [];
  8384. }
  8385. toIterate = toIterate.withIndex(index);
  8386. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8387. const nodes = [];
  8388. const cmp = index.getCompare();
  8389. const iter = reverse
  8390. ? toIterate.getReverseIteratorFrom(startPost, index)
  8391. : toIterate.getIteratorFrom(startPost, index);
  8392. let next = iter.getNext();
  8393. while (next && nodes.length < count) {
  8394. if (cmp(next, startPost) !== 0) {
  8395. nodes.push(next);
  8396. }
  8397. next = iter.getNext();
  8398. }
  8399. return nodes;
  8400. }
  8401. else {
  8402. return [];
  8403. }
  8404. }
  8405. function newWriteTree() {
  8406. return {
  8407. visibleWrites: CompoundWrite.empty(),
  8408. allWrites: [],
  8409. lastWriteId: -1
  8410. };
  8411. }
  8412. /**
  8413. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8414. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8415. * can lead to a more expensive calculation.
  8416. *
  8417. * @param writeIdsToExclude - Optional writes to exclude.
  8418. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8419. */
  8420. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8421. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8422. }
  8423. /**
  8424. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8425. * mix of the given server data and write data.
  8426. *
  8427. */
  8428. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8429. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8430. }
  8431. /**
  8432. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8433. * if anything, needs to be applied to the event cache.
  8434. *
  8435. * Possibilities:
  8436. *
  8437. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8438. *
  8439. * 2. Some write is completely shadowing. No events to be raised
  8440. *
  8441. * 3. Is partially shadowed. Events should be raised
  8442. *
  8443. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8444. *
  8445. *
  8446. */
  8447. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8448. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8449. }
  8450. /**
  8451. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8452. * a higher path, this will return the child of that write relative to the write and this path.
  8453. * Returns null if there is no write at this path.
  8454. *
  8455. */
  8456. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8457. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8458. }
  8459. /**
  8460. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8461. * the window, but may now be in the window
  8462. */
  8463. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8464. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8465. }
  8466. /**
  8467. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8468. * complete child for this ChildKey.
  8469. */
  8470. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8471. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8472. }
  8473. /**
  8474. * Return a WriteTreeRef for a child.
  8475. */
  8476. function writeTreeRefChild(writeTreeRef, childName) {
  8477. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8478. }
  8479. function newWriteTreeRef(path, writeTree) {
  8480. return {
  8481. treePath: path,
  8482. writeTree
  8483. };
  8484. }
  8485. /**
  8486. * @license
  8487. * Copyright 2017 Google LLC
  8488. *
  8489. * Licensed under the Apache License, Version 2.0 (the "License");
  8490. * you may not use this file except in compliance with the License.
  8491. * You may obtain a copy of the License at
  8492. *
  8493. * http://www.apache.org/licenses/LICENSE-2.0
  8494. *
  8495. * Unless required by applicable law or agreed to in writing, software
  8496. * distributed under the License is distributed on an "AS IS" BASIS,
  8497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8498. * See the License for the specific language governing permissions and
  8499. * limitations under the License.
  8500. */
  8501. class ChildChangeAccumulator {
  8502. constructor() {
  8503. this.changeMap = new Map();
  8504. }
  8505. trackChildChange(change) {
  8506. const type = change.type;
  8507. const childKey = change.childName;
  8508. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8509. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8510. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8511. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8512. const oldChange = this.changeMap.get(childKey);
  8513. if (oldChange) {
  8514. const oldType = oldChange.type;
  8515. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8516. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8517. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8518. }
  8519. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8520. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8521. this.changeMap.delete(childKey);
  8522. }
  8523. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8524. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8525. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8526. }
  8527. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8528. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8529. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8530. }
  8531. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8532. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8533. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8534. }
  8535. else {
  8536. throw util.assertionError('Illegal combination of changes: ' +
  8537. change +
  8538. ' occurred after ' +
  8539. oldChange);
  8540. }
  8541. }
  8542. else {
  8543. this.changeMap.set(childKey, change);
  8544. }
  8545. }
  8546. getChanges() {
  8547. return Array.from(this.changeMap.values());
  8548. }
  8549. }
  8550. /**
  8551. * @license
  8552. * Copyright 2017 Google LLC
  8553. *
  8554. * Licensed under the Apache License, Version 2.0 (the "License");
  8555. * you may not use this file except in compliance with the License.
  8556. * You may obtain a copy of the License at
  8557. *
  8558. * http://www.apache.org/licenses/LICENSE-2.0
  8559. *
  8560. * Unless required by applicable law or agreed to in writing, software
  8561. * distributed under the License is distributed on an "AS IS" BASIS,
  8562. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8563. * See the License for the specific language governing permissions and
  8564. * limitations under the License.
  8565. */
  8566. /**
  8567. * An implementation of CompleteChildSource that never returns any additional children
  8568. */
  8569. // eslint-disable-next-line @typescript-eslint/naming-convention
  8570. class NoCompleteChildSource_ {
  8571. getCompleteChild(childKey) {
  8572. return null;
  8573. }
  8574. getChildAfterChild(index, child, reverse) {
  8575. return null;
  8576. }
  8577. }
  8578. /**
  8579. * Singleton instance.
  8580. */
  8581. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8582. /**
  8583. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8584. * old event caches available to calculate complete children.
  8585. */
  8586. class WriteTreeCompleteChildSource {
  8587. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8588. this.writes_ = writes_;
  8589. this.viewCache_ = viewCache_;
  8590. this.optCompleteServerCache_ = optCompleteServerCache_;
  8591. }
  8592. getCompleteChild(childKey) {
  8593. const node = this.viewCache_.eventCache;
  8594. if (node.isCompleteForChild(childKey)) {
  8595. return node.getNode().getImmediateChild(childKey);
  8596. }
  8597. else {
  8598. const serverNode = this.optCompleteServerCache_ != null
  8599. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8600. : this.viewCache_.serverCache;
  8601. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8602. }
  8603. }
  8604. getChildAfterChild(index, child, reverse) {
  8605. const completeServerData = this.optCompleteServerCache_ != null
  8606. ? this.optCompleteServerCache_
  8607. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8608. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8609. if (nodes.length === 0) {
  8610. return null;
  8611. }
  8612. else {
  8613. return nodes[0];
  8614. }
  8615. }
  8616. }
  8617. /**
  8618. * @license
  8619. * Copyright 2017 Google LLC
  8620. *
  8621. * Licensed under the Apache License, Version 2.0 (the "License");
  8622. * you may not use this file except in compliance with the License.
  8623. * You may obtain a copy of the License at
  8624. *
  8625. * http://www.apache.org/licenses/LICENSE-2.0
  8626. *
  8627. * Unless required by applicable law or agreed to in writing, software
  8628. * distributed under the License is distributed on an "AS IS" BASIS,
  8629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8630. * See the License for the specific language governing permissions and
  8631. * limitations under the License.
  8632. */
  8633. function newViewProcessor(filter) {
  8634. return { filter };
  8635. }
  8636. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8637. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8638. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8639. }
  8640. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8641. const accumulator = new ChildChangeAccumulator();
  8642. let newViewCache, filterServerNode;
  8643. if (operation.type === OperationType.OVERWRITE) {
  8644. const overwrite = operation;
  8645. if (overwrite.source.fromUser) {
  8646. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8647. }
  8648. else {
  8649. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8650. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8651. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8652. // again
  8653. filterServerNode =
  8654. overwrite.source.tagged ||
  8655. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8656. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8657. }
  8658. }
  8659. else if (operation.type === OperationType.MERGE) {
  8660. const merge = operation;
  8661. if (merge.source.fromUser) {
  8662. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8663. }
  8664. else {
  8665. util.assert(merge.source.fromServer, 'Unknown source.');
  8666. // We filter the node if it's a tagged update or the node has been previously filtered
  8667. filterServerNode =
  8668. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8669. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8670. }
  8671. }
  8672. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8673. const ackUserWrite = operation;
  8674. if (!ackUserWrite.revert) {
  8675. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8676. }
  8677. else {
  8678. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8679. }
  8680. }
  8681. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8682. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8683. }
  8684. else {
  8685. throw util.assertionError('Unknown operation type: ' + operation.type);
  8686. }
  8687. const changes = accumulator.getChanges();
  8688. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8689. return { viewCache: newViewCache, changes };
  8690. }
  8691. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8692. const eventSnap = newViewCache.eventCache;
  8693. if (eventSnap.isFullyInitialized()) {
  8694. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8695. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8696. if (accumulator.length > 0 ||
  8697. !oldViewCache.eventCache.isFullyInitialized() ||
  8698. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8699. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8700. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8701. }
  8702. }
  8703. }
  8704. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8705. const oldEventSnap = viewCache.eventCache;
  8706. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8707. // we have a shadowing write, ignore changes
  8708. return viewCache;
  8709. }
  8710. else {
  8711. let newEventCache, serverNode;
  8712. if (pathIsEmpty(changePath)) {
  8713. // TODO: figure out how this plays with "sliding ack windows"
  8714. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8715. if (viewCache.serverCache.isFiltered()) {
  8716. // We need to special case this, because we need to only apply writes to complete children, or
  8717. // we might end up raising events for incomplete children. If the server data is filtered deep
  8718. // writes cannot be guaranteed to be complete
  8719. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8720. const completeChildren = serverCache instanceof ChildrenNode
  8721. ? serverCache
  8722. : ChildrenNode.EMPTY_NODE;
  8723. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8724. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8725. }
  8726. else {
  8727. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8728. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8729. }
  8730. }
  8731. else {
  8732. const childKey = pathGetFront(changePath);
  8733. if (childKey === '.priority') {
  8734. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8735. const oldEventNode = oldEventSnap.getNode();
  8736. serverNode = viewCache.serverCache.getNode();
  8737. // we might have overwrites for this priority
  8738. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8739. if (updatedPriority != null) {
  8740. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8741. }
  8742. else {
  8743. // priority didn't change, keep old node
  8744. newEventCache = oldEventSnap.getNode();
  8745. }
  8746. }
  8747. else {
  8748. const childChangePath = pathPopFront(changePath);
  8749. // update child
  8750. let newEventChild;
  8751. if (oldEventSnap.isCompleteForChild(childKey)) {
  8752. serverNode = viewCache.serverCache.getNode();
  8753. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8754. if (eventChildUpdate != null) {
  8755. newEventChild = oldEventSnap
  8756. .getNode()
  8757. .getImmediateChild(childKey)
  8758. .updateChild(childChangePath, eventChildUpdate);
  8759. }
  8760. else {
  8761. // Nothing changed, just keep the old child
  8762. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8763. }
  8764. }
  8765. else {
  8766. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8767. }
  8768. if (newEventChild != null) {
  8769. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8770. }
  8771. else {
  8772. // no complete child available or no change
  8773. newEventCache = oldEventSnap.getNode();
  8774. }
  8775. }
  8776. }
  8777. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8778. }
  8779. }
  8780. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8781. const oldServerSnap = oldViewCache.serverCache;
  8782. let newServerCache;
  8783. const serverFilter = filterServerNode
  8784. ? viewProcessor.filter
  8785. : viewProcessor.filter.getIndexedFilter();
  8786. if (pathIsEmpty(changePath)) {
  8787. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8788. }
  8789. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8790. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8791. const newServerNode = oldServerSnap
  8792. .getNode()
  8793. .updateChild(changePath, changedSnap);
  8794. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8795. }
  8796. else {
  8797. const childKey = pathGetFront(changePath);
  8798. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8799. pathGetLength(changePath) > 1) {
  8800. // We don't update incomplete nodes with updates intended for other listeners
  8801. return oldViewCache;
  8802. }
  8803. const childChangePath = pathPopFront(changePath);
  8804. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8805. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8806. if (childKey === '.priority') {
  8807. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8808. }
  8809. else {
  8810. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8811. }
  8812. }
  8813. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8814. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8815. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8816. }
  8817. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8818. const oldEventSnap = oldViewCache.eventCache;
  8819. let newViewCache, newEventCache;
  8820. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8821. if (pathIsEmpty(changePath)) {
  8822. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8823. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8824. }
  8825. else {
  8826. const childKey = pathGetFront(changePath);
  8827. if (childKey === '.priority') {
  8828. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8829. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8830. }
  8831. else {
  8832. const childChangePath = pathPopFront(changePath);
  8833. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8834. let newChild;
  8835. if (pathIsEmpty(childChangePath)) {
  8836. // Child overwrite, we can replace the child
  8837. newChild = changedSnap;
  8838. }
  8839. else {
  8840. const childNode = source.getCompleteChild(childKey);
  8841. if (childNode != null) {
  8842. if (pathGetBack(childChangePath) === '.priority' &&
  8843. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8844. // This is a priority update on an empty node. If this node exists on the server, the
  8845. // server will send down the priority in the update, so ignore for now
  8846. newChild = childNode;
  8847. }
  8848. else {
  8849. newChild = childNode.updateChild(childChangePath, changedSnap);
  8850. }
  8851. }
  8852. else {
  8853. // There is no complete child node available
  8854. newChild = ChildrenNode.EMPTY_NODE;
  8855. }
  8856. }
  8857. if (!oldChild.equals(newChild)) {
  8858. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8859. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8860. }
  8861. else {
  8862. newViewCache = oldViewCache;
  8863. }
  8864. }
  8865. }
  8866. return newViewCache;
  8867. }
  8868. function viewProcessorCacheHasChild(viewCache, childKey) {
  8869. return viewCache.eventCache.isCompleteForChild(childKey);
  8870. }
  8871. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8872. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8873. // window leaving room for new items. It's important we process these changes first, so we
  8874. // iterate the changes twice, first processing any that affect items currently in view.
  8875. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8876. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8877. // not the other.
  8878. let curViewCache = viewCache;
  8879. changedChildren.foreach((relativePath, childNode) => {
  8880. const writePath = pathChild(path, relativePath);
  8881. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8882. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8883. }
  8884. });
  8885. changedChildren.foreach((relativePath, childNode) => {
  8886. const writePath = pathChild(path, relativePath);
  8887. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8888. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8889. }
  8890. });
  8891. return curViewCache;
  8892. }
  8893. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8894. merge.foreach((relativePath, childNode) => {
  8895. node = node.updateChild(relativePath, childNode);
  8896. });
  8897. return node;
  8898. }
  8899. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8900. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8901. // wait for the complete data update coming soon.
  8902. if (viewCache.serverCache.getNode().isEmpty() &&
  8903. !viewCache.serverCache.isFullyInitialized()) {
  8904. return viewCache;
  8905. }
  8906. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8907. // window leaving room for new items. It's important we process these changes first, so we
  8908. // iterate the changes twice, first processing any that affect items currently in view.
  8909. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8910. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8911. // not the other.
  8912. let curViewCache = viewCache;
  8913. let viewMergeTree;
  8914. if (pathIsEmpty(path)) {
  8915. viewMergeTree = changedChildren;
  8916. }
  8917. else {
  8918. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8919. }
  8920. const serverNode = viewCache.serverCache.getNode();
  8921. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8922. if (serverNode.hasChild(childKey)) {
  8923. const serverChild = viewCache.serverCache
  8924. .getNode()
  8925. .getImmediateChild(childKey);
  8926. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8927. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8928. }
  8929. });
  8930. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8931. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8932. childMergeTree.value === null;
  8933. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8934. const serverChild = viewCache.serverCache
  8935. .getNode()
  8936. .getImmediateChild(childKey);
  8937. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8938. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8939. }
  8940. });
  8941. return curViewCache;
  8942. }
  8943. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8944. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8945. return viewCache;
  8946. }
  8947. // Only filter server node if it is currently filtered
  8948. const filterServerNode = viewCache.serverCache.isFiltered();
  8949. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8950. // now that it won't be shadowed.
  8951. const serverCache = viewCache.serverCache;
  8952. if (affectedTree.value != null) {
  8953. // This is an overwrite.
  8954. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8955. serverCache.isCompleteForPath(ackPath)) {
  8956. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8957. }
  8958. else if (pathIsEmpty(ackPath)) {
  8959. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8960. // should just re-apply whatever we have in our cache as a merge.
  8961. let changedChildren = new ImmutableTree(null);
  8962. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8963. changedChildren = changedChildren.set(new Path(name), node);
  8964. });
  8965. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8966. }
  8967. else {
  8968. return viewCache;
  8969. }
  8970. }
  8971. else {
  8972. // This is a merge.
  8973. let changedChildren = new ImmutableTree(null);
  8974. affectedTree.foreach((mergePath, value) => {
  8975. const serverCachePath = pathChild(ackPath, mergePath);
  8976. if (serverCache.isCompleteForPath(serverCachePath)) {
  8977. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8978. }
  8979. });
  8980. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8981. }
  8982. }
  8983. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8984. const oldServerNode = viewCache.serverCache;
  8985. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8986. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8987. }
  8988. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8989. let complete;
  8990. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8991. return viewCache;
  8992. }
  8993. else {
  8994. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8995. const oldEventCache = viewCache.eventCache.getNode();
  8996. let newEventCache;
  8997. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  8998. let newNode;
  8999. if (viewCache.serverCache.isFullyInitialized()) {
  9000. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9001. }
  9002. else {
  9003. const serverChildren = viewCache.serverCache.getNode();
  9004. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9005. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9006. }
  9007. newNode = newNode;
  9008. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9009. }
  9010. else {
  9011. const childKey = pathGetFront(path);
  9012. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9013. if (newChild == null &&
  9014. viewCache.serverCache.isCompleteForChild(childKey)) {
  9015. newChild = oldEventCache.getImmediateChild(childKey);
  9016. }
  9017. if (newChild != null) {
  9018. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9019. }
  9020. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9021. // No complete child available, delete the existing one, if any
  9022. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9023. }
  9024. else {
  9025. newEventCache = oldEventCache;
  9026. }
  9027. if (newEventCache.isEmpty() &&
  9028. viewCache.serverCache.isFullyInitialized()) {
  9029. // We might have reverted all child writes. Maybe the old event was a leaf node
  9030. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9031. if (complete.isLeafNode()) {
  9032. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9033. }
  9034. }
  9035. }
  9036. complete =
  9037. viewCache.serverCache.isFullyInitialized() ||
  9038. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9039. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9040. }
  9041. }
  9042. /**
  9043. * @license
  9044. * Copyright 2017 Google LLC
  9045. *
  9046. * Licensed under the Apache License, Version 2.0 (the "License");
  9047. * you may not use this file except in compliance with the License.
  9048. * You may obtain a copy of the License at
  9049. *
  9050. * http://www.apache.org/licenses/LICENSE-2.0
  9051. *
  9052. * Unless required by applicable law or agreed to in writing, software
  9053. * distributed under the License is distributed on an "AS IS" BASIS,
  9054. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9055. * See the License for the specific language governing permissions and
  9056. * limitations under the License.
  9057. */
  9058. /**
  9059. * A view represents a specific location and query that has 1 or more event registrations.
  9060. *
  9061. * It does several things:
  9062. * - Maintains the list of event registrations for this location/query.
  9063. * - Maintains a cache of the data visible for this location/query.
  9064. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9065. * registrations returns the set of events to be raised.
  9066. */
  9067. class View {
  9068. constructor(query_, initialViewCache) {
  9069. this.query_ = query_;
  9070. this.eventRegistrations_ = [];
  9071. const params = this.query_._queryParams;
  9072. const indexFilter = new IndexedFilter(params.getIndex());
  9073. const filter = queryParamsGetNodeFilter(params);
  9074. this.processor_ = newViewProcessor(filter);
  9075. const initialServerCache = initialViewCache.serverCache;
  9076. const initialEventCache = initialViewCache.eventCache;
  9077. // Don't filter server node with other filter than index, wait for tagged listen
  9078. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9079. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9080. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9081. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9082. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9083. this.eventGenerator_ = new EventGenerator(this.query_);
  9084. }
  9085. get query() {
  9086. return this.query_;
  9087. }
  9088. }
  9089. function viewGetServerCache(view) {
  9090. return view.viewCache_.serverCache.getNode();
  9091. }
  9092. function viewGetCompleteNode(view) {
  9093. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9094. }
  9095. function viewGetCompleteServerCache(view, path) {
  9096. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9097. if (cache) {
  9098. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9099. // we need to see if it contains the child we're interested in.
  9100. if (view.query._queryParams.loadsAllData() ||
  9101. (!pathIsEmpty(path) &&
  9102. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9103. return cache.getChild(path);
  9104. }
  9105. }
  9106. return null;
  9107. }
  9108. function viewIsEmpty(view) {
  9109. return view.eventRegistrations_.length === 0;
  9110. }
  9111. function viewAddEventRegistration(view, eventRegistration) {
  9112. view.eventRegistrations_.push(eventRegistration);
  9113. }
  9114. /**
  9115. * @param eventRegistration - If null, remove all callbacks.
  9116. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9117. * @returns Cancel events, if cancelError was provided.
  9118. */
  9119. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9120. const cancelEvents = [];
  9121. if (cancelError) {
  9122. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9123. const path = view.query._path;
  9124. view.eventRegistrations_.forEach(registration => {
  9125. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9126. if (maybeEvent) {
  9127. cancelEvents.push(maybeEvent);
  9128. }
  9129. });
  9130. }
  9131. if (eventRegistration) {
  9132. let remaining = [];
  9133. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9134. const existing = view.eventRegistrations_[i];
  9135. if (!existing.matches(eventRegistration)) {
  9136. remaining.push(existing);
  9137. }
  9138. else if (eventRegistration.hasAnyCallback()) {
  9139. // We're removing just this one
  9140. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9141. break;
  9142. }
  9143. }
  9144. view.eventRegistrations_ = remaining;
  9145. }
  9146. else {
  9147. view.eventRegistrations_ = [];
  9148. }
  9149. return cancelEvents;
  9150. }
  9151. /**
  9152. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9153. */
  9154. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9155. if (operation.type === OperationType.MERGE &&
  9156. operation.source.queryId !== null) {
  9157. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9158. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9159. }
  9160. const oldViewCache = view.viewCache_;
  9161. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9162. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9163. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9164. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9165. view.viewCache_ = result.viewCache;
  9166. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9167. }
  9168. function viewGetInitialEvents(view, registration) {
  9169. const eventSnap = view.viewCache_.eventCache;
  9170. const initialChanges = [];
  9171. if (!eventSnap.getNode().isLeafNode()) {
  9172. const eventNode = eventSnap.getNode();
  9173. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9174. initialChanges.push(changeChildAdded(key, childNode));
  9175. });
  9176. }
  9177. if (eventSnap.isFullyInitialized()) {
  9178. initialChanges.push(changeValue(eventSnap.getNode()));
  9179. }
  9180. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9181. }
  9182. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9183. const registrations = eventRegistration
  9184. ? [eventRegistration]
  9185. : view.eventRegistrations_;
  9186. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9187. }
  9188. /**
  9189. * @license
  9190. * Copyright 2017 Google LLC
  9191. *
  9192. * Licensed under the Apache License, Version 2.0 (the "License");
  9193. * you may not use this file except in compliance with the License.
  9194. * You may obtain a copy of the License at
  9195. *
  9196. * http://www.apache.org/licenses/LICENSE-2.0
  9197. *
  9198. * Unless required by applicable law or agreed to in writing, software
  9199. * distributed under the License is distributed on an "AS IS" BASIS,
  9200. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9201. * See the License for the specific language governing permissions and
  9202. * limitations under the License.
  9203. */
  9204. let referenceConstructor$1;
  9205. /**
  9206. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9207. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9208. * and user writes (set, transaction, update).
  9209. *
  9210. * It's responsible for:
  9211. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9212. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9213. * applyUserOverwrite, etc.)
  9214. */
  9215. class SyncPoint {
  9216. constructor() {
  9217. /**
  9218. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9219. * queryId and the value is the View for that query.
  9220. *
  9221. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9222. */
  9223. this.views = new Map();
  9224. }
  9225. }
  9226. function syncPointSetReferenceConstructor(val) {
  9227. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9228. referenceConstructor$1 = val;
  9229. }
  9230. function syncPointGetReferenceConstructor() {
  9231. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9232. return referenceConstructor$1;
  9233. }
  9234. function syncPointIsEmpty(syncPoint) {
  9235. return syncPoint.views.size === 0;
  9236. }
  9237. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9238. const queryId = operation.source.queryId;
  9239. if (queryId !== null) {
  9240. const view = syncPoint.views.get(queryId);
  9241. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9242. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9243. }
  9244. else {
  9245. let events = [];
  9246. for (const view of syncPoint.views.values()) {
  9247. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9248. }
  9249. return events;
  9250. }
  9251. }
  9252. /**
  9253. * Get a view for the specified query.
  9254. *
  9255. * @param query - The query to return a view for
  9256. * @param writesCache
  9257. * @param serverCache
  9258. * @param serverCacheComplete
  9259. * @returns Events to raise.
  9260. */
  9261. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9262. const queryId = query._queryIdentifier;
  9263. const view = syncPoint.views.get(queryId);
  9264. if (!view) {
  9265. // TODO: make writesCache take flag for complete server node
  9266. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9267. let eventCacheComplete = false;
  9268. if (eventCache) {
  9269. eventCacheComplete = true;
  9270. }
  9271. else if (serverCache instanceof ChildrenNode) {
  9272. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9273. eventCacheComplete = false;
  9274. }
  9275. else {
  9276. eventCache = ChildrenNode.EMPTY_NODE;
  9277. eventCacheComplete = false;
  9278. }
  9279. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9280. return new View(query, viewCache);
  9281. }
  9282. return view;
  9283. }
  9284. /**
  9285. * Add an event callback for the specified query.
  9286. *
  9287. * @param query
  9288. * @param eventRegistration
  9289. * @param writesCache
  9290. * @param serverCache - Complete server cache, if we have it.
  9291. * @param serverCacheComplete
  9292. * @returns Events to raise.
  9293. */
  9294. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9295. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9296. if (!syncPoint.views.has(query._queryIdentifier)) {
  9297. syncPoint.views.set(query._queryIdentifier, view);
  9298. }
  9299. // This is guaranteed to exist now, we just created anything that was missing
  9300. viewAddEventRegistration(view, eventRegistration);
  9301. return viewGetInitialEvents(view, eventRegistration);
  9302. }
  9303. /**
  9304. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9305. *
  9306. * If query is the default query, we'll check all views for the specified eventRegistration.
  9307. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9308. *
  9309. * @param eventRegistration - If null, remove all callbacks.
  9310. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9311. * @returns removed queries and any cancel events
  9312. */
  9313. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9314. const queryId = query._queryIdentifier;
  9315. const removed = [];
  9316. let cancelEvents = [];
  9317. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9318. if (queryId === 'default') {
  9319. // When you do ref.off(...), we search all views for the registration to remove.
  9320. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9321. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9322. if (viewIsEmpty(view)) {
  9323. syncPoint.views.delete(viewQueryId);
  9324. // We'll deal with complete views later.
  9325. if (!view.query._queryParams.loadsAllData()) {
  9326. removed.push(view.query);
  9327. }
  9328. }
  9329. }
  9330. }
  9331. else {
  9332. // remove the callback from the specific view.
  9333. const view = syncPoint.views.get(queryId);
  9334. if (view) {
  9335. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9336. if (viewIsEmpty(view)) {
  9337. syncPoint.views.delete(queryId);
  9338. // We'll deal with complete views later.
  9339. if (!view.query._queryParams.loadsAllData()) {
  9340. removed.push(view.query);
  9341. }
  9342. }
  9343. }
  9344. }
  9345. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9346. // We removed our last complete view.
  9347. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9348. }
  9349. return { removed, events: cancelEvents };
  9350. }
  9351. function syncPointGetQueryViews(syncPoint) {
  9352. const result = [];
  9353. for (const view of syncPoint.views.values()) {
  9354. if (!view.query._queryParams.loadsAllData()) {
  9355. result.push(view);
  9356. }
  9357. }
  9358. return result;
  9359. }
  9360. /**
  9361. * @param path - The path to the desired complete snapshot
  9362. * @returns A complete cache, if it exists
  9363. */
  9364. function syncPointGetCompleteServerCache(syncPoint, path) {
  9365. let serverCache = null;
  9366. for (const view of syncPoint.views.values()) {
  9367. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9368. }
  9369. return serverCache;
  9370. }
  9371. function syncPointViewForQuery(syncPoint, query) {
  9372. const params = query._queryParams;
  9373. if (params.loadsAllData()) {
  9374. return syncPointGetCompleteView(syncPoint);
  9375. }
  9376. else {
  9377. const queryId = query._queryIdentifier;
  9378. return syncPoint.views.get(queryId);
  9379. }
  9380. }
  9381. function syncPointViewExistsForQuery(syncPoint, query) {
  9382. return syncPointViewForQuery(syncPoint, query) != null;
  9383. }
  9384. function syncPointHasCompleteView(syncPoint) {
  9385. return syncPointGetCompleteView(syncPoint) != null;
  9386. }
  9387. function syncPointGetCompleteView(syncPoint) {
  9388. for (const view of syncPoint.views.values()) {
  9389. if (view.query._queryParams.loadsAllData()) {
  9390. return view;
  9391. }
  9392. }
  9393. return null;
  9394. }
  9395. /**
  9396. * @license
  9397. * Copyright 2017 Google LLC
  9398. *
  9399. * Licensed under the Apache License, Version 2.0 (the "License");
  9400. * you may not use this file except in compliance with the License.
  9401. * You may obtain a copy of the License at
  9402. *
  9403. * http://www.apache.org/licenses/LICENSE-2.0
  9404. *
  9405. * Unless required by applicable law or agreed to in writing, software
  9406. * distributed under the License is distributed on an "AS IS" BASIS,
  9407. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9408. * See the License for the specific language governing permissions and
  9409. * limitations under the License.
  9410. */
  9411. let referenceConstructor;
  9412. function syncTreeSetReferenceConstructor(val) {
  9413. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9414. referenceConstructor = val;
  9415. }
  9416. function syncTreeGetReferenceConstructor() {
  9417. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9418. return referenceConstructor;
  9419. }
  9420. /**
  9421. * Static tracker for next query tag.
  9422. */
  9423. let syncTreeNextQueryTag_ = 1;
  9424. /**
  9425. * SyncTree is the central class for managing event callback registration, data caching, views
  9426. * (query processing), and event generation. There are typically two SyncTree instances for
  9427. * each Repo, one for the normal Firebase data, and one for the .info data.
  9428. *
  9429. * It has a number of responsibilities, including:
  9430. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9431. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9432. * (applyUserOverwrite(), applyUserMerge()).
  9433. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9434. * applyServerMerge()).
  9435. * - Generating user-facing events for server and user changes (all of the apply* methods
  9436. * return the set of events that need to be raised as a result).
  9437. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9438. * to the correct set of paths and queries to satisfy the current set of user event
  9439. * callbacks (listens are started/stopped using the provided listenProvider).
  9440. *
  9441. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9442. * events are returned to the caller rather than raised synchronously.
  9443. *
  9444. */
  9445. class SyncTree {
  9446. /**
  9447. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9448. * to server data.
  9449. */
  9450. constructor(listenProvider_) {
  9451. this.listenProvider_ = listenProvider_;
  9452. /**
  9453. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9454. */
  9455. this.syncPointTree_ = new ImmutableTree(null);
  9456. /**
  9457. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9458. */
  9459. this.pendingWriteTree_ = newWriteTree();
  9460. this.tagToQueryMap = new Map();
  9461. this.queryToTagMap = new Map();
  9462. }
  9463. }
  9464. /**
  9465. * Apply the data changes for a user-generated set() or transaction() call.
  9466. *
  9467. * @returns Events to raise.
  9468. */
  9469. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9470. // Record pending write.
  9471. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9472. if (!visible) {
  9473. return [];
  9474. }
  9475. else {
  9476. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9477. }
  9478. }
  9479. /**
  9480. * Apply the data from a user-generated update() call
  9481. *
  9482. * @returns Events to raise.
  9483. */
  9484. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9485. // Record pending merge.
  9486. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9487. const changeTree = ImmutableTree.fromObject(changedChildren);
  9488. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9489. }
  9490. /**
  9491. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9492. *
  9493. * @param revert - True if the given write failed and needs to be reverted
  9494. * @returns Events to raise.
  9495. */
  9496. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9497. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9498. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9499. if (!needToReevaluate) {
  9500. return [];
  9501. }
  9502. else {
  9503. let affectedTree = new ImmutableTree(null);
  9504. if (write.snap != null) {
  9505. // overwrite
  9506. affectedTree = affectedTree.set(newEmptyPath(), true);
  9507. }
  9508. else {
  9509. each(write.children, (pathString) => {
  9510. affectedTree = affectedTree.set(new Path(pathString), true);
  9511. });
  9512. }
  9513. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9514. }
  9515. }
  9516. /**
  9517. * Apply new server data for the specified path..
  9518. *
  9519. * @returns Events to raise.
  9520. */
  9521. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9522. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9523. }
  9524. /**
  9525. * Apply new server data to be merged in at the specified path.
  9526. *
  9527. * @returns Events to raise.
  9528. */
  9529. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9530. const changeTree = ImmutableTree.fromObject(changedChildren);
  9531. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9532. }
  9533. /**
  9534. * Apply a listen complete for a query
  9535. *
  9536. * @returns Events to raise.
  9537. */
  9538. function syncTreeApplyListenComplete(syncTree, path) {
  9539. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9540. }
  9541. /**
  9542. * Apply a listen complete for a tagged query
  9543. *
  9544. * @returns Events to raise.
  9545. */
  9546. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9547. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9548. if (queryKey) {
  9549. const r = syncTreeParseQueryKey_(queryKey);
  9550. const queryPath = r.path, queryId = r.queryId;
  9551. const relativePath = newRelativePath(queryPath, path);
  9552. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9553. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9554. }
  9555. else {
  9556. // We've already removed the query. No big deal, ignore the update
  9557. return [];
  9558. }
  9559. }
  9560. /**
  9561. * Remove event callback(s).
  9562. *
  9563. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9564. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9565. *
  9566. * @param eventRegistration - If null, all callbacks are removed.
  9567. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9568. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9569. * deduping needs to take place. This flag allows toggling of that behavior
  9570. * @returns Cancel events, if cancelError was provided.
  9571. */
  9572. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9573. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9574. const path = query._path;
  9575. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9576. let cancelEvents = [];
  9577. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9578. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9579. // not loadsAllData().
  9580. if (maybeSyncPoint &&
  9581. (query._queryIdentifier === 'default' ||
  9582. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9583. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9584. if (syncPointIsEmpty(maybeSyncPoint)) {
  9585. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9586. }
  9587. const removed = removedAndEvents.removed;
  9588. cancelEvents = removedAndEvents.events;
  9589. if (!skipListenerDedup) {
  9590. /**
  9591. * We may have just removed one of many listeners and can short-circuit this whole process
  9592. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9593. * properly set up.
  9594. */
  9595. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9596. // queryId === 'default'
  9597. const removingDefault = -1 !==
  9598. removed.findIndex(query => {
  9599. return query._queryParams.loadsAllData();
  9600. });
  9601. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9602. if (removingDefault && !covered) {
  9603. const subtree = syncTree.syncPointTree_.subtree(path);
  9604. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9605. // removal
  9606. if (!subtree.isEmpty()) {
  9607. // We need to fold over our subtree and collect the listeners to send
  9608. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9609. // Ok, we've collected all the listens we need. Set them up.
  9610. for (let i = 0; i < newViews.length; ++i) {
  9611. const view = newViews[i], newQuery = view.query;
  9612. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9613. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9614. }
  9615. }
  9616. // Otherwise there's nothing below us, so nothing we need to start listening on
  9617. }
  9618. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9619. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9620. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9621. if (!covered && removed.length > 0 && !cancelError) {
  9622. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9623. // default. Otherwise, we need to iterate through and cancel each individual query
  9624. if (removingDefault) {
  9625. // We don't tag default listeners
  9626. const defaultTag = null;
  9627. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9628. }
  9629. else {
  9630. removed.forEach((queryToRemove) => {
  9631. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9632. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9633. });
  9634. }
  9635. }
  9636. }
  9637. // Now, clear all of the tags we're tracking for the removed listens
  9638. syncTreeRemoveTags_(syncTree, removed);
  9639. }
  9640. return cancelEvents;
  9641. }
  9642. /**
  9643. * Apply new server data for the specified tagged query.
  9644. *
  9645. * @returns Events to raise.
  9646. */
  9647. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9648. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9649. if (queryKey != null) {
  9650. const r = syncTreeParseQueryKey_(queryKey);
  9651. const queryPath = r.path, queryId = r.queryId;
  9652. const relativePath = newRelativePath(queryPath, path);
  9653. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9654. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9655. }
  9656. else {
  9657. // Query must have been removed already
  9658. return [];
  9659. }
  9660. }
  9661. /**
  9662. * Apply server data to be merged in for the specified tagged query.
  9663. *
  9664. * @returns Events to raise.
  9665. */
  9666. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9667. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9668. if (queryKey) {
  9669. const r = syncTreeParseQueryKey_(queryKey);
  9670. const queryPath = r.path, queryId = r.queryId;
  9671. const relativePath = newRelativePath(queryPath, path);
  9672. const changeTree = ImmutableTree.fromObject(changedChildren);
  9673. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9674. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9675. }
  9676. else {
  9677. // We've already removed the query. No big deal, ignore the update
  9678. return [];
  9679. }
  9680. }
  9681. /**
  9682. * Add an event callback for the specified query.
  9683. *
  9684. * @returns Events to raise.
  9685. */
  9686. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9687. const path = query._path;
  9688. let serverCache = null;
  9689. let foundAncestorDefaultView = false;
  9690. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9691. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9692. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9693. const relativePath = newRelativePath(pathToSyncPoint, path);
  9694. serverCache =
  9695. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9696. foundAncestorDefaultView =
  9697. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9698. });
  9699. let syncPoint = syncTree.syncPointTree_.get(path);
  9700. if (!syncPoint) {
  9701. syncPoint = new SyncPoint();
  9702. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9703. }
  9704. else {
  9705. foundAncestorDefaultView =
  9706. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9707. serverCache =
  9708. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9709. }
  9710. let serverCacheComplete;
  9711. if (serverCache != null) {
  9712. serverCacheComplete = true;
  9713. }
  9714. else {
  9715. serverCacheComplete = false;
  9716. serverCache = ChildrenNode.EMPTY_NODE;
  9717. const subtree = syncTree.syncPointTree_.subtree(path);
  9718. subtree.foreachChild((childName, childSyncPoint) => {
  9719. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9720. if (completeCache) {
  9721. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9722. }
  9723. });
  9724. }
  9725. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9726. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9727. // We need to track a tag for this query
  9728. const queryKey = syncTreeMakeQueryKey_(query);
  9729. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9730. const tag = syncTreeGetNextQueryTag_();
  9731. syncTree.queryToTagMap.set(queryKey, tag);
  9732. syncTree.tagToQueryMap.set(tag, queryKey);
  9733. }
  9734. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9735. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9736. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9737. const view = syncPointViewForQuery(syncPoint, query);
  9738. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9739. }
  9740. return events;
  9741. }
  9742. /**
  9743. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9744. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9745. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9746. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9747. *
  9748. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9749. *
  9750. * @param path - The path to the data we want
  9751. * @param writeIdsToExclude - A specific set to be excluded
  9752. */
  9753. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9754. const includeHiddenSets = true;
  9755. const writeTree = syncTree.pendingWriteTree_;
  9756. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9757. const relativePath = newRelativePath(pathSoFar, path);
  9758. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9759. if (serverCache) {
  9760. return serverCache;
  9761. }
  9762. });
  9763. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9764. }
  9765. function syncTreeGetServerValue(syncTree, query) {
  9766. const path = query._path;
  9767. let serverCache = null;
  9768. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9769. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9770. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9771. const relativePath = newRelativePath(pathToSyncPoint, path);
  9772. serverCache =
  9773. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9774. });
  9775. let syncPoint = syncTree.syncPointTree_.get(path);
  9776. if (!syncPoint) {
  9777. syncPoint = new SyncPoint();
  9778. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9779. }
  9780. else {
  9781. serverCache =
  9782. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9783. }
  9784. const serverCacheComplete = serverCache != null;
  9785. const serverCacheNode = serverCacheComplete
  9786. ? new CacheNode(serverCache, true, false)
  9787. : null;
  9788. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9789. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9790. return viewGetCompleteNode(view);
  9791. }
  9792. /**
  9793. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9794. *
  9795. * NOTES:
  9796. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9797. *
  9798. * - We call applyOperation() on each SyncPoint passing three things:
  9799. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9800. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9801. * 3. A snapshot Node with cached server data, if we have it.
  9802. *
  9803. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9804. */
  9805. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9806. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9807. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9808. }
  9809. /**
  9810. * Recursive helper for applyOperationToSyncPoints_
  9811. */
  9812. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9813. if (pathIsEmpty(operation.path)) {
  9814. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9815. }
  9816. else {
  9817. const syncPoint = syncPointTree.get(newEmptyPath());
  9818. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9819. if (serverCache == null && syncPoint != null) {
  9820. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9821. }
  9822. let events = [];
  9823. const childName = pathGetFront(operation.path);
  9824. const childOperation = operation.operationForChild(childName);
  9825. const childTree = syncPointTree.children.get(childName);
  9826. if (childTree && childOperation) {
  9827. const childServerCache = serverCache
  9828. ? serverCache.getImmediateChild(childName)
  9829. : null;
  9830. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9831. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9832. }
  9833. if (syncPoint) {
  9834. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9835. }
  9836. return events;
  9837. }
  9838. }
  9839. /**
  9840. * Recursive helper for applyOperationToSyncPoints_
  9841. */
  9842. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9843. const syncPoint = syncPointTree.get(newEmptyPath());
  9844. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9845. if (serverCache == null && syncPoint != null) {
  9846. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9847. }
  9848. let events = [];
  9849. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9850. const childServerCache = serverCache
  9851. ? serverCache.getImmediateChild(childName)
  9852. : null;
  9853. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9854. const childOperation = operation.operationForChild(childName);
  9855. if (childOperation) {
  9856. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9857. }
  9858. });
  9859. if (syncPoint) {
  9860. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9861. }
  9862. return events;
  9863. }
  9864. function syncTreeCreateListenerForView_(syncTree, view) {
  9865. const query = view.query;
  9866. const tag = syncTreeTagForQuery(syncTree, query);
  9867. return {
  9868. hashFn: () => {
  9869. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9870. return cache.hash();
  9871. },
  9872. onComplete: (status) => {
  9873. if (status === 'ok') {
  9874. if (tag) {
  9875. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9876. }
  9877. else {
  9878. return syncTreeApplyListenComplete(syncTree, query._path);
  9879. }
  9880. }
  9881. else {
  9882. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9883. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9884. const error = errorForServerCode(status, query);
  9885. return syncTreeRemoveEventRegistration(syncTree, query,
  9886. /*eventRegistration*/ null, error);
  9887. }
  9888. }
  9889. };
  9890. }
  9891. /**
  9892. * Return the tag associated with the given query.
  9893. */
  9894. function syncTreeTagForQuery(syncTree, query) {
  9895. const queryKey = syncTreeMakeQueryKey_(query);
  9896. return syncTree.queryToTagMap.get(queryKey);
  9897. }
  9898. /**
  9899. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9900. */
  9901. function syncTreeMakeQueryKey_(query) {
  9902. return query._path.toString() + '$' + query._queryIdentifier;
  9903. }
  9904. /**
  9905. * Return the query associated with the given tag, if we have one
  9906. */
  9907. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9908. return syncTree.tagToQueryMap.get(tag);
  9909. }
  9910. /**
  9911. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9912. */
  9913. function syncTreeParseQueryKey_(queryKey) {
  9914. const splitIndex = queryKey.indexOf('$');
  9915. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9916. return {
  9917. queryId: queryKey.substr(splitIndex + 1),
  9918. path: new Path(queryKey.substr(0, splitIndex))
  9919. };
  9920. }
  9921. /**
  9922. * A helper method to apply tagged operations
  9923. */
  9924. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9925. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9926. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9927. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9928. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9929. }
  9930. /**
  9931. * This collapses multiple unfiltered views into a single view, since we only need a single
  9932. * listener for them.
  9933. */
  9934. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9935. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9936. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9937. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9938. return [completeView];
  9939. }
  9940. else {
  9941. // No complete view here, flatten any deeper listens into an array
  9942. let views = [];
  9943. if (maybeChildSyncPoint) {
  9944. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9945. }
  9946. each(childMap, (_key, childViews) => {
  9947. views = views.concat(childViews);
  9948. });
  9949. return views;
  9950. }
  9951. });
  9952. }
  9953. /**
  9954. * Normalizes a query to a query we send the server for listening
  9955. *
  9956. * @returns The normalized query
  9957. */
  9958. function syncTreeQueryForListening_(query) {
  9959. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9960. // We treat queries that load all data as default queries
  9961. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9962. // from Query
  9963. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9964. }
  9965. else {
  9966. return query;
  9967. }
  9968. }
  9969. function syncTreeRemoveTags_(syncTree, queries) {
  9970. for (let j = 0; j < queries.length; ++j) {
  9971. const removedQuery = queries[j];
  9972. if (!removedQuery._queryParams.loadsAllData()) {
  9973. // We should have a tag for this
  9974. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9975. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9976. syncTree.queryToTagMap.delete(removedQueryKey);
  9977. syncTree.tagToQueryMap.delete(removedQueryTag);
  9978. }
  9979. }
  9980. }
  9981. /**
  9982. * Static accessor for query tags.
  9983. */
  9984. function syncTreeGetNextQueryTag_() {
  9985. return syncTreeNextQueryTag_++;
  9986. }
  9987. /**
  9988. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9989. *
  9990. * @returns This method can return events to support synchronous data sources
  9991. */
  9992. function syncTreeSetupListener_(syncTree, query, view) {
  9993. const path = query._path;
  9994. const tag = syncTreeTagForQuery(syncTree, query);
  9995. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9996. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9997. const subtree = syncTree.syncPointTree_.subtree(path);
  9998. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  9999. // may need to shadow other listens as well.
  10000. if (tag) {
  10001. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10002. }
  10003. else {
  10004. // Shadow everything at or below this location, this is a default listener.
  10005. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10006. if (!pathIsEmpty(relativePath) &&
  10007. maybeChildSyncPoint &&
  10008. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10009. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10010. }
  10011. else {
  10012. // No default listener here, flatten any deeper queries into an array
  10013. let queries = [];
  10014. if (maybeChildSyncPoint) {
  10015. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10016. }
  10017. each(childMap, (_key, childQueries) => {
  10018. queries = queries.concat(childQueries);
  10019. });
  10020. return queries;
  10021. }
  10022. });
  10023. for (let i = 0; i < queriesToStop.length; ++i) {
  10024. const queryToStop = queriesToStop[i];
  10025. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10026. }
  10027. }
  10028. return events;
  10029. }
  10030. /**
  10031. * @license
  10032. * Copyright 2017 Google LLC
  10033. *
  10034. * Licensed under the Apache License, Version 2.0 (the "License");
  10035. * you may not use this file except in compliance with the License.
  10036. * You may obtain a copy of the License at
  10037. *
  10038. * http://www.apache.org/licenses/LICENSE-2.0
  10039. *
  10040. * Unless required by applicable law or agreed to in writing, software
  10041. * distributed under the License is distributed on an "AS IS" BASIS,
  10042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10043. * See the License for the specific language governing permissions and
  10044. * limitations under the License.
  10045. */
  10046. class ExistingValueProvider {
  10047. constructor(node_) {
  10048. this.node_ = node_;
  10049. }
  10050. getImmediateChild(childName) {
  10051. const child = this.node_.getImmediateChild(childName);
  10052. return new ExistingValueProvider(child);
  10053. }
  10054. node() {
  10055. return this.node_;
  10056. }
  10057. }
  10058. class DeferredValueProvider {
  10059. constructor(syncTree, path) {
  10060. this.syncTree_ = syncTree;
  10061. this.path_ = path;
  10062. }
  10063. getImmediateChild(childName) {
  10064. const childPath = pathChild(this.path_, childName);
  10065. return new DeferredValueProvider(this.syncTree_, childPath);
  10066. }
  10067. node() {
  10068. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10069. }
  10070. }
  10071. /**
  10072. * Generate placeholders for deferred values.
  10073. */
  10074. const generateWithValues = function (values) {
  10075. values = values || {};
  10076. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10077. return values;
  10078. };
  10079. /**
  10080. * Value to use when firing local events. When writing server values, fire
  10081. * local events with an approximate value, otherwise return value as-is.
  10082. */
  10083. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10084. if (!value || typeof value !== 'object') {
  10085. return value;
  10086. }
  10087. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10088. if (typeof value['.sv'] === 'string') {
  10089. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10090. }
  10091. else if (typeof value['.sv'] === 'object') {
  10092. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10093. }
  10094. else {
  10095. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10096. }
  10097. };
  10098. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10099. switch (op) {
  10100. case 'timestamp':
  10101. return serverValues['timestamp'];
  10102. default:
  10103. util.assert(false, 'Unexpected server value: ' + op);
  10104. }
  10105. };
  10106. const resolveComplexDeferredValue = function (op, existing, unused) {
  10107. if (!op.hasOwnProperty('increment')) {
  10108. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10109. }
  10110. const delta = op['increment'];
  10111. if (typeof delta !== 'number') {
  10112. util.assert(false, 'Unexpected increment value: ' + delta);
  10113. }
  10114. const existingNode = existing.node();
  10115. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10116. // Incrementing a non-number sets the value to the incremented amount
  10117. if (!existingNode.isLeafNode()) {
  10118. return delta;
  10119. }
  10120. const leaf = existingNode;
  10121. const existingVal = leaf.getValue();
  10122. if (typeof existingVal !== 'number') {
  10123. return delta;
  10124. }
  10125. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10126. return existingVal + delta;
  10127. };
  10128. /**
  10129. * Recursively replace all deferred values and priorities in the tree with the
  10130. * specified generated replacement values.
  10131. * @param path - path to which write is relative
  10132. * @param node - new data written at path
  10133. * @param syncTree - current data
  10134. */
  10135. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10136. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10137. };
  10138. /**
  10139. * Recursively replace all deferred values and priorities in the node with the
  10140. * specified generated replacement values. If there are no server values in the node,
  10141. * it'll be returned as-is.
  10142. */
  10143. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10144. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10145. };
  10146. function resolveDeferredValue(node, existingVal, serverValues) {
  10147. const rawPri = node.getPriority().val();
  10148. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10149. let newNode;
  10150. if (node.isLeafNode()) {
  10151. const leafNode = node;
  10152. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10153. if (value !== leafNode.getValue() ||
  10154. priority !== leafNode.getPriority().val()) {
  10155. return new LeafNode(value, nodeFromJSON(priority));
  10156. }
  10157. else {
  10158. return node;
  10159. }
  10160. }
  10161. else {
  10162. const childrenNode = node;
  10163. newNode = childrenNode;
  10164. if (priority !== childrenNode.getPriority().val()) {
  10165. newNode = newNode.updatePriority(new LeafNode(priority));
  10166. }
  10167. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10168. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10169. if (newChildNode !== childNode) {
  10170. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10171. }
  10172. });
  10173. return newNode;
  10174. }
  10175. }
  10176. /**
  10177. * @license
  10178. * Copyright 2017 Google LLC
  10179. *
  10180. * Licensed under the Apache License, Version 2.0 (the "License");
  10181. * you may not use this file except in compliance with the License.
  10182. * You may obtain a copy of the License at
  10183. *
  10184. * http://www.apache.org/licenses/LICENSE-2.0
  10185. *
  10186. * Unless required by applicable law or agreed to in writing, software
  10187. * distributed under the License is distributed on an "AS IS" BASIS,
  10188. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10189. * See the License for the specific language governing permissions and
  10190. * limitations under the License.
  10191. */
  10192. /**
  10193. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10194. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10195. * children.
  10196. */
  10197. class Tree {
  10198. /**
  10199. * @param name - Optional name of the node.
  10200. * @param parent - Optional parent node.
  10201. * @param node - Optional node to wrap.
  10202. */
  10203. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10204. this.name = name;
  10205. this.parent = parent;
  10206. this.node = node;
  10207. }
  10208. }
  10209. /**
  10210. * Returns a sub-Tree for the given path.
  10211. *
  10212. * @param pathObj - Path to look up.
  10213. * @returns Tree for path.
  10214. */
  10215. function treeSubTree(tree, pathObj) {
  10216. // TODO: Require pathObj to be Path?
  10217. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10218. let child = tree, next = pathGetFront(path);
  10219. while (next !== null) {
  10220. const childNode = util.safeGet(child.node.children, next) || {
  10221. children: {},
  10222. childCount: 0
  10223. };
  10224. child = new Tree(next, child, childNode);
  10225. path = pathPopFront(path);
  10226. next = pathGetFront(path);
  10227. }
  10228. return child;
  10229. }
  10230. /**
  10231. * Returns the data associated with this tree node.
  10232. *
  10233. * @returns The data or null if no data exists.
  10234. */
  10235. function treeGetValue(tree) {
  10236. return tree.node.value;
  10237. }
  10238. /**
  10239. * Sets data to this tree node.
  10240. *
  10241. * @param value - Value to set.
  10242. */
  10243. function treeSetValue(tree, value) {
  10244. tree.node.value = value;
  10245. treeUpdateParents(tree);
  10246. }
  10247. /**
  10248. * @returns Whether the tree has any children.
  10249. */
  10250. function treeHasChildren(tree) {
  10251. return tree.node.childCount > 0;
  10252. }
  10253. /**
  10254. * @returns Whether the tree is empty (no value or children).
  10255. */
  10256. function treeIsEmpty(tree) {
  10257. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10258. }
  10259. /**
  10260. * Calls action for each child of this tree node.
  10261. *
  10262. * @param action - Action to be called for each child.
  10263. */
  10264. function treeForEachChild(tree, action) {
  10265. each(tree.node.children, (child, childTree) => {
  10266. action(new Tree(child, tree, childTree));
  10267. });
  10268. }
  10269. /**
  10270. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10271. *
  10272. * @param action - Action to be called for each child.
  10273. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10274. * false.
  10275. * @param childrenFirst - Whether to call action on children before calling it on
  10276. * parent.
  10277. */
  10278. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10279. if (includeSelf && !childrenFirst) {
  10280. action(tree);
  10281. }
  10282. treeForEachChild(tree, child => {
  10283. treeForEachDescendant(child, action, true, childrenFirst);
  10284. });
  10285. if (includeSelf && childrenFirst) {
  10286. action(tree);
  10287. }
  10288. }
  10289. /**
  10290. * Calls action on each ancestor node.
  10291. *
  10292. * @param action - Action to be called on each parent; return
  10293. * true to abort.
  10294. * @param includeSelf - Whether to call action on this node as well.
  10295. * @returns true if the action callback returned true.
  10296. */
  10297. function treeForEachAncestor(tree, action, includeSelf) {
  10298. let node = includeSelf ? tree : tree.parent;
  10299. while (node !== null) {
  10300. if (action(node)) {
  10301. return true;
  10302. }
  10303. node = node.parent;
  10304. }
  10305. return false;
  10306. }
  10307. /**
  10308. * @returns The path of this tree node, as a Path.
  10309. */
  10310. function treeGetPath(tree) {
  10311. return new Path(tree.parent === null
  10312. ? tree.name
  10313. : treeGetPath(tree.parent) + '/' + tree.name);
  10314. }
  10315. /**
  10316. * Adds or removes this child from its parent based on whether it's empty or not.
  10317. */
  10318. function treeUpdateParents(tree) {
  10319. if (tree.parent !== null) {
  10320. treeUpdateChild(tree.parent, tree.name, tree);
  10321. }
  10322. }
  10323. /**
  10324. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10325. *
  10326. * @param childName - The name of the child to update.
  10327. * @param child - The child to update.
  10328. */
  10329. function treeUpdateChild(tree, childName, child) {
  10330. const childEmpty = treeIsEmpty(child);
  10331. const childExists = util.contains(tree.node.children, childName);
  10332. if (childEmpty && childExists) {
  10333. delete tree.node.children[childName];
  10334. tree.node.childCount--;
  10335. treeUpdateParents(tree);
  10336. }
  10337. else if (!childEmpty && !childExists) {
  10338. tree.node.children[childName] = child.node;
  10339. tree.node.childCount++;
  10340. treeUpdateParents(tree);
  10341. }
  10342. }
  10343. /**
  10344. * @license
  10345. * Copyright 2017 Google LLC
  10346. *
  10347. * Licensed under the Apache License, Version 2.0 (the "License");
  10348. * you may not use this file except in compliance with the License.
  10349. * You may obtain a copy of the License at
  10350. *
  10351. * http://www.apache.org/licenses/LICENSE-2.0
  10352. *
  10353. * Unless required by applicable law or agreed to in writing, software
  10354. * distributed under the License is distributed on an "AS IS" BASIS,
  10355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10356. * See the License for the specific language governing permissions and
  10357. * limitations under the License.
  10358. */
  10359. /**
  10360. * True for invalid Firebase keys
  10361. */
  10362. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10363. /**
  10364. * True for invalid Firebase paths.
  10365. * Allows '/' in paths.
  10366. */
  10367. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10368. /**
  10369. * Maximum number of characters to allow in leaf value
  10370. */
  10371. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10372. const isValidKey = function (key) {
  10373. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10374. };
  10375. const isValidPathString = function (pathString) {
  10376. return (typeof pathString === 'string' &&
  10377. pathString.length !== 0 &&
  10378. !INVALID_PATH_REGEX_.test(pathString));
  10379. };
  10380. const isValidRootPathString = function (pathString) {
  10381. if (pathString) {
  10382. // Allow '/.info/' at the beginning.
  10383. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10384. }
  10385. return isValidPathString(pathString);
  10386. };
  10387. const isValidPriority = function (priority) {
  10388. return (priority === null ||
  10389. typeof priority === 'string' ||
  10390. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10391. (priority &&
  10392. typeof priority === 'object' &&
  10393. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10394. util.contains(priority, '.sv')));
  10395. };
  10396. /**
  10397. * Pre-validate a datum passed as an argument to Firebase function.
  10398. */
  10399. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10400. if (optional && value === undefined) {
  10401. return;
  10402. }
  10403. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10404. };
  10405. /**
  10406. * Validate a data object client-side before sending to server.
  10407. */
  10408. const validateFirebaseData = function (errorPrefix, data, path_) {
  10409. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10410. if (data === undefined) {
  10411. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10412. }
  10413. if (typeof data === 'function') {
  10414. throw new Error(errorPrefix +
  10415. 'contains a function ' +
  10416. validationPathToErrorString(path) +
  10417. ' with contents = ' +
  10418. data.toString());
  10419. }
  10420. if (isInvalidJSONNumber(data)) {
  10421. throw new Error(errorPrefix +
  10422. 'contains ' +
  10423. data.toString() +
  10424. ' ' +
  10425. validationPathToErrorString(path));
  10426. }
  10427. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10428. if (typeof data === 'string' &&
  10429. data.length > MAX_LEAF_SIZE_ / 3 &&
  10430. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10431. throw new Error(errorPrefix +
  10432. 'contains a string greater than ' +
  10433. MAX_LEAF_SIZE_ +
  10434. ' utf8 bytes ' +
  10435. validationPathToErrorString(path) +
  10436. " ('" +
  10437. data.substring(0, 50) +
  10438. "...')");
  10439. }
  10440. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10441. // to save extra walking of large objects.
  10442. if (data && typeof data === 'object') {
  10443. let hasDotValue = false;
  10444. let hasActualChild = false;
  10445. each(data, (key, value) => {
  10446. if (key === '.value') {
  10447. hasDotValue = true;
  10448. }
  10449. else if (key !== '.priority' && key !== '.sv') {
  10450. hasActualChild = true;
  10451. if (!isValidKey(key)) {
  10452. throw new Error(errorPrefix +
  10453. ' contains an invalid key (' +
  10454. key +
  10455. ') ' +
  10456. validationPathToErrorString(path) +
  10457. '. Keys must be non-empty strings ' +
  10458. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10459. }
  10460. }
  10461. validationPathPush(path, key);
  10462. validateFirebaseData(errorPrefix, value, path);
  10463. validationPathPop(path);
  10464. });
  10465. if (hasDotValue && hasActualChild) {
  10466. throw new Error(errorPrefix +
  10467. ' contains ".value" child ' +
  10468. validationPathToErrorString(path) +
  10469. ' in addition to actual children.');
  10470. }
  10471. }
  10472. };
  10473. /**
  10474. * Pre-validate paths passed in the firebase function.
  10475. */
  10476. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10477. let i, curPath;
  10478. for (i = 0; i < mergePaths.length; i++) {
  10479. curPath = mergePaths[i];
  10480. const keys = pathSlice(curPath);
  10481. for (let j = 0; j < keys.length; j++) {
  10482. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10483. else if (!isValidKey(keys[j])) {
  10484. throw new Error(errorPrefix +
  10485. 'contains an invalid key (' +
  10486. keys[j] +
  10487. ') in path ' +
  10488. curPath.toString() +
  10489. '. Keys must be non-empty strings ' +
  10490. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10491. }
  10492. }
  10493. }
  10494. // Check that update keys are not descendants of each other.
  10495. // We rely on the property that sorting guarantees that ancestors come
  10496. // right before descendants.
  10497. mergePaths.sort(pathCompare);
  10498. let prevPath = null;
  10499. for (i = 0; i < mergePaths.length; i++) {
  10500. curPath = mergePaths[i];
  10501. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10502. throw new Error(errorPrefix +
  10503. 'contains a path ' +
  10504. prevPath.toString() +
  10505. ' that is ancestor of another path ' +
  10506. curPath.toString());
  10507. }
  10508. prevPath = curPath;
  10509. }
  10510. };
  10511. /**
  10512. * pre-validate an object passed as an argument to firebase function (
  10513. * must be an object - e.g. for firebase.update()).
  10514. */
  10515. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10516. if (optional && data === undefined) {
  10517. return;
  10518. }
  10519. const errorPrefix = util.errorPrefix(fnName, 'values');
  10520. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10521. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10522. }
  10523. const mergePaths = [];
  10524. each(data, (key, value) => {
  10525. const curPath = new Path(key);
  10526. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10527. if (pathGetBack(curPath) === '.priority') {
  10528. if (!isValidPriority(value)) {
  10529. throw new Error(errorPrefix +
  10530. "contains an invalid value for '" +
  10531. curPath.toString() +
  10532. "', which must be a valid " +
  10533. 'Firebase priority (a string, finite number, server value, or null).');
  10534. }
  10535. }
  10536. mergePaths.push(curPath);
  10537. });
  10538. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10539. };
  10540. const validatePriority = function (fnName, priority, optional) {
  10541. if (optional && priority === undefined) {
  10542. return;
  10543. }
  10544. if (isInvalidJSONNumber(priority)) {
  10545. throw new Error(util.errorPrefix(fnName, 'priority') +
  10546. 'is ' +
  10547. priority.toString() +
  10548. ', but must be a valid Firebase priority (a string, finite number, ' +
  10549. 'server value, or null).');
  10550. }
  10551. // Special case to allow importing data with a .sv.
  10552. if (!isValidPriority(priority)) {
  10553. throw new Error(util.errorPrefix(fnName, 'priority') +
  10554. 'must be a valid Firebase priority ' +
  10555. '(a string, finite number, server value, or null).');
  10556. }
  10557. };
  10558. const validateKey = function (fnName, argumentName, key, optional) {
  10559. if (optional && key === undefined) {
  10560. return;
  10561. }
  10562. if (!isValidKey(key)) {
  10563. throw new Error(util.errorPrefix(fnName, argumentName) +
  10564. 'was an invalid key = "' +
  10565. key +
  10566. '". Firebase keys must be non-empty strings and ' +
  10567. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10568. }
  10569. };
  10570. /**
  10571. * @internal
  10572. */
  10573. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10574. if (optional && pathString === undefined) {
  10575. return;
  10576. }
  10577. if (!isValidPathString(pathString)) {
  10578. throw new Error(util.errorPrefix(fnName, argumentName) +
  10579. 'was an invalid path = "' +
  10580. pathString +
  10581. '". Paths must be non-empty strings and ' +
  10582. 'can\'t contain ".", "#", "$", "[", or "]"');
  10583. }
  10584. };
  10585. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10586. if (pathString) {
  10587. // Allow '/.info/' at the beginning.
  10588. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10589. }
  10590. validatePathString(fnName, argumentName, pathString, optional);
  10591. };
  10592. /**
  10593. * @internal
  10594. */
  10595. const validateWritablePath = function (fnName, path) {
  10596. if (pathGetFront(path) === '.info') {
  10597. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10598. }
  10599. };
  10600. const validateUrl = function (fnName, parsedUrl) {
  10601. // TODO = Validate server better.
  10602. const pathString = parsedUrl.path.toString();
  10603. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10604. parsedUrl.repoInfo.host.length === 0 ||
  10605. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10606. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10607. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10608. throw new Error(util.errorPrefix(fnName, 'url') +
  10609. 'must be a valid firebase URL and ' +
  10610. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10611. }
  10612. };
  10613. /**
  10614. * @license
  10615. * Copyright 2017 Google LLC
  10616. *
  10617. * Licensed under the Apache License, Version 2.0 (the "License");
  10618. * you may not use this file except in compliance with the License.
  10619. * You may obtain a copy of the License at
  10620. *
  10621. * http://www.apache.org/licenses/LICENSE-2.0
  10622. *
  10623. * Unless required by applicable law or agreed to in writing, software
  10624. * distributed under the License is distributed on an "AS IS" BASIS,
  10625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10626. * See the License for the specific language governing permissions and
  10627. * limitations under the License.
  10628. */
  10629. /**
  10630. * The event queue serves a few purposes:
  10631. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10632. * events being queued.
  10633. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10634. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10635. * left off, ensuring that the events are still raised synchronously and in order.
  10636. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10637. * events are raised synchronously.
  10638. *
  10639. * NOTE: This can all go away if/when we move to async events.
  10640. *
  10641. */
  10642. class EventQueue {
  10643. constructor() {
  10644. this.eventLists_ = [];
  10645. /**
  10646. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10647. */
  10648. this.recursionDepth_ = 0;
  10649. }
  10650. }
  10651. /**
  10652. * @param eventDataList - The new events to queue.
  10653. */
  10654. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10655. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10656. let currList = null;
  10657. for (let i = 0; i < eventDataList.length; i++) {
  10658. const data = eventDataList[i];
  10659. const path = data.getPath();
  10660. if (currList !== null && !pathEquals(path, currList.path)) {
  10661. eventQueue.eventLists_.push(currList);
  10662. currList = null;
  10663. }
  10664. if (currList === null) {
  10665. currList = { events: [], path };
  10666. }
  10667. currList.events.push(data);
  10668. }
  10669. if (currList) {
  10670. eventQueue.eventLists_.push(currList);
  10671. }
  10672. }
  10673. /**
  10674. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10675. * for the specified path.
  10676. *
  10677. * It is assumed that the new events are all for the specified path.
  10678. *
  10679. * @param path - The path to raise events for.
  10680. * @param eventDataList - The new events to raise.
  10681. */
  10682. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10683. eventQueueQueueEvents(eventQueue, eventDataList);
  10684. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10685. }
  10686. /**
  10687. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10688. * locations related to the specified change path (i.e. all ancestors and descendants).
  10689. *
  10690. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10691. *
  10692. * @param changedPath - The path to raise events for.
  10693. * @param eventDataList - The events to raise
  10694. */
  10695. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10696. eventQueueQueueEvents(eventQueue, eventDataList);
  10697. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10698. pathContains(changedPath, eventPath));
  10699. }
  10700. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10701. eventQueue.recursionDepth_++;
  10702. let sentAll = true;
  10703. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10704. const eventList = eventQueue.eventLists_[i];
  10705. if (eventList) {
  10706. const eventPath = eventList.path;
  10707. if (predicate(eventPath)) {
  10708. eventListRaise(eventQueue.eventLists_[i]);
  10709. eventQueue.eventLists_[i] = null;
  10710. }
  10711. else {
  10712. sentAll = false;
  10713. }
  10714. }
  10715. }
  10716. if (sentAll) {
  10717. eventQueue.eventLists_ = [];
  10718. }
  10719. eventQueue.recursionDepth_--;
  10720. }
  10721. /**
  10722. * Iterates through the list and raises each event
  10723. */
  10724. function eventListRaise(eventList) {
  10725. for (let i = 0; i < eventList.events.length; i++) {
  10726. const eventData = eventList.events[i];
  10727. if (eventData !== null) {
  10728. eventList.events[i] = null;
  10729. const eventFn = eventData.getEventRunner();
  10730. if (logger) {
  10731. log('event: ' + eventData.toString());
  10732. }
  10733. exceptionGuard(eventFn);
  10734. }
  10735. }
  10736. }
  10737. /**
  10738. * @license
  10739. * Copyright 2017 Google LLC
  10740. *
  10741. * Licensed under the Apache License, Version 2.0 (the "License");
  10742. * you may not use this file except in compliance with the License.
  10743. * You may obtain a copy of the License at
  10744. *
  10745. * http://www.apache.org/licenses/LICENSE-2.0
  10746. *
  10747. * Unless required by applicable law or agreed to in writing, software
  10748. * distributed under the License is distributed on an "AS IS" BASIS,
  10749. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10750. * See the License for the specific language governing permissions and
  10751. * limitations under the License.
  10752. */
  10753. const INTERRUPT_REASON = 'repo_interrupt';
  10754. /**
  10755. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10756. * things this ensure that if there's ever a bug causing a mismatch between
  10757. * client / server hashes for some data, we won't retry indefinitely.
  10758. */
  10759. const MAX_TRANSACTION_RETRIES = 25;
  10760. /**
  10761. * A connection to a single data repository.
  10762. */
  10763. class Repo {
  10764. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10765. this.repoInfo_ = repoInfo_;
  10766. this.forceRestClient_ = forceRestClient_;
  10767. this.authTokenProvider_ = authTokenProvider_;
  10768. this.appCheckProvider_ = appCheckProvider_;
  10769. this.dataUpdateCount = 0;
  10770. this.statsListener_ = null;
  10771. this.eventQueue_ = new EventQueue();
  10772. this.nextWriteId_ = 1;
  10773. this.interceptServerDataCallback_ = null;
  10774. /** A list of data pieces and paths to be set when this client disconnects. */
  10775. this.onDisconnect_ = newSparseSnapshotTree();
  10776. /** Stores queues of outstanding transactions for Firebase locations. */
  10777. this.transactionQueueTree_ = new Tree();
  10778. // TODO: This should be @private but it's used by test_access.js and internal.js
  10779. this.persistentConnection_ = null;
  10780. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10781. this.key = this.repoInfo_.toURLString();
  10782. }
  10783. /**
  10784. * @returns The URL corresponding to the root of this Firebase.
  10785. */
  10786. toString() {
  10787. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10788. }
  10789. }
  10790. function repoStart(repo, appId, authOverride) {
  10791. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10792. if (repo.forceRestClient_ || beingCrawled()) {
  10793. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10794. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10795. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10796. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10797. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10798. }
  10799. else {
  10800. // Validate authOverride
  10801. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10802. if (typeof authOverride !== 'object') {
  10803. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10804. }
  10805. try {
  10806. util.stringify(authOverride);
  10807. }
  10808. catch (e) {
  10809. throw new Error('Invalid authOverride provided: ' + e);
  10810. }
  10811. }
  10812. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10813. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10814. }, (connectStatus) => {
  10815. repoOnConnectStatus(repo, connectStatus);
  10816. }, (updates) => {
  10817. repoOnServerInfoUpdate(repo, updates);
  10818. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10819. repo.server_ = repo.persistentConnection_;
  10820. }
  10821. repo.authTokenProvider_.addTokenChangeListener(token => {
  10822. repo.server_.refreshAuthToken(token);
  10823. });
  10824. repo.appCheckProvider_.addTokenChangeListener(result => {
  10825. repo.server_.refreshAppCheckToken(result.token);
  10826. });
  10827. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10828. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10829. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10830. // Used for .info.
  10831. repo.infoData_ = new SnapshotHolder();
  10832. repo.infoSyncTree_ = new SyncTree({
  10833. startListening: (query, tag, currentHashFn, onComplete) => {
  10834. let infoEvents = [];
  10835. const node = repo.infoData_.getNode(query._path);
  10836. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10837. // on initial data...
  10838. if (!node.isEmpty()) {
  10839. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10840. setTimeout(() => {
  10841. onComplete('ok');
  10842. }, 0);
  10843. }
  10844. return infoEvents;
  10845. },
  10846. stopListening: () => { }
  10847. });
  10848. repoUpdateInfo(repo, 'connected', false);
  10849. repo.serverSyncTree_ = new SyncTree({
  10850. startListening: (query, tag, currentHashFn, onComplete) => {
  10851. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10852. const events = onComplete(status, data);
  10853. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10854. });
  10855. // No synchronous events for network-backed sync trees
  10856. return [];
  10857. },
  10858. stopListening: (query, tag) => {
  10859. repo.server_.unlisten(query, tag);
  10860. }
  10861. });
  10862. }
  10863. /**
  10864. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10865. */
  10866. function repoServerTime(repo) {
  10867. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10868. const offset = offsetNode.val() || 0;
  10869. return new Date().getTime() + offset;
  10870. }
  10871. /**
  10872. * Generate ServerValues using some variables from the repo object.
  10873. */
  10874. function repoGenerateServerValues(repo) {
  10875. return generateWithValues({
  10876. timestamp: repoServerTime(repo)
  10877. });
  10878. }
  10879. /**
  10880. * Called by realtime when we get new messages from the server.
  10881. */
  10882. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10883. // For testing.
  10884. repo.dataUpdateCount++;
  10885. const path = new Path(pathString);
  10886. data = repo.interceptServerDataCallback_
  10887. ? repo.interceptServerDataCallback_(pathString, data)
  10888. : data;
  10889. let events = [];
  10890. if (tag) {
  10891. if (isMerge) {
  10892. const taggedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10893. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10894. }
  10895. else {
  10896. const taggedSnap = nodeFromJSON(data);
  10897. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10898. }
  10899. }
  10900. else if (isMerge) {
  10901. const changedChildren = util.map(data, (raw) => nodeFromJSON(raw));
  10902. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10903. }
  10904. else {
  10905. const snap = nodeFromJSON(data);
  10906. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10907. }
  10908. let affectedPath = path;
  10909. if (events.length > 0) {
  10910. // Since we have a listener outstanding for each transaction, receiving any events
  10911. // is a proxy for some change having occurred.
  10912. affectedPath = repoRerunTransactions(repo, path);
  10913. }
  10914. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10915. }
  10916. function repoOnConnectStatus(repo, connectStatus) {
  10917. repoUpdateInfo(repo, 'connected', connectStatus);
  10918. if (connectStatus === false) {
  10919. repoRunOnDisconnectEvents(repo);
  10920. }
  10921. }
  10922. function repoOnServerInfoUpdate(repo, updates) {
  10923. each(updates, (key, value) => {
  10924. repoUpdateInfo(repo, key, value);
  10925. });
  10926. }
  10927. function repoUpdateInfo(repo, pathString, value) {
  10928. const path = new Path('/.info/' + pathString);
  10929. const newNode = nodeFromJSON(value);
  10930. repo.infoData_.updateSnapshot(path, newNode);
  10931. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10932. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10933. }
  10934. function repoGetNextWriteId(repo) {
  10935. return repo.nextWriteId_++;
  10936. }
  10937. /**
  10938. * The purpose of `getValue` is to return the latest known value
  10939. * satisfying `query`.
  10940. *
  10941. * This method will first check for in-memory cached values
  10942. * belonging to active listeners. If they are found, such values
  10943. * are considered to be the most up-to-date.
  10944. *
  10945. * If the client is not connected, this method will wait until the
  10946. * repo has established a connection and then request the value for `query`.
  10947. * If the client is not able to retrieve the query result for another reason,
  10948. * it reports an error.
  10949. *
  10950. * @param query - The query to surface a value for.
  10951. */
  10952. function repoGetValue(repo, query, eventRegistration) {
  10953. // Only active queries are cached. There is no persisted cache.
  10954. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10955. if (cached != null) {
  10956. return Promise.resolve(cached);
  10957. }
  10958. return repo.server_.get(query).then(payload => {
  10959. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10960. /**
  10961. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10962. * Add an event registration,
  10963. * Update data at the path,
  10964. * Raise any events,
  10965. * Cleanup the SyncTree
  10966. */
  10967. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10968. let events;
  10969. if (query._queryParams.loadsAllData()) {
  10970. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10971. }
  10972. else {
  10973. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10974. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10975. }
  10976. /*
  10977. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10978. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10979. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10980. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10981. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10982. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10983. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10984. * ensure the corresponding child events will get fired.
  10985. */
  10986. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10987. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10988. return node;
  10989. }, err => {
  10990. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  10991. return Promise.reject(new Error(err));
  10992. });
  10993. }
  10994. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10995. repoLog(repo, 'set', {
  10996. path: path.toString(),
  10997. value: newVal,
  10998. priority: newPriority
  10999. });
  11000. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11001. // (b) store unresolved paths on JSON parse
  11002. const serverValues = repoGenerateServerValues(repo);
  11003. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11004. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11005. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11006. const writeId = repoGetNextWriteId(repo);
  11007. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11008. eventQueueQueueEvents(repo.eventQueue_, events);
  11009. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11010. const success = status === 'ok';
  11011. if (!success) {
  11012. warn('set at ' + path + ' failed: ' + status);
  11013. }
  11014. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11015. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11016. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11017. });
  11018. const affectedPath = repoAbortTransactions(repo, path);
  11019. repoRerunTransactions(repo, affectedPath);
  11020. // We queued the events above, so just flush the queue here
  11021. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11022. }
  11023. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11024. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11025. // Start with our existing data and merge each child into it.
  11026. let empty = true;
  11027. const serverValues = repoGenerateServerValues(repo);
  11028. const changedChildren = {};
  11029. each(childrenToMerge, (changedKey, changedValue) => {
  11030. empty = false;
  11031. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11032. });
  11033. if (!empty) {
  11034. const writeId = repoGetNextWriteId(repo);
  11035. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11036. eventQueueQueueEvents(repo.eventQueue_, events);
  11037. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11038. const success = status === 'ok';
  11039. if (!success) {
  11040. warn('update at ' + path + ' failed: ' + status);
  11041. }
  11042. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11043. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11044. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11045. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11046. });
  11047. each(childrenToMerge, (changedPath) => {
  11048. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11049. repoRerunTransactions(repo, affectedPath);
  11050. });
  11051. // We queued the events above, so just flush the queue here
  11052. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11053. }
  11054. else {
  11055. log("update() called with empty data. Don't do anything.");
  11056. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11057. }
  11058. }
  11059. /**
  11060. * Applies all of the changes stored up in the onDisconnect_ tree.
  11061. */
  11062. function repoRunOnDisconnectEvents(repo) {
  11063. repoLog(repo, 'onDisconnectEvents');
  11064. const serverValues = repoGenerateServerValues(repo);
  11065. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11066. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11067. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11068. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11069. });
  11070. let events = [];
  11071. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11072. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11073. const affectedPath = repoAbortTransactions(repo, path);
  11074. repoRerunTransactions(repo, affectedPath);
  11075. });
  11076. repo.onDisconnect_ = newSparseSnapshotTree();
  11077. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11078. }
  11079. function repoOnDisconnectCancel(repo, path, onComplete) {
  11080. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11081. if (status === 'ok') {
  11082. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11083. }
  11084. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11085. });
  11086. }
  11087. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11088. const newNode = nodeFromJSON(value);
  11089. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11090. if (status === 'ok') {
  11091. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11092. }
  11093. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11094. });
  11095. }
  11096. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11097. const newNode = nodeFromJSON(value, priority);
  11098. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11099. if (status === 'ok') {
  11100. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11101. }
  11102. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11103. });
  11104. }
  11105. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11106. if (util.isEmpty(childrenToMerge)) {
  11107. log("onDisconnect().update() called with empty data. Don't do anything.");
  11108. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11109. return;
  11110. }
  11111. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11112. if (status === 'ok') {
  11113. each(childrenToMerge, (childName, childNode) => {
  11114. const newChildNode = nodeFromJSON(childNode);
  11115. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11116. });
  11117. }
  11118. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11119. });
  11120. }
  11121. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11122. let events;
  11123. if (pathGetFront(query._path) === '.info') {
  11124. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11125. }
  11126. else {
  11127. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11128. }
  11129. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11130. }
  11131. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11132. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11133. // a little bit by handling the return values anyways.
  11134. let events;
  11135. if (pathGetFront(query._path) === '.info') {
  11136. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11137. }
  11138. else {
  11139. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11140. }
  11141. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11142. }
  11143. function repoInterrupt(repo) {
  11144. if (repo.persistentConnection_) {
  11145. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11146. }
  11147. }
  11148. function repoResume(repo) {
  11149. if (repo.persistentConnection_) {
  11150. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11151. }
  11152. }
  11153. function repoLog(repo, ...varArgs) {
  11154. let prefix = '';
  11155. if (repo.persistentConnection_) {
  11156. prefix = repo.persistentConnection_.id + ':';
  11157. }
  11158. log(prefix, ...varArgs);
  11159. }
  11160. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11161. if (callback) {
  11162. exceptionGuard(() => {
  11163. if (status === 'ok') {
  11164. callback(null);
  11165. }
  11166. else {
  11167. const code = (status || 'error').toUpperCase();
  11168. let message = code;
  11169. if (errorReason) {
  11170. message += ': ' + errorReason;
  11171. }
  11172. const error = new Error(message);
  11173. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11174. error.code = code;
  11175. callback(error);
  11176. }
  11177. });
  11178. }
  11179. }
  11180. /**
  11181. * Creates a new transaction, adds it to the transactions we're tracking, and
  11182. * sends it to the server if possible.
  11183. *
  11184. * @param path - Path at which to do transaction.
  11185. * @param transactionUpdate - Update callback.
  11186. * @param onComplete - Completion callback.
  11187. * @param unwatcher - Function that will be called when the transaction no longer
  11188. * need data updates for `path`.
  11189. * @param applyLocally - Whether or not to make intermediate results visible
  11190. */
  11191. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11192. repoLog(repo, 'transaction on ' + path);
  11193. // Initialize transaction.
  11194. const transaction = {
  11195. path,
  11196. update: transactionUpdate,
  11197. onComplete,
  11198. // One of TransactionStatus enums.
  11199. status: null,
  11200. // Used when combining transactions at different locations to figure out
  11201. // which one goes first.
  11202. order: LUIDGenerator(),
  11203. // Whether to raise local events for this transaction.
  11204. applyLocally,
  11205. // Count of how many times we've retried the transaction.
  11206. retryCount: 0,
  11207. // Function to call to clean up our .on() listener.
  11208. unwatcher,
  11209. // Stores why a transaction was aborted.
  11210. abortReason: null,
  11211. currentWriteId: null,
  11212. currentInputSnapshot: null,
  11213. currentOutputSnapshotRaw: null,
  11214. currentOutputSnapshotResolved: null
  11215. };
  11216. // Run transaction initially.
  11217. const currentState = repoGetLatestState(repo, path, undefined);
  11218. transaction.currentInputSnapshot = currentState;
  11219. const newVal = transaction.update(currentState.val());
  11220. if (newVal === undefined) {
  11221. // Abort transaction.
  11222. transaction.unwatcher();
  11223. transaction.currentOutputSnapshotRaw = null;
  11224. transaction.currentOutputSnapshotResolved = null;
  11225. if (transaction.onComplete) {
  11226. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11227. }
  11228. }
  11229. else {
  11230. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11231. // Mark as run and add to our queue.
  11232. transaction.status = 0 /* TransactionStatus.RUN */;
  11233. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11234. const nodeQueue = treeGetValue(queueNode) || [];
  11235. nodeQueue.push(transaction);
  11236. treeSetValue(queueNode, nodeQueue);
  11237. // Update visibleData and raise events
  11238. // Note: We intentionally raise events after updating all of our
  11239. // transaction state, since the user could start new transactions from the
  11240. // event callbacks.
  11241. let priorityForNode;
  11242. if (typeof newVal === 'object' &&
  11243. newVal !== null &&
  11244. util.contains(newVal, '.priority')) {
  11245. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11246. priorityForNode = util.safeGet(newVal, '.priority');
  11247. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11248. 'Priority must be a valid string, finite number, server value, or null.');
  11249. }
  11250. else {
  11251. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11252. ChildrenNode.EMPTY_NODE;
  11253. priorityForNode = currentNode.getPriority().val();
  11254. }
  11255. const serverValues = repoGenerateServerValues(repo);
  11256. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11257. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11258. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11259. transaction.currentOutputSnapshotResolved = newNode;
  11260. transaction.currentWriteId = repoGetNextWriteId(repo);
  11261. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11262. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11263. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11264. }
  11265. }
  11266. /**
  11267. * @param excludeSets - A specific set to exclude
  11268. */
  11269. function repoGetLatestState(repo, path, excludeSets) {
  11270. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11271. ChildrenNode.EMPTY_NODE);
  11272. }
  11273. /**
  11274. * Sends any already-run transactions that aren't waiting for outstanding
  11275. * transactions to complete.
  11276. *
  11277. * Externally it's called with no arguments, but it calls itself recursively
  11278. * with a particular transactionQueueTree node to recurse through the tree.
  11279. *
  11280. * @param node - transactionQueueTree node to start at.
  11281. */
  11282. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11283. // Before recursing, make sure any completed transactions are removed.
  11284. if (!node) {
  11285. repoPruneCompletedTransactionsBelowNode(repo, node);
  11286. }
  11287. if (treeGetValue(node)) {
  11288. const queue = repoBuildTransactionQueue(repo, node);
  11289. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11290. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11291. // If they're all run (and not sent), we can send them. Else, we must wait.
  11292. if (allRun) {
  11293. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11294. }
  11295. }
  11296. else if (treeHasChildren(node)) {
  11297. treeForEachChild(node, childNode => {
  11298. repoSendReadyTransactions(repo, childNode);
  11299. });
  11300. }
  11301. }
  11302. /**
  11303. * Given a list of run transactions, send them to the server and then handle
  11304. * the result (success or failure).
  11305. *
  11306. * @param path - The location of the queue.
  11307. * @param queue - Queue of transactions under the specified location.
  11308. */
  11309. function repoSendTransactionQueue(repo, path, queue) {
  11310. // Mark transactions as sent and increment retry count!
  11311. const setsToIgnore = queue.map(txn => {
  11312. return txn.currentWriteId;
  11313. });
  11314. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11315. let snapToSend = latestState;
  11316. const latestHash = latestState.hash();
  11317. for (let i = 0; i < queue.length; i++) {
  11318. const txn = queue[i];
  11319. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11320. txn.status = 1 /* TransactionStatus.SENT */;
  11321. txn.retryCount++;
  11322. const relativePath = newRelativePath(path, txn.path);
  11323. // If we've gotten to this point, the output snapshot must be defined.
  11324. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11325. }
  11326. const dataToSend = snapToSend.val(true);
  11327. const pathToSend = path;
  11328. // Send the put.
  11329. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11330. repoLog(repo, 'transaction put response', {
  11331. path: pathToSend.toString(),
  11332. status
  11333. });
  11334. let events = [];
  11335. if (status === 'ok') {
  11336. // Queue up the callbacks and fire them after cleaning up all of our
  11337. // transaction state, since the callback could trigger more
  11338. // transactions or sets.
  11339. const callbacks = [];
  11340. for (let i = 0; i < queue.length; i++) {
  11341. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11342. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11343. if (queue[i].onComplete) {
  11344. // We never unset the output snapshot, and given that this
  11345. // transaction is complete, it should be set
  11346. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11347. }
  11348. queue[i].unwatcher();
  11349. }
  11350. // Now remove the completed transactions.
  11351. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11352. // There may be pending transactions that we can now send.
  11353. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11354. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11355. // Finally, trigger onComplete callbacks.
  11356. for (let i = 0; i < callbacks.length; i++) {
  11357. exceptionGuard(callbacks[i]);
  11358. }
  11359. }
  11360. else {
  11361. // transactions are no longer sent. Update their status appropriately.
  11362. if (status === 'datastale') {
  11363. for (let i = 0; i < queue.length; i++) {
  11364. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11365. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11366. }
  11367. else {
  11368. queue[i].status = 0 /* TransactionStatus.RUN */;
  11369. }
  11370. }
  11371. }
  11372. else {
  11373. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11374. for (let i = 0; i < queue.length; i++) {
  11375. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11376. queue[i].abortReason = status;
  11377. }
  11378. }
  11379. repoRerunTransactions(repo, path);
  11380. }
  11381. }, latestHash);
  11382. }
  11383. /**
  11384. * Finds all transactions dependent on the data at changedPath and reruns them.
  11385. *
  11386. * Should be called any time cached data changes.
  11387. *
  11388. * Return the highest path that was affected by rerunning transactions. This
  11389. * is the path at which events need to be raised for.
  11390. *
  11391. * @param changedPath - The path in mergedData that changed.
  11392. * @returns The rootmost path that was affected by rerunning transactions.
  11393. */
  11394. function repoRerunTransactions(repo, changedPath) {
  11395. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11396. const path = treeGetPath(rootMostTransactionNode);
  11397. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11398. repoRerunTransactionQueue(repo, queue, path);
  11399. return path;
  11400. }
  11401. /**
  11402. * Does all the work of rerunning transactions (as well as cleans up aborted
  11403. * transactions and whatnot).
  11404. *
  11405. * @param queue - The queue of transactions to run.
  11406. * @param path - The path the queue is for.
  11407. */
  11408. function repoRerunTransactionQueue(repo, queue, path) {
  11409. if (queue.length === 0) {
  11410. return; // Nothing to do!
  11411. }
  11412. // Queue up the callbacks and fire them after cleaning up all of our
  11413. // transaction state, since the callback could trigger more transactions or
  11414. // sets.
  11415. const callbacks = [];
  11416. let events = [];
  11417. // Ignore all of the sets we're going to re-run.
  11418. const txnsToRerun = queue.filter(q => {
  11419. return q.status === 0 /* TransactionStatus.RUN */;
  11420. });
  11421. const setsToIgnore = txnsToRerun.map(q => {
  11422. return q.currentWriteId;
  11423. });
  11424. for (let i = 0; i < queue.length; i++) {
  11425. const transaction = queue[i];
  11426. const relativePath = newRelativePath(path, transaction.path);
  11427. let abortTransaction = false, abortReason;
  11428. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11429. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11430. abortTransaction = true;
  11431. abortReason = transaction.abortReason;
  11432. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11433. }
  11434. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11435. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11436. abortTransaction = true;
  11437. abortReason = 'maxretry';
  11438. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11439. }
  11440. else {
  11441. // This code reruns a transaction
  11442. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11443. transaction.currentInputSnapshot = currentNode;
  11444. const newData = queue[i].update(currentNode.val());
  11445. if (newData !== undefined) {
  11446. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11447. let newDataNode = nodeFromJSON(newData);
  11448. const hasExplicitPriority = typeof newData === 'object' &&
  11449. newData != null &&
  11450. util.contains(newData, '.priority');
  11451. if (!hasExplicitPriority) {
  11452. // Keep the old priority if there wasn't a priority explicitly specified.
  11453. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11454. }
  11455. const oldWriteId = transaction.currentWriteId;
  11456. const serverValues = repoGenerateServerValues(repo);
  11457. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11458. transaction.currentOutputSnapshotRaw = newDataNode;
  11459. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11460. transaction.currentWriteId = repoGetNextWriteId(repo);
  11461. // Mutates setsToIgnore in place
  11462. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11463. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11464. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11465. }
  11466. else {
  11467. abortTransaction = true;
  11468. abortReason = 'nodata';
  11469. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11470. }
  11471. }
  11472. }
  11473. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11474. events = [];
  11475. if (abortTransaction) {
  11476. // Abort.
  11477. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11478. // Removing a listener can trigger pruning which can muck with
  11479. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11480. // until we're done.
  11481. (function (unwatcher) {
  11482. setTimeout(unwatcher, Math.floor(0));
  11483. })(queue[i].unwatcher);
  11484. if (queue[i].onComplete) {
  11485. if (abortReason === 'nodata') {
  11486. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11487. }
  11488. else {
  11489. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11490. }
  11491. }
  11492. }
  11493. }
  11494. // Clean up completed transactions.
  11495. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11496. // Now fire callbacks, now that we're in a good, known state.
  11497. for (let i = 0; i < callbacks.length; i++) {
  11498. exceptionGuard(callbacks[i]);
  11499. }
  11500. // Try to send the transaction result to the server.
  11501. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11502. }
  11503. /**
  11504. * Returns the rootmost ancestor node of the specified path that has a pending
  11505. * transaction on it, or just returns the node for the given path if there are
  11506. * no pending transactions on any ancestor.
  11507. *
  11508. * @param path - The location to start at.
  11509. * @returns The rootmost node with a transaction.
  11510. */
  11511. function repoGetAncestorTransactionNode(repo, path) {
  11512. let front;
  11513. // Start at the root and walk deeper into the tree towards path until we
  11514. // find a node with pending transactions.
  11515. let transactionNode = repo.transactionQueueTree_;
  11516. front = pathGetFront(path);
  11517. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11518. transactionNode = treeSubTree(transactionNode, front);
  11519. path = pathPopFront(path);
  11520. front = pathGetFront(path);
  11521. }
  11522. return transactionNode;
  11523. }
  11524. /**
  11525. * Builds the queue of all transactions at or below the specified
  11526. * transactionNode.
  11527. *
  11528. * @param transactionNode
  11529. * @returns The generated queue.
  11530. */
  11531. function repoBuildTransactionQueue(repo, transactionNode) {
  11532. // Walk any child transaction queues and aggregate them into a single queue.
  11533. const transactionQueue = [];
  11534. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11535. // Sort them by the order the transactions were created.
  11536. transactionQueue.sort((a, b) => a.order - b.order);
  11537. return transactionQueue;
  11538. }
  11539. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11540. const nodeQueue = treeGetValue(node);
  11541. if (nodeQueue) {
  11542. for (let i = 0; i < nodeQueue.length; i++) {
  11543. queue.push(nodeQueue[i]);
  11544. }
  11545. }
  11546. treeForEachChild(node, child => {
  11547. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11548. });
  11549. }
  11550. /**
  11551. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11552. */
  11553. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11554. const queue = treeGetValue(node);
  11555. if (queue) {
  11556. let to = 0;
  11557. for (let from = 0; from < queue.length; from++) {
  11558. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11559. queue[to] = queue[from];
  11560. to++;
  11561. }
  11562. }
  11563. queue.length = to;
  11564. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11565. }
  11566. treeForEachChild(node, childNode => {
  11567. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11568. });
  11569. }
  11570. /**
  11571. * Aborts all transactions on ancestors or descendants of the specified path.
  11572. * Called when doing a set() or update() since we consider them incompatible
  11573. * with transactions.
  11574. *
  11575. * @param path - Path for which we want to abort related transactions.
  11576. */
  11577. function repoAbortTransactions(repo, path) {
  11578. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11579. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11580. treeForEachAncestor(transactionNode, (node) => {
  11581. repoAbortTransactionsOnNode(repo, node);
  11582. });
  11583. repoAbortTransactionsOnNode(repo, transactionNode);
  11584. treeForEachDescendant(transactionNode, (node) => {
  11585. repoAbortTransactionsOnNode(repo, node);
  11586. });
  11587. return affectedPath;
  11588. }
  11589. /**
  11590. * Abort transactions stored in this transaction queue node.
  11591. *
  11592. * @param node - Node to abort transactions for.
  11593. */
  11594. function repoAbortTransactionsOnNode(repo, node) {
  11595. const queue = treeGetValue(node);
  11596. if (queue) {
  11597. // Queue up the callbacks and fire them after cleaning up all of our
  11598. // transaction state, since the callback could trigger more transactions
  11599. // or sets.
  11600. const callbacks = [];
  11601. // Go through queue. Any already-sent transactions must be marked for
  11602. // abort, while the unsent ones can be immediately aborted and removed.
  11603. let events = [];
  11604. let lastSent = -1;
  11605. for (let i = 0; i < queue.length; i++) {
  11606. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11607. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11608. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11609. lastSent = i;
  11610. // Mark transaction for abort when it comes back.
  11611. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11612. queue[i].abortReason = 'set';
  11613. }
  11614. else {
  11615. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11616. // We can abort it immediately.
  11617. queue[i].unwatcher();
  11618. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11619. if (queue[i].onComplete) {
  11620. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11621. }
  11622. }
  11623. }
  11624. if (lastSent === -1) {
  11625. // We're not waiting for any sent transactions. We can clear the queue.
  11626. treeSetValue(node, undefined);
  11627. }
  11628. else {
  11629. // Remove the transactions we aborted.
  11630. queue.length = lastSent + 1;
  11631. }
  11632. // Now fire the callbacks.
  11633. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11634. for (let i = 0; i < callbacks.length; i++) {
  11635. exceptionGuard(callbacks[i]);
  11636. }
  11637. }
  11638. }
  11639. /**
  11640. * @license
  11641. * Copyright 2017 Google LLC
  11642. *
  11643. * Licensed under the Apache License, Version 2.0 (the "License");
  11644. * you may not use this file except in compliance with the License.
  11645. * You may obtain a copy of the License at
  11646. *
  11647. * http://www.apache.org/licenses/LICENSE-2.0
  11648. *
  11649. * Unless required by applicable law or agreed to in writing, software
  11650. * distributed under the License is distributed on an "AS IS" BASIS,
  11651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11652. * See the License for the specific language governing permissions and
  11653. * limitations under the License.
  11654. */
  11655. function decodePath(pathString) {
  11656. let pathStringDecoded = '';
  11657. const pieces = pathString.split('/');
  11658. for (let i = 0; i < pieces.length; i++) {
  11659. if (pieces[i].length > 0) {
  11660. let piece = pieces[i];
  11661. try {
  11662. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11663. }
  11664. catch (e) { }
  11665. pathStringDecoded += '/' + piece;
  11666. }
  11667. }
  11668. return pathStringDecoded;
  11669. }
  11670. /**
  11671. * @returns key value hash
  11672. */
  11673. function decodeQuery(queryString) {
  11674. const results = {};
  11675. if (queryString.charAt(0) === '?') {
  11676. queryString = queryString.substring(1);
  11677. }
  11678. for (const segment of queryString.split('&')) {
  11679. if (segment.length === 0) {
  11680. continue;
  11681. }
  11682. const kv = segment.split('=');
  11683. if (kv.length === 2) {
  11684. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11685. }
  11686. else {
  11687. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11688. }
  11689. }
  11690. return results;
  11691. }
  11692. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11693. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11694. if (parsedUrl.domain === 'firebase.com') {
  11695. fatal(parsedUrl.host +
  11696. ' is no longer supported. ' +
  11697. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11698. }
  11699. // Catch common error of uninitialized namespace value.
  11700. if ((!namespace || namespace === 'undefined') &&
  11701. parsedUrl.domain !== 'localhost') {
  11702. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11703. }
  11704. if (!parsedUrl.secure) {
  11705. warnIfPageIsSecure();
  11706. }
  11707. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11708. return {
  11709. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11710. /*persistenceKey=*/ '',
  11711. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11712. path: new Path(parsedUrl.pathString)
  11713. };
  11714. };
  11715. const parseDatabaseURL = function (dataURL) {
  11716. // Default to empty strings in the event of a malformed string.
  11717. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11718. // Always default to SSL, unless otherwise specified.
  11719. let secure = true, scheme = 'https', port = 443;
  11720. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11721. if (typeof dataURL === 'string') {
  11722. // Parse scheme.
  11723. let colonInd = dataURL.indexOf('//');
  11724. if (colonInd >= 0) {
  11725. scheme = dataURL.substring(0, colonInd - 1);
  11726. dataURL = dataURL.substring(colonInd + 2);
  11727. }
  11728. // Parse host, path, and query string.
  11729. let slashInd = dataURL.indexOf('/');
  11730. if (slashInd === -1) {
  11731. slashInd = dataURL.length;
  11732. }
  11733. let questionMarkInd = dataURL.indexOf('?');
  11734. if (questionMarkInd === -1) {
  11735. questionMarkInd = dataURL.length;
  11736. }
  11737. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11738. if (slashInd < questionMarkInd) {
  11739. // For pathString, questionMarkInd will always come after slashInd
  11740. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11741. }
  11742. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11743. // If we have a port, use scheme for determining if it's secure.
  11744. colonInd = host.indexOf(':');
  11745. if (colonInd >= 0) {
  11746. secure = scheme === 'https' || scheme === 'wss';
  11747. port = parseInt(host.substring(colonInd + 1), 10);
  11748. }
  11749. else {
  11750. colonInd = host.length;
  11751. }
  11752. const hostWithoutPort = host.slice(0, colonInd);
  11753. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11754. domain = 'localhost';
  11755. }
  11756. else if (hostWithoutPort.split('.').length <= 2) {
  11757. domain = hostWithoutPort;
  11758. }
  11759. else {
  11760. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11761. const dotInd = host.indexOf('.');
  11762. subdomain = host.substring(0, dotInd).toLowerCase();
  11763. domain = host.substring(dotInd + 1);
  11764. // Normalize namespaces to lowercase to share storage / connection.
  11765. namespace = subdomain;
  11766. }
  11767. // Always treat the value of the `ns` as the namespace name if it is present.
  11768. if ('ns' in queryParams) {
  11769. namespace = queryParams['ns'];
  11770. }
  11771. }
  11772. return {
  11773. host,
  11774. port,
  11775. domain,
  11776. subdomain,
  11777. secure,
  11778. scheme,
  11779. pathString,
  11780. namespace
  11781. };
  11782. };
  11783. /**
  11784. * @license
  11785. * Copyright 2017 Google LLC
  11786. *
  11787. * Licensed under the Apache License, Version 2.0 (the "License");
  11788. * you may not use this file except in compliance with the License.
  11789. * You may obtain a copy of the License at
  11790. *
  11791. * http://www.apache.org/licenses/LICENSE-2.0
  11792. *
  11793. * Unless required by applicable law or agreed to in writing, software
  11794. * distributed under the License is distributed on an "AS IS" BASIS,
  11795. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11796. * See the License for the specific language governing permissions and
  11797. * limitations under the License.
  11798. */
  11799. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11800. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11801. /**
  11802. * Fancy ID generator that creates 20-character string identifiers with the
  11803. * following properties:
  11804. *
  11805. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11806. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11807. * collide with other clients' IDs.
  11808. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11809. * that will sort properly).
  11810. * 4. They're monotonically increasing. Even if you generate more than one in
  11811. * the same timestamp, the latter ones will sort after the former ones. We do
  11812. * this by using the previous random bits but "incrementing" them by 1 (only
  11813. * in the case of a timestamp collision).
  11814. */
  11815. const nextPushId = (function () {
  11816. // Timestamp of last push, used to prevent local collisions if you push twice
  11817. // in one ms.
  11818. let lastPushTime = 0;
  11819. // We generate 72-bits of randomness which get turned into 12 characters and
  11820. // appended to the timestamp to prevent collisions with other clients. We
  11821. // store the last characters we generated because in the event of a collision,
  11822. // we'll use those same characters except "incremented" by one.
  11823. const lastRandChars = [];
  11824. return function (now) {
  11825. const duplicateTime = now === lastPushTime;
  11826. lastPushTime = now;
  11827. let i;
  11828. const timeStampChars = new Array(8);
  11829. for (i = 7; i >= 0; i--) {
  11830. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11831. // NOTE: Can't use << here because javascript will convert to int and lose
  11832. // the upper bits.
  11833. now = Math.floor(now / 64);
  11834. }
  11835. util.assert(now === 0, 'Cannot push at time == 0');
  11836. let id = timeStampChars.join('');
  11837. if (!duplicateTime) {
  11838. for (i = 0; i < 12; i++) {
  11839. lastRandChars[i] = Math.floor(Math.random() * 64);
  11840. }
  11841. }
  11842. else {
  11843. // If the timestamp hasn't changed since last push, use the same random
  11844. // number, except incremented by 1.
  11845. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11846. lastRandChars[i] = 0;
  11847. }
  11848. lastRandChars[i]++;
  11849. }
  11850. for (i = 0; i < 12; i++) {
  11851. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11852. }
  11853. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  11854. return id;
  11855. };
  11856. })();
  11857. /**
  11858. * @license
  11859. * Copyright 2017 Google LLC
  11860. *
  11861. * Licensed under the Apache License, Version 2.0 (the "License");
  11862. * you may not use this file except in compliance with the License.
  11863. * You may obtain a copy of the License at
  11864. *
  11865. * http://www.apache.org/licenses/LICENSE-2.0
  11866. *
  11867. * Unless required by applicable law or agreed to in writing, software
  11868. * distributed under the License is distributed on an "AS IS" BASIS,
  11869. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11870. * See the License for the specific language governing permissions and
  11871. * limitations under the License.
  11872. */
  11873. /**
  11874. * Encapsulates the data needed to raise an event
  11875. */
  11876. class DataEvent {
  11877. /**
  11878. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11879. * @param eventRegistration - The function to call to with the event data. User provided
  11880. * @param snapshot - The data backing the event
  11881. * @param prevName - Optional, the name of the previous child for child_* events.
  11882. */
  11883. constructor(eventType, eventRegistration, snapshot, prevName) {
  11884. this.eventType = eventType;
  11885. this.eventRegistration = eventRegistration;
  11886. this.snapshot = snapshot;
  11887. this.prevName = prevName;
  11888. }
  11889. getPath() {
  11890. const ref = this.snapshot.ref;
  11891. if (this.eventType === 'value') {
  11892. return ref._path;
  11893. }
  11894. else {
  11895. return ref.parent._path;
  11896. }
  11897. }
  11898. getEventType() {
  11899. return this.eventType;
  11900. }
  11901. getEventRunner() {
  11902. return this.eventRegistration.getEventRunner(this);
  11903. }
  11904. toString() {
  11905. return (this.getPath().toString() +
  11906. ':' +
  11907. this.eventType +
  11908. ':' +
  11909. util.stringify(this.snapshot.exportVal()));
  11910. }
  11911. }
  11912. class CancelEvent {
  11913. constructor(eventRegistration, error, path) {
  11914. this.eventRegistration = eventRegistration;
  11915. this.error = error;
  11916. this.path = path;
  11917. }
  11918. getPath() {
  11919. return this.path;
  11920. }
  11921. getEventType() {
  11922. return 'cancel';
  11923. }
  11924. getEventRunner() {
  11925. return this.eventRegistration.getEventRunner(this);
  11926. }
  11927. toString() {
  11928. return this.path.toString() + ':cancel';
  11929. }
  11930. }
  11931. /**
  11932. * @license
  11933. * Copyright 2017 Google LLC
  11934. *
  11935. * Licensed under the Apache License, Version 2.0 (the "License");
  11936. * you may not use this file except in compliance with the License.
  11937. * You may obtain a copy of the License at
  11938. *
  11939. * http://www.apache.org/licenses/LICENSE-2.0
  11940. *
  11941. * Unless required by applicable law or agreed to in writing, software
  11942. * distributed under the License is distributed on an "AS IS" BASIS,
  11943. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11944. * See the License for the specific language governing permissions and
  11945. * limitations under the License.
  11946. */
  11947. /**
  11948. * A wrapper class that converts events from the database@exp SDK to the legacy
  11949. * Database SDK. Events are not converted directly as event registration relies
  11950. * on reference comparison of the original user callback (see `matches()`) and
  11951. * relies on equality of the legacy SDK's `context` object.
  11952. */
  11953. class CallbackContext {
  11954. constructor(snapshotCallback, cancelCallback) {
  11955. this.snapshotCallback = snapshotCallback;
  11956. this.cancelCallback = cancelCallback;
  11957. }
  11958. onValue(expDataSnapshot, previousChildName) {
  11959. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11960. }
  11961. onCancel(error) {
  11962. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11963. return this.cancelCallback.call(null, error);
  11964. }
  11965. get hasCancelCallback() {
  11966. return !!this.cancelCallback;
  11967. }
  11968. matches(other) {
  11969. return (this.snapshotCallback === other.snapshotCallback ||
  11970. (this.snapshotCallback.userCallback !== undefined &&
  11971. this.snapshotCallback.userCallback ===
  11972. other.snapshotCallback.userCallback &&
  11973. this.snapshotCallback.context === other.snapshotCallback.context));
  11974. }
  11975. }
  11976. /**
  11977. * @license
  11978. * Copyright 2021 Google LLC
  11979. *
  11980. * Licensed under the Apache License, Version 2.0 (the "License");
  11981. * you may not use this file except in compliance with the License.
  11982. * You may obtain a copy of the License at
  11983. *
  11984. * http://www.apache.org/licenses/LICENSE-2.0
  11985. *
  11986. * Unless required by applicable law or agreed to in writing, software
  11987. * distributed under the License is distributed on an "AS IS" BASIS,
  11988. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11989. * See the License for the specific language governing permissions and
  11990. * limitations under the License.
  11991. */
  11992. /**
  11993. * The `onDisconnect` class allows you to write or clear data when your client
  11994. * disconnects from the Database server. These updates occur whether your
  11995. * client disconnects cleanly or not, so you can rely on them to clean up data
  11996. * even if a connection is dropped or a client crashes.
  11997. *
  11998. * The `onDisconnect` class is most commonly used to manage presence in
  11999. * applications where it is useful to detect how many clients are connected and
  12000. * when other clients disconnect. See
  12001. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12002. * for more information.
  12003. *
  12004. * To avoid problems when a connection is dropped before the requests can be
  12005. * transferred to the Database server, these functions should be called before
  12006. * writing any data.
  12007. *
  12008. * Note that `onDisconnect` operations are only triggered once. If you want an
  12009. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12010. * the `onDisconnect` operations each time you reconnect.
  12011. */
  12012. class OnDisconnect {
  12013. /** @hideconstructor */
  12014. constructor(_repo, _path) {
  12015. this._repo = _repo;
  12016. this._path = _path;
  12017. }
  12018. /**
  12019. * Cancels all previously queued `onDisconnect()` set or update events for this
  12020. * location and all children.
  12021. *
  12022. * If a write has been queued for this location via a `set()` or `update()` at a
  12023. * parent location, the write at this location will be canceled, though writes
  12024. * to sibling locations will still occur.
  12025. *
  12026. * @returns Resolves when synchronization to the server is complete.
  12027. */
  12028. cancel() {
  12029. const deferred = new util.Deferred();
  12030. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12031. return deferred.promise;
  12032. }
  12033. /**
  12034. * Ensures the data at this location is deleted when the client is disconnected
  12035. * (due to closing the browser, navigating to a new page, or network issues).
  12036. *
  12037. * @returns Resolves when synchronization to the server is complete.
  12038. */
  12039. remove() {
  12040. validateWritablePath('OnDisconnect.remove', this._path);
  12041. const deferred = new util.Deferred();
  12042. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12043. return deferred.promise;
  12044. }
  12045. /**
  12046. * Ensures the data at this location is set to the specified value when the
  12047. * client is disconnected (due to closing the browser, navigating to a new page,
  12048. * or network issues).
  12049. *
  12050. * `set()` is especially useful for implementing "presence" systems, where a
  12051. * value should be changed or cleared when a user disconnects so that they
  12052. * appear "offline" to other users. See
  12053. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12054. * for more information.
  12055. *
  12056. * Note that `onDisconnect` operations are only triggered once. If you want an
  12057. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12058. * the `onDisconnect` operations each time.
  12059. *
  12060. * @param value - The value to be written to this location on disconnect (can
  12061. * be an object, array, string, number, boolean, or null).
  12062. * @returns Resolves when synchronization to the Database is complete.
  12063. */
  12064. set(value) {
  12065. validateWritablePath('OnDisconnect.set', this._path);
  12066. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12067. const deferred = new util.Deferred();
  12068. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12069. return deferred.promise;
  12070. }
  12071. /**
  12072. * Ensures the data at this location is set to the specified value and priority
  12073. * when the client is disconnected (due to closing the browser, navigating to a
  12074. * new page, or network issues).
  12075. *
  12076. * @param value - The value to be written to this location on disconnect (can
  12077. * be an object, array, string, number, boolean, or null).
  12078. * @param priority - The priority to be written (string, number, or null).
  12079. * @returns Resolves when synchronization to the Database is complete.
  12080. */
  12081. setWithPriority(value, priority) {
  12082. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12083. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12084. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12085. const deferred = new util.Deferred();
  12086. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12087. return deferred.promise;
  12088. }
  12089. /**
  12090. * Writes multiple values at this location when the client is disconnected (due
  12091. * to closing the browser, navigating to a new page, or network issues).
  12092. *
  12093. * The `values` argument contains multiple property-value pairs that will be
  12094. * written to the Database together. Each child property can either be a simple
  12095. * property (for example, "name") or a relative path (for example, "name/first")
  12096. * from the current location to the data to update.
  12097. *
  12098. * As opposed to the `set()` method, `update()` can be use to selectively update
  12099. * only the referenced properties at the current location (instead of replacing
  12100. * all the child properties at the current location).
  12101. *
  12102. * @param values - Object containing multiple values.
  12103. * @returns Resolves when synchronization to the Database is complete.
  12104. */
  12105. update(values) {
  12106. validateWritablePath('OnDisconnect.update', this._path);
  12107. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12108. const deferred = new util.Deferred();
  12109. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12110. return deferred.promise;
  12111. }
  12112. }
  12113. /**
  12114. * @license
  12115. * Copyright 2020 Google LLC
  12116. *
  12117. * Licensed under the Apache License, Version 2.0 (the "License");
  12118. * you may not use this file except in compliance with the License.
  12119. * You may obtain a copy of the License at
  12120. *
  12121. * http://www.apache.org/licenses/LICENSE-2.0
  12122. *
  12123. * Unless required by applicable law or agreed to in writing, software
  12124. * distributed under the License is distributed on an "AS IS" BASIS,
  12125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12126. * See the License for the specific language governing permissions and
  12127. * limitations under the License.
  12128. */
  12129. /**
  12130. * @internal
  12131. */
  12132. class QueryImpl {
  12133. /**
  12134. * @hideconstructor
  12135. */
  12136. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12137. this._repo = _repo;
  12138. this._path = _path;
  12139. this._queryParams = _queryParams;
  12140. this._orderByCalled = _orderByCalled;
  12141. }
  12142. get key() {
  12143. if (pathIsEmpty(this._path)) {
  12144. return null;
  12145. }
  12146. else {
  12147. return pathGetBack(this._path);
  12148. }
  12149. }
  12150. get ref() {
  12151. return new ReferenceImpl(this._repo, this._path);
  12152. }
  12153. get _queryIdentifier() {
  12154. const obj = queryParamsGetQueryObject(this._queryParams);
  12155. const id = ObjectToUniqueKey(obj);
  12156. return id === '{}' ? 'default' : id;
  12157. }
  12158. /**
  12159. * An object representation of the query parameters used by this Query.
  12160. */
  12161. get _queryObject() {
  12162. return queryParamsGetQueryObject(this._queryParams);
  12163. }
  12164. isEqual(other) {
  12165. other = util.getModularInstance(other);
  12166. if (!(other instanceof QueryImpl)) {
  12167. return false;
  12168. }
  12169. const sameRepo = this._repo === other._repo;
  12170. const samePath = pathEquals(this._path, other._path);
  12171. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12172. return sameRepo && samePath && sameQueryIdentifier;
  12173. }
  12174. toJSON() {
  12175. return this.toString();
  12176. }
  12177. toString() {
  12178. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12179. }
  12180. }
  12181. /**
  12182. * Validates that no other order by call has been made
  12183. */
  12184. function validateNoPreviousOrderByCall(query, fnName) {
  12185. if (query._orderByCalled === true) {
  12186. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12187. }
  12188. }
  12189. /**
  12190. * Validates start/end values for queries.
  12191. */
  12192. function validateQueryEndpoints(params) {
  12193. let startNode = null;
  12194. let endNode = null;
  12195. if (params.hasStart()) {
  12196. startNode = params.getIndexStartValue();
  12197. }
  12198. if (params.hasEnd()) {
  12199. endNode = params.getIndexEndValue();
  12200. }
  12201. if (params.getIndex() === KEY_INDEX) {
  12202. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12203. 'startAt(), endAt(), or equalTo().';
  12204. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12205. 'endAt(), endBefore(), or equalTo() must be a string.';
  12206. if (params.hasStart()) {
  12207. const startName = params.getIndexStartName();
  12208. if (startName !== MIN_NAME) {
  12209. throw new Error(tooManyArgsError);
  12210. }
  12211. else if (typeof startNode !== 'string') {
  12212. throw new Error(wrongArgTypeError);
  12213. }
  12214. }
  12215. if (params.hasEnd()) {
  12216. const endName = params.getIndexEndName();
  12217. if (endName !== MAX_NAME) {
  12218. throw new Error(tooManyArgsError);
  12219. }
  12220. else if (typeof endNode !== 'string') {
  12221. throw new Error(wrongArgTypeError);
  12222. }
  12223. }
  12224. }
  12225. else if (params.getIndex() === PRIORITY_INDEX) {
  12226. if ((startNode != null && !isValidPriority(startNode)) ||
  12227. (endNode != null && !isValidPriority(endNode))) {
  12228. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12229. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12230. '(null, a number, or a string).');
  12231. }
  12232. }
  12233. else {
  12234. util.assert(params.getIndex() instanceof PathIndex ||
  12235. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12236. if ((startNode != null && typeof startNode === 'object') ||
  12237. (endNode != null && typeof endNode === 'object')) {
  12238. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12239. 'equalTo() cannot be an object.');
  12240. }
  12241. }
  12242. }
  12243. /**
  12244. * Validates that limit* has been called with the correct combination of parameters
  12245. */
  12246. function validateLimit(params) {
  12247. if (params.hasStart() &&
  12248. params.hasEnd() &&
  12249. params.hasLimit() &&
  12250. !params.hasAnchoredLimit()) {
  12251. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12252. 'limitToFirst() or limitToLast() instead.');
  12253. }
  12254. }
  12255. /**
  12256. * @internal
  12257. */
  12258. class ReferenceImpl extends QueryImpl {
  12259. /** @hideconstructor */
  12260. constructor(repo, path) {
  12261. super(repo, path, new QueryParams(), false);
  12262. }
  12263. get parent() {
  12264. const parentPath = pathParent(this._path);
  12265. return parentPath === null
  12266. ? null
  12267. : new ReferenceImpl(this._repo, parentPath);
  12268. }
  12269. get root() {
  12270. let ref = this;
  12271. while (ref.parent !== null) {
  12272. ref = ref.parent;
  12273. }
  12274. return ref;
  12275. }
  12276. }
  12277. /**
  12278. * A `DataSnapshot` contains data from a Database location.
  12279. *
  12280. * Any time you read data from the Database, you receive the data as a
  12281. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12282. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12283. * JavaScript object by calling the `val()` method. Alternatively, you can
  12284. * traverse into the snapshot by calling `child()` to return child snapshots
  12285. * (which you could then call `val()` on).
  12286. *
  12287. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12288. * a Database location. It cannot be modified and will never change (to modify
  12289. * data, you always call the `set()` method on a `Reference` directly).
  12290. */
  12291. class DataSnapshot {
  12292. /**
  12293. * @param _node - A SnapshotNode to wrap.
  12294. * @param ref - The location this snapshot came from.
  12295. * @param _index - The iteration order for this snapshot
  12296. * @hideconstructor
  12297. */
  12298. constructor(_node,
  12299. /**
  12300. * The location of this DataSnapshot.
  12301. */
  12302. ref, _index) {
  12303. this._node = _node;
  12304. this.ref = ref;
  12305. this._index = _index;
  12306. }
  12307. /**
  12308. * Gets the priority value of the data in this `DataSnapshot`.
  12309. *
  12310. * Applications need not use priority but can order collections by
  12311. * ordinary properties (see
  12312. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12313. * ).
  12314. */
  12315. get priority() {
  12316. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12317. return this._node.getPriority().val();
  12318. }
  12319. /**
  12320. * The key (last part of the path) of the location of this `DataSnapshot`.
  12321. *
  12322. * The last token in a Database location is considered its key. For example,
  12323. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12324. * `DataSnapshot` will return the key for the location that generated it.
  12325. * However, accessing the key on the root URL of a Database will return
  12326. * `null`.
  12327. */
  12328. get key() {
  12329. return this.ref.key;
  12330. }
  12331. /** Returns the number of child properties of this `DataSnapshot`. */
  12332. get size() {
  12333. return this._node.numChildren();
  12334. }
  12335. /**
  12336. * Gets another `DataSnapshot` for the location at the specified relative path.
  12337. *
  12338. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12339. * another `DataSnapshot` for the location at the specified relative path. The
  12340. * relative path can either be a simple child name (for example, "ada") or a
  12341. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12342. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12343. * whose value is `null`) is returned.
  12344. *
  12345. * @param path - A relative path to the location of child data.
  12346. */
  12347. child(path) {
  12348. const childPath = new Path(path);
  12349. const childRef = child(this.ref, path);
  12350. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12351. }
  12352. /**
  12353. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12354. * efficient than using `snapshot.val() !== null`.
  12355. */
  12356. exists() {
  12357. return !this._node.isEmpty();
  12358. }
  12359. /**
  12360. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12361. *
  12362. * The `exportVal()` method is similar to `val()`, except priority information
  12363. * is included (if available), making it suitable for backing up your data.
  12364. *
  12365. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12366. * Array, string, number, boolean, or `null`).
  12367. */
  12368. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12369. exportVal() {
  12370. return this._node.val(true);
  12371. }
  12372. /**
  12373. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  12374. *
  12375. * Because of the way JavaScript objects work, the ordering of data in the
  12376. * JavaScript object returned by `val()` is not guaranteed to match the
  12377. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12378. * where `forEach()` comes in handy. It guarantees the children of a
  12379. * `DataSnapshot` will be iterated in their query order.
  12380. *
  12381. * If no explicit `orderBy*()` method is used, results are returned
  12382. * ordered by key (unless priorities are used, in which case, results are
  12383. * returned by priority).
  12384. *
  12385. * @param action - A function that will be called for each child DataSnapshot.
  12386. * The callback can return true to cancel further enumeration.
  12387. * @returns true if enumeration was canceled due to your callback returning
  12388. * true.
  12389. */
  12390. forEach(action) {
  12391. if (this._node.isLeafNode()) {
  12392. return false;
  12393. }
  12394. const childrenNode = this._node;
  12395. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12396. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12397. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12398. });
  12399. }
  12400. /**
  12401. * Returns true if the specified child path has (non-null) data.
  12402. *
  12403. * @param path - A relative path to the location of a potential child.
  12404. * @returns `true` if data exists at the specified child path; else
  12405. * `false`.
  12406. */
  12407. hasChild(path) {
  12408. const childPath = new Path(path);
  12409. return !this._node.getChild(childPath).isEmpty();
  12410. }
  12411. /**
  12412. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12413. * properties.
  12414. *
  12415. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12416. * children. If it does, you can enumerate them using `forEach()`. If it
  12417. * doesn't, then either this snapshot contains a primitive value (which can be
  12418. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12419. * `null`).
  12420. *
  12421. * @returns true if this snapshot has any children; else false.
  12422. */
  12423. hasChildren() {
  12424. if (this._node.isLeafNode()) {
  12425. return false;
  12426. }
  12427. else {
  12428. return !this._node.isEmpty();
  12429. }
  12430. }
  12431. /**
  12432. * Returns a JSON-serializable representation of this object.
  12433. */
  12434. toJSON() {
  12435. return this.exportVal();
  12436. }
  12437. /**
  12438. * Extracts a JavaScript value from a `DataSnapshot`.
  12439. *
  12440. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12441. * scalar type (string, number, or boolean), an array, or an object. It may
  12442. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12443. * data).
  12444. *
  12445. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12446. * Array, string, number, boolean, or `null`).
  12447. */
  12448. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12449. val() {
  12450. return this._node.val();
  12451. }
  12452. }
  12453. /**
  12454. *
  12455. * Returns a `Reference` representing the location in the Database
  12456. * corresponding to the provided path. If no path is provided, the `Reference`
  12457. * will point to the root of the Database.
  12458. *
  12459. * @param db - The database instance to obtain a reference for.
  12460. * @param path - Optional path representing the location the returned
  12461. * `Reference` will point. If not provided, the returned `Reference` will
  12462. * point to the root of the Database.
  12463. * @returns If a path is provided, a `Reference`
  12464. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12465. * root of the Database.
  12466. */
  12467. function ref(db, path) {
  12468. db = util.getModularInstance(db);
  12469. db._checkNotDeleted('ref');
  12470. return path !== undefined ? child(db._root, path) : db._root;
  12471. }
  12472. /**
  12473. * Returns a `Reference` representing the location in the Database
  12474. * corresponding to the provided Firebase URL.
  12475. *
  12476. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12477. * has a different domain than the current `Database` instance.
  12478. *
  12479. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12480. * and are not applied to the returned `Reference`.
  12481. *
  12482. * @param db - The database instance to obtain a reference for.
  12483. * @param url - The Firebase URL at which the returned `Reference` will
  12484. * point.
  12485. * @returns A `Reference` pointing to the provided
  12486. * Firebase URL.
  12487. */
  12488. function refFromURL(db, url) {
  12489. db = util.getModularInstance(db);
  12490. db._checkNotDeleted('refFromURL');
  12491. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12492. validateUrl('refFromURL', parsedURL);
  12493. const repoInfo = parsedURL.repoInfo;
  12494. if (!db._repo.repoInfo_.isCustomHost() &&
  12495. repoInfo.host !== db._repo.repoInfo_.host) {
  12496. fatal('refFromURL' +
  12497. ': Host name does not match the current database: ' +
  12498. '(found ' +
  12499. repoInfo.host +
  12500. ' but expected ' +
  12501. db._repo.repoInfo_.host +
  12502. ')');
  12503. }
  12504. return ref(db, parsedURL.path.toString());
  12505. }
  12506. /**
  12507. * Gets a `Reference` for the location at the specified relative path.
  12508. *
  12509. * The relative path can either be a simple child name (for example, "ada") or
  12510. * a deeper slash-separated path (for example, "ada/name/first").
  12511. *
  12512. * @param parent - The parent location.
  12513. * @param path - A relative path from this location to the desired child
  12514. * location.
  12515. * @returns The specified child location.
  12516. */
  12517. function child(parent, path) {
  12518. parent = util.getModularInstance(parent);
  12519. if (pathGetFront(parent._path) === null) {
  12520. validateRootPathString('child', 'path', path, false);
  12521. }
  12522. else {
  12523. validatePathString('child', 'path', path, false);
  12524. }
  12525. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12526. }
  12527. /**
  12528. * Returns an `OnDisconnect` object - see
  12529. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12530. * for more information on how to use it.
  12531. *
  12532. * @param ref - The reference to add OnDisconnect triggers for.
  12533. */
  12534. function onDisconnect(ref) {
  12535. ref = util.getModularInstance(ref);
  12536. return new OnDisconnect(ref._repo, ref._path);
  12537. }
  12538. /**
  12539. * Generates a new child location using a unique key and returns its
  12540. * `Reference`.
  12541. *
  12542. * This is the most common pattern for adding data to a collection of items.
  12543. *
  12544. * If you provide a value to `push()`, the value is written to the
  12545. * generated location. If you don't pass a value, nothing is written to the
  12546. * database and the child remains empty (but you can use the `Reference`
  12547. * elsewhere).
  12548. *
  12549. * The unique keys generated by `push()` are ordered by the current time, so the
  12550. * resulting list of items is chronologically sorted. The keys are also
  12551. * designed to be unguessable (they contain 72 random bits of entropy).
  12552. *
  12553. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12554. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12555. *
  12556. * @param parent - The parent location.
  12557. * @param value - Optional value to be written at the generated location.
  12558. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12559. * but can be used immediately as the `Reference` to the child location.
  12560. */
  12561. function push(parent, value) {
  12562. parent = util.getModularInstance(parent);
  12563. validateWritablePath('push', parent._path);
  12564. validateFirebaseDataArg('push', value, parent._path, true);
  12565. const now = repoServerTime(parent._repo);
  12566. const name = nextPushId(now);
  12567. // push() returns a ThennableReference whose promise is fulfilled with a
  12568. // regular Reference. We use child() to create handles to two different
  12569. // references. The first is turned into a ThennableReference below by adding
  12570. // then() and catch() methods and is used as the return value of push(). The
  12571. // second remains a regular Reference and is used as the fulfilled value of
  12572. // the first ThennableReference.
  12573. const thenablePushRef = child(parent, name);
  12574. const pushRef = child(parent, name);
  12575. let promise;
  12576. if (value != null) {
  12577. promise = set(pushRef, value).then(() => pushRef);
  12578. }
  12579. else {
  12580. promise = Promise.resolve(pushRef);
  12581. }
  12582. thenablePushRef.then = promise.then.bind(promise);
  12583. thenablePushRef.catch = promise.then.bind(promise, undefined);
  12584. return thenablePushRef;
  12585. }
  12586. /**
  12587. * Removes the data at this Database location.
  12588. *
  12589. * Any data at child locations will also be deleted.
  12590. *
  12591. * The effect of the remove will be visible immediately and the corresponding
  12592. * event 'value' will be triggered. Synchronization of the remove to the
  12593. * Firebase servers will also be started, and the returned Promise will resolve
  12594. * when complete. If provided, the onComplete callback will be called
  12595. * asynchronously after synchronization has finished.
  12596. *
  12597. * @param ref - The location to remove.
  12598. * @returns Resolves when remove on server is complete.
  12599. */
  12600. function remove(ref) {
  12601. validateWritablePath('remove', ref._path);
  12602. return set(ref, null);
  12603. }
  12604. /**
  12605. * Writes data to this Database location.
  12606. *
  12607. * This will overwrite any data at this location and all child locations.
  12608. *
  12609. * The effect of the write will be visible immediately, and the corresponding
  12610. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12611. * the data to the Firebase servers will also be started, and the returned
  12612. * Promise will resolve when complete. If provided, the `onComplete` callback
  12613. * will be called asynchronously after synchronization has finished.
  12614. *
  12615. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12616. * all data at this location and all child locations will be deleted.
  12617. *
  12618. * `set()` will remove any priority stored at this location, so if priority is
  12619. * meant to be preserved, you need to use `setWithPriority()` instead.
  12620. *
  12621. * Note that modifying data with `set()` will cancel any pending transactions
  12622. * at that location, so extreme care should be taken if mixing `set()` and
  12623. * `transaction()` to modify the same data.
  12624. *
  12625. * A single `set()` will generate a single "value" event at the location where
  12626. * the `set()` was performed.
  12627. *
  12628. * @param ref - The location to write to.
  12629. * @param value - The value to be written (string, number, boolean, object,
  12630. * array, or null).
  12631. * @returns Resolves when write to server is complete.
  12632. */
  12633. function set(ref, value) {
  12634. ref = util.getModularInstance(ref);
  12635. validateWritablePath('set', ref._path);
  12636. validateFirebaseDataArg('set', value, ref._path, false);
  12637. const deferred = new util.Deferred();
  12638. repoSetWithPriority(ref._repo, ref._path, value,
  12639. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12640. return deferred.promise;
  12641. }
  12642. /**
  12643. * Sets a priority for the data at this Database location.
  12644. *
  12645. * Applications need not use priority but can order collections by
  12646. * ordinary properties (see
  12647. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12648. * ).
  12649. *
  12650. * @param ref - The location to write to.
  12651. * @param priority - The priority to be written (string, number, or null).
  12652. * @returns Resolves when write to server is complete.
  12653. */
  12654. function setPriority(ref, priority) {
  12655. ref = util.getModularInstance(ref);
  12656. validateWritablePath('setPriority', ref._path);
  12657. validatePriority('setPriority', priority, false);
  12658. const deferred = new util.Deferred();
  12659. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12660. return deferred.promise;
  12661. }
  12662. /**
  12663. * Writes data the Database location. Like `set()` but also specifies the
  12664. * priority for that data.
  12665. *
  12666. * Applications need not use priority but can order collections by
  12667. * ordinary properties (see
  12668. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12669. * ).
  12670. *
  12671. * @param ref - The location to write to.
  12672. * @param value - The value to be written (string, number, boolean, object,
  12673. * array, or null).
  12674. * @param priority - The priority to be written (string, number, or null).
  12675. * @returns Resolves when write to server is complete.
  12676. */
  12677. function setWithPriority(ref, value, priority) {
  12678. validateWritablePath('setWithPriority', ref._path);
  12679. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12680. validatePriority('setWithPriority', priority, false);
  12681. if (ref.key === '.length' || ref.key === '.keys') {
  12682. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12683. }
  12684. const deferred = new util.Deferred();
  12685. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12686. return deferred.promise;
  12687. }
  12688. /**
  12689. * Writes multiple values to the Database at once.
  12690. *
  12691. * The `values` argument contains multiple property-value pairs that will be
  12692. * written to the Database together. Each child property can either be a simple
  12693. * property (for example, "name") or a relative path (for example,
  12694. * "name/first") from the current location to the data to update.
  12695. *
  12696. * As opposed to the `set()` method, `update()` can be use to selectively update
  12697. * only the referenced properties at the current location (instead of replacing
  12698. * all the child properties at the current location).
  12699. *
  12700. * The effect of the write will be visible immediately, and the corresponding
  12701. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12702. * the data to the Firebase servers will also be started, and the returned
  12703. * Promise will resolve when complete. If provided, the `onComplete` callback
  12704. * will be called asynchronously after synchronization has finished.
  12705. *
  12706. * A single `update()` will generate a single "value" event at the location
  12707. * where the `update()` was performed, regardless of how many children were
  12708. * modified.
  12709. *
  12710. * Note that modifying data with `update()` will cancel any pending
  12711. * transactions at that location, so extreme care should be taken if mixing
  12712. * `update()` and `transaction()` to modify the same data.
  12713. *
  12714. * Passing `null` to `update()` will remove the data at this location.
  12715. *
  12716. * See
  12717. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12718. *
  12719. * @param ref - The location to write to.
  12720. * @param values - Object containing multiple values.
  12721. * @returns Resolves when update on server is complete.
  12722. */
  12723. function update(ref, values) {
  12724. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12725. const deferred = new util.Deferred();
  12726. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12727. return deferred.promise;
  12728. }
  12729. /**
  12730. * Gets the most up-to-date result for this query.
  12731. *
  12732. * @param query - The query to run.
  12733. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12734. * available, or rejects if the client is unable to return a value (e.g., if the
  12735. * server is unreachable and there is nothing cached).
  12736. */
  12737. function get(query) {
  12738. query = util.getModularInstance(query);
  12739. const callbackContext = new CallbackContext(() => { });
  12740. const container = new ValueEventRegistration(callbackContext);
  12741. return repoGetValue(query._repo, query, container).then(node => {
  12742. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12743. });
  12744. }
  12745. /**
  12746. * Represents registration for 'value' events.
  12747. */
  12748. class ValueEventRegistration {
  12749. constructor(callbackContext) {
  12750. this.callbackContext = callbackContext;
  12751. }
  12752. respondsTo(eventType) {
  12753. return eventType === 'value';
  12754. }
  12755. createEvent(change, query) {
  12756. const index = query._queryParams.getIndex();
  12757. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12758. }
  12759. getEventRunner(eventData) {
  12760. if (eventData.getEventType() === 'cancel') {
  12761. return () => this.callbackContext.onCancel(eventData.error);
  12762. }
  12763. else {
  12764. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12765. }
  12766. }
  12767. createCancelEvent(error, path) {
  12768. if (this.callbackContext.hasCancelCallback) {
  12769. return new CancelEvent(this, error, path);
  12770. }
  12771. else {
  12772. return null;
  12773. }
  12774. }
  12775. matches(other) {
  12776. if (!(other instanceof ValueEventRegistration)) {
  12777. return false;
  12778. }
  12779. else if (!other.callbackContext || !this.callbackContext) {
  12780. // If no callback specified, we consider it to match any callback.
  12781. return true;
  12782. }
  12783. else {
  12784. return other.callbackContext.matches(this.callbackContext);
  12785. }
  12786. }
  12787. hasAnyCallback() {
  12788. return this.callbackContext !== null;
  12789. }
  12790. }
  12791. /**
  12792. * Represents the registration of a child_x event.
  12793. */
  12794. class ChildEventRegistration {
  12795. constructor(eventType, callbackContext) {
  12796. this.eventType = eventType;
  12797. this.callbackContext = callbackContext;
  12798. }
  12799. respondsTo(eventType) {
  12800. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12801. eventToCheck =
  12802. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12803. return this.eventType === eventToCheck;
  12804. }
  12805. createCancelEvent(error, path) {
  12806. if (this.callbackContext.hasCancelCallback) {
  12807. return new CancelEvent(this, error, path);
  12808. }
  12809. else {
  12810. return null;
  12811. }
  12812. }
  12813. createEvent(change, query) {
  12814. util.assert(change.childName != null, 'Child events should have a childName.');
  12815. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12816. const index = query._queryParams.getIndex();
  12817. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12818. }
  12819. getEventRunner(eventData) {
  12820. if (eventData.getEventType() === 'cancel') {
  12821. return () => this.callbackContext.onCancel(eventData.error);
  12822. }
  12823. else {
  12824. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12825. }
  12826. }
  12827. matches(other) {
  12828. if (other instanceof ChildEventRegistration) {
  12829. return (this.eventType === other.eventType &&
  12830. (!this.callbackContext ||
  12831. !other.callbackContext ||
  12832. this.callbackContext.matches(other.callbackContext)));
  12833. }
  12834. return false;
  12835. }
  12836. hasAnyCallback() {
  12837. return !!this.callbackContext;
  12838. }
  12839. }
  12840. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12841. let cancelCallback;
  12842. if (typeof cancelCallbackOrListenOptions === 'object') {
  12843. cancelCallback = undefined;
  12844. options = cancelCallbackOrListenOptions;
  12845. }
  12846. if (typeof cancelCallbackOrListenOptions === 'function') {
  12847. cancelCallback = cancelCallbackOrListenOptions;
  12848. }
  12849. if (options && options.onlyOnce) {
  12850. const userCallback = callback;
  12851. const onceCallback = (dataSnapshot, previousChildName) => {
  12852. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12853. userCallback(dataSnapshot, previousChildName);
  12854. };
  12855. onceCallback.userCallback = callback.userCallback;
  12856. onceCallback.context = callback.context;
  12857. callback = onceCallback;
  12858. }
  12859. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12860. const container = eventType === 'value'
  12861. ? new ValueEventRegistration(callbackContext)
  12862. : new ChildEventRegistration(eventType, callbackContext);
  12863. repoAddEventCallbackForQuery(query._repo, query, container);
  12864. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12865. }
  12866. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12867. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12868. }
  12869. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12870. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12871. }
  12872. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12873. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12874. }
  12875. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12876. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12877. }
  12878. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12879. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12880. }
  12881. /**
  12882. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12883. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12884. * the respective `on*` callbacks.
  12885. *
  12886. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12887. * will not automatically remove listeners registered on child nodes, `off()`
  12888. * must also be called on any child listeners to remove the callback.
  12889. *
  12890. * If a callback is not specified, all callbacks for the specified eventType
  12891. * will be removed. Similarly, if no eventType is specified, all callbacks
  12892. * for the `Reference` will be removed.
  12893. *
  12894. * Individual listeners can also be removed by invoking their unsubscribe
  12895. * callbacks.
  12896. *
  12897. * @param query - The query that the listener was registered with.
  12898. * @param eventType - One of the following strings: "value", "child_added",
  12899. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12900. * for the `Reference` will be removed.
  12901. * @param callback - The callback function that was passed to `on()` or
  12902. * `undefined` to remove all callbacks.
  12903. */
  12904. function off(query, eventType, callback) {
  12905. let container = null;
  12906. const expCallback = callback ? new CallbackContext(callback) : null;
  12907. if (eventType === 'value') {
  12908. container = new ValueEventRegistration(expCallback);
  12909. }
  12910. else if (eventType) {
  12911. container = new ChildEventRegistration(eventType, expCallback);
  12912. }
  12913. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12914. }
  12915. /**
  12916. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12917. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12918. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12919. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12920. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12921. * {@link orderByValue} or {@link equalTo} and
  12922. * can then be passed to {@link query} to create a new query instance that
  12923. * also contains this `QueryConstraint`.
  12924. */
  12925. class QueryConstraint {
  12926. }
  12927. class QueryEndAtConstraint extends QueryConstraint {
  12928. constructor(_value, _key) {
  12929. super();
  12930. this._value = _value;
  12931. this._key = _key;
  12932. this.type = 'endAt';
  12933. }
  12934. _apply(query) {
  12935. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12936. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12937. validateLimit(newParams);
  12938. validateQueryEndpoints(newParams);
  12939. if (query._queryParams.hasEnd()) {
  12940. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12941. 'endBefore or equalTo).');
  12942. }
  12943. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12944. }
  12945. }
  12946. /**
  12947. * Creates a `QueryConstraint` with the specified ending point.
  12948. *
  12949. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12950. * allows you to choose arbitrary starting and ending points for your queries.
  12951. *
  12952. * The ending point is inclusive, so children with exactly the specified value
  12953. * will be included in the query. The optional key argument can be used to
  12954. * further limit the range of the query. If it is specified, then children that
  12955. * have exactly the specified value must also have a key name less than or equal
  12956. * to the specified key.
  12957. *
  12958. * You can read more about `endAt()` in
  12959. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12960. *
  12961. * @param value - The value to end at. The argument type depends on which
  12962. * `orderBy*()` function was used in this query. Specify a value that matches
  12963. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12964. * value must be a string.
  12965. * @param key - The child key to end at, among the children with the previously
  12966. * specified priority. This argument is only allowed if ordering by child,
  12967. * value, or priority.
  12968. */
  12969. function endAt(value, key) {
  12970. validateKey('endAt', 'key', key, true);
  12971. return new QueryEndAtConstraint(value, key);
  12972. }
  12973. class QueryEndBeforeConstraint extends QueryConstraint {
  12974. constructor(_value, _key) {
  12975. super();
  12976. this._value = _value;
  12977. this._key = _key;
  12978. this.type = 'endBefore';
  12979. }
  12980. _apply(query) {
  12981. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12982. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12983. validateLimit(newParams);
  12984. validateQueryEndpoints(newParams);
  12985. if (query._queryParams.hasEnd()) {
  12986. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12987. 'endBefore or equalTo).');
  12988. }
  12989. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12990. }
  12991. }
  12992. /**
  12993. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12994. *
  12995. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12996. * allows you to choose arbitrary starting and ending points for your queries.
  12997. *
  12998. * The ending point is exclusive. If only a value is provided, children
  12999. * with a value less than the specified value will be included in the query.
  13000. * If a key is specified, then children must have a value less than or equal
  13001. * to the specified value and a key name less than the specified key.
  13002. *
  13003. * @param value - The value to end before. The argument type depends on which
  13004. * `orderBy*()` function was used in this query. Specify a value that matches
  13005. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13006. * value must be a string.
  13007. * @param key - The child key to end before, among the children with the
  13008. * previously specified priority. This argument is only allowed if ordering by
  13009. * child, value, or priority.
  13010. */
  13011. function endBefore(value, key) {
  13012. validateKey('endBefore', 'key', key, true);
  13013. return new QueryEndBeforeConstraint(value, key);
  13014. }
  13015. class QueryStartAtConstraint extends QueryConstraint {
  13016. constructor(_value, _key) {
  13017. super();
  13018. this._value = _value;
  13019. this._key = _key;
  13020. this.type = 'startAt';
  13021. }
  13022. _apply(query) {
  13023. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13024. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13025. validateLimit(newParams);
  13026. validateQueryEndpoints(newParams);
  13027. if (query._queryParams.hasStart()) {
  13028. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13029. 'startBefore or equalTo).');
  13030. }
  13031. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13032. }
  13033. }
  13034. /**
  13035. * Creates a `QueryConstraint` with the specified starting point.
  13036. *
  13037. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13038. * allows you to choose arbitrary starting and ending points for your queries.
  13039. *
  13040. * The starting point is inclusive, so children with exactly the specified value
  13041. * will be included in the query. The optional key argument can be used to
  13042. * further limit the range of the query. If it is specified, then children that
  13043. * have exactly the specified value must also have a key name greater than or
  13044. * equal to the specified key.
  13045. *
  13046. * You can read more about `startAt()` in
  13047. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13048. *
  13049. * @param value - The value to start at. The argument type depends on which
  13050. * `orderBy*()` function was used in this query. Specify a value that matches
  13051. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13052. * value must be a string.
  13053. * @param key - The child key to start at. This argument is only allowed if
  13054. * ordering by child, value, or priority.
  13055. */
  13056. function startAt(value = null, key) {
  13057. validateKey('startAt', 'key', key, true);
  13058. return new QueryStartAtConstraint(value, key);
  13059. }
  13060. class QueryStartAfterConstraint extends QueryConstraint {
  13061. constructor(_value, _key) {
  13062. super();
  13063. this._value = _value;
  13064. this._key = _key;
  13065. this.type = 'startAfter';
  13066. }
  13067. _apply(query) {
  13068. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13069. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13070. validateLimit(newParams);
  13071. validateQueryEndpoints(newParams);
  13072. if (query._queryParams.hasStart()) {
  13073. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13074. 'startAfter, or equalTo).');
  13075. }
  13076. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13077. }
  13078. }
  13079. /**
  13080. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13081. *
  13082. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13083. * allows you to choose arbitrary starting and ending points for your queries.
  13084. *
  13085. * The starting point is exclusive. If only a value is provided, children
  13086. * with a value greater than the specified value will be included in the query.
  13087. * If a key is specified, then children must have a value greater than or equal
  13088. * to the specified value and a a key name greater than the specified key.
  13089. *
  13090. * @param value - The value to start after. The argument type depends on which
  13091. * `orderBy*()` function was used in this query. Specify a value that matches
  13092. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13093. * value must be a string.
  13094. * @param key - The child key to start after. This argument is only allowed if
  13095. * ordering by child, value, or priority.
  13096. */
  13097. function startAfter(value, key) {
  13098. validateKey('startAfter', 'key', key, true);
  13099. return new QueryStartAfterConstraint(value, key);
  13100. }
  13101. class QueryLimitToFirstConstraint extends QueryConstraint {
  13102. constructor(_limit) {
  13103. super();
  13104. this._limit = _limit;
  13105. this.type = 'limitToFirst';
  13106. }
  13107. _apply(query) {
  13108. if (query._queryParams.hasLimit()) {
  13109. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13110. 'or limitToLast).');
  13111. }
  13112. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13113. }
  13114. }
  13115. /**
  13116. * Creates a new `QueryConstraint` that if limited to the first specific number
  13117. * of children.
  13118. *
  13119. * The `limitToFirst()` method is used to set a maximum number of children to be
  13120. * synced for a given callback. If we set a limit of 100, we will initially only
  13121. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13122. * stored in our Database, a `child_added` event will fire for each message.
  13123. * However, if we have over 100 messages, we will only receive a `child_added`
  13124. * event for the first 100 ordered messages. As items change, we will receive
  13125. * `child_removed` events for each item that drops out of the active list so
  13126. * that the total number stays at 100.
  13127. *
  13128. * You can read more about `limitToFirst()` in
  13129. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13130. *
  13131. * @param limit - The maximum number of nodes to include in this query.
  13132. */
  13133. function limitToFirst(limit) {
  13134. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13135. throw new Error('limitToFirst: First argument must be a positive integer.');
  13136. }
  13137. return new QueryLimitToFirstConstraint(limit);
  13138. }
  13139. class QueryLimitToLastConstraint extends QueryConstraint {
  13140. constructor(_limit) {
  13141. super();
  13142. this._limit = _limit;
  13143. this.type = 'limitToLast';
  13144. }
  13145. _apply(query) {
  13146. if (query._queryParams.hasLimit()) {
  13147. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13148. 'or limitToLast).');
  13149. }
  13150. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13151. }
  13152. }
  13153. /**
  13154. * Creates a new `QueryConstraint` that is limited to return only the last
  13155. * specified number of children.
  13156. *
  13157. * The `limitToLast()` method is used to set a maximum number of children to be
  13158. * synced for a given callback. If we set a limit of 100, we will initially only
  13159. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13160. * stored in our Database, a `child_added` event will fire for each message.
  13161. * However, if we have over 100 messages, we will only receive a `child_added`
  13162. * event for the last 100 ordered messages. As items change, we will receive
  13163. * `child_removed` events for each item that drops out of the active list so
  13164. * that the total number stays at 100.
  13165. *
  13166. * You can read more about `limitToLast()` in
  13167. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13168. *
  13169. * @param limit - The maximum number of nodes to include in this query.
  13170. */
  13171. function limitToLast(limit) {
  13172. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13173. throw new Error('limitToLast: First argument must be a positive integer.');
  13174. }
  13175. return new QueryLimitToLastConstraint(limit);
  13176. }
  13177. class QueryOrderByChildConstraint extends QueryConstraint {
  13178. constructor(_path) {
  13179. super();
  13180. this._path = _path;
  13181. this.type = 'orderByChild';
  13182. }
  13183. _apply(query) {
  13184. validateNoPreviousOrderByCall(query, 'orderByChild');
  13185. const parsedPath = new Path(this._path);
  13186. if (pathIsEmpty(parsedPath)) {
  13187. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13188. }
  13189. const index = new PathIndex(parsedPath);
  13190. const newParams = queryParamsOrderBy(query._queryParams, index);
  13191. validateQueryEndpoints(newParams);
  13192. return new QueryImpl(query._repo, query._path, newParams,
  13193. /*orderByCalled=*/ true);
  13194. }
  13195. }
  13196. /**
  13197. * Creates a new `QueryConstraint` that orders by the specified child key.
  13198. *
  13199. * Queries can only order by one key at a time. Calling `orderByChild()`
  13200. * multiple times on the same query is an error.
  13201. *
  13202. * Firebase queries allow you to order your data by any child key on the fly.
  13203. * However, if you know in advance what your indexes will be, you can define
  13204. * them via the .indexOn rule in your Security Rules for better performance. See
  13205. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13206. * rule for more information.
  13207. *
  13208. * You can read more about `orderByChild()` in
  13209. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13210. *
  13211. * @param path - The path to order by.
  13212. */
  13213. function orderByChild(path) {
  13214. if (path === '$key') {
  13215. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13216. }
  13217. else if (path === '$priority') {
  13218. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13219. }
  13220. else if (path === '$value') {
  13221. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13222. }
  13223. validatePathString('orderByChild', 'path', path, false);
  13224. return new QueryOrderByChildConstraint(path);
  13225. }
  13226. class QueryOrderByKeyConstraint extends QueryConstraint {
  13227. constructor() {
  13228. super(...arguments);
  13229. this.type = 'orderByKey';
  13230. }
  13231. _apply(query) {
  13232. validateNoPreviousOrderByCall(query, 'orderByKey');
  13233. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13234. validateQueryEndpoints(newParams);
  13235. return new QueryImpl(query._repo, query._path, newParams,
  13236. /*orderByCalled=*/ true);
  13237. }
  13238. }
  13239. /**
  13240. * Creates a new `QueryConstraint` that orders by the key.
  13241. *
  13242. * Sorts the results of a query by their (ascending) key values.
  13243. *
  13244. * You can read more about `orderByKey()` in
  13245. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13246. */
  13247. function orderByKey() {
  13248. return new QueryOrderByKeyConstraint();
  13249. }
  13250. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13251. constructor() {
  13252. super(...arguments);
  13253. this.type = 'orderByPriority';
  13254. }
  13255. _apply(query) {
  13256. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13257. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13258. validateQueryEndpoints(newParams);
  13259. return new QueryImpl(query._repo, query._path, newParams,
  13260. /*orderByCalled=*/ true);
  13261. }
  13262. }
  13263. /**
  13264. * Creates a new `QueryConstraint` that orders by priority.
  13265. *
  13266. * Applications need not use priority but can order collections by
  13267. * ordinary properties (see
  13268. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13269. * for alternatives to priority.
  13270. */
  13271. function orderByPriority() {
  13272. return new QueryOrderByPriorityConstraint();
  13273. }
  13274. class QueryOrderByValueConstraint extends QueryConstraint {
  13275. constructor() {
  13276. super(...arguments);
  13277. this.type = 'orderByValue';
  13278. }
  13279. _apply(query) {
  13280. validateNoPreviousOrderByCall(query, 'orderByValue');
  13281. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13282. validateQueryEndpoints(newParams);
  13283. return new QueryImpl(query._repo, query._path, newParams,
  13284. /*orderByCalled=*/ true);
  13285. }
  13286. }
  13287. /**
  13288. * Creates a new `QueryConstraint` that orders by value.
  13289. *
  13290. * If the children of a query are all scalar values (string, number, or
  13291. * boolean), you can order the results by their (ascending) values.
  13292. *
  13293. * You can read more about `orderByValue()` in
  13294. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13295. */
  13296. function orderByValue() {
  13297. return new QueryOrderByValueConstraint();
  13298. }
  13299. class QueryEqualToValueConstraint extends QueryConstraint {
  13300. constructor(_value, _key) {
  13301. super();
  13302. this._value = _value;
  13303. this._key = _key;
  13304. this.type = 'equalTo';
  13305. }
  13306. _apply(query) {
  13307. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13308. if (query._queryParams.hasStart()) {
  13309. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13310. 'equalTo).');
  13311. }
  13312. if (query._queryParams.hasEnd()) {
  13313. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13314. 'equalTo).');
  13315. }
  13316. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13317. }
  13318. }
  13319. /**
  13320. * Creates a `QueryConstraint` that includes children that match the specified
  13321. * value.
  13322. *
  13323. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13324. * allows you to choose arbitrary starting and ending points for your queries.
  13325. *
  13326. * The optional key argument can be used to further limit the range of the
  13327. * query. If it is specified, then children that have exactly the specified
  13328. * value must also have exactly the specified key as their key name. This can be
  13329. * used to filter result sets with many matches for the same value.
  13330. *
  13331. * You can read more about `equalTo()` in
  13332. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13333. *
  13334. * @param value - The value to match for. The argument type depends on which
  13335. * `orderBy*()` function was used in this query. Specify a value that matches
  13336. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13337. * value must be a string.
  13338. * @param key - The child key to start at, among the children with the
  13339. * previously specified priority. This argument is only allowed if ordering by
  13340. * child, value, or priority.
  13341. */
  13342. function equalTo(value, key) {
  13343. validateKey('equalTo', 'key', key, true);
  13344. return new QueryEqualToValueConstraint(value, key);
  13345. }
  13346. /**
  13347. * Creates a new immutable instance of `Query` that is extended to also include
  13348. * additional query constraints.
  13349. *
  13350. * @param query - The Query instance to use as a base for the new constraints.
  13351. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13352. * @throws if any of the provided query constraints cannot be combined with the
  13353. * existing or new constraints.
  13354. */
  13355. function query(query, ...queryConstraints) {
  13356. let queryImpl = util.getModularInstance(query);
  13357. for (const constraint of queryConstraints) {
  13358. queryImpl = constraint._apply(queryImpl);
  13359. }
  13360. return queryImpl;
  13361. }
  13362. /**
  13363. * Define reference constructor in various modules
  13364. *
  13365. * We are doing this here to avoid several circular
  13366. * dependency issues
  13367. */
  13368. syncPointSetReferenceConstructor(ReferenceImpl);
  13369. syncTreeSetReferenceConstructor(ReferenceImpl);
  13370. /**
  13371. * @license
  13372. * Copyright 2020 Google LLC
  13373. *
  13374. * Licensed under the Apache License, Version 2.0 (the "License");
  13375. * you may not use this file except in compliance with the License.
  13376. * You may obtain a copy of the License at
  13377. *
  13378. * http://www.apache.org/licenses/LICENSE-2.0
  13379. *
  13380. * Unless required by applicable law or agreed to in writing, software
  13381. * distributed under the License is distributed on an "AS IS" BASIS,
  13382. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13383. * See the License for the specific language governing permissions and
  13384. * limitations under the License.
  13385. */
  13386. /**
  13387. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13388. * modifying this definition, consult the definition in:
  13389. *
  13390. * https://github.com/firebase/firebase-admin-node
  13391. *
  13392. * and make sure the two are consistent.
  13393. */
  13394. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13395. /**
  13396. * Creates and caches `Repo` instances.
  13397. */
  13398. const repos = {};
  13399. /**
  13400. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13401. */
  13402. let useRestClient = false;
  13403. /**
  13404. * Update an existing `Repo` in place to point to a new host/port.
  13405. */
  13406. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13407. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13408. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13409. /*isUsingEmulator=*/ true);
  13410. if (tokenProvider) {
  13411. repo.authTokenProvider_ = tokenProvider;
  13412. }
  13413. }
  13414. /**
  13415. * This function should only ever be called to CREATE a new database instance.
  13416. * @internal
  13417. */
  13418. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13419. let dbUrl = url || app.options.databaseURL;
  13420. if (dbUrl === undefined) {
  13421. if (!app.options.projectId) {
  13422. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13423. ' a Project ID when calling firebase.initializeApp().');
  13424. }
  13425. log('Using default host for project ', app.options.projectId);
  13426. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13427. }
  13428. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13429. let repoInfo = parsedUrl.repoInfo;
  13430. let isEmulator;
  13431. let dbEmulatorHost = undefined;
  13432. if (typeof process !== 'undefined' && process.env) {
  13433. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13434. }
  13435. if (dbEmulatorHost) {
  13436. isEmulator = true;
  13437. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13438. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13439. repoInfo = parsedUrl.repoInfo;
  13440. }
  13441. else {
  13442. isEmulator = !parsedUrl.repoInfo.secure;
  13443. }
  13444. const authTokenProvider = nodeAdmin && isEmulator
  13445. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13446. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13447. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13448. if (!pathIsEmpty(parsedUrl.path)) {
  13449. fatal('Database URL must point to the root of a Firebase Database ' +
  13450. '(not including a child path).');
  13451. }
  13452. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13453. return new Database(repo, app);
  13454. }
  13455. /**
  13456. * Remove the repo and make sure it is disconnected.
  13457. *
  13458. */
  13459. function repoManagerDeleteRepo(repo, appName) {
  13460. const appRepos = repos[appName];
  13461. // This should never happen...
  13462. if (!appRepos || appRepos[repo.key] !== repo) {
  13463. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13464. }
  13465. repoInterrupt(repo);
  13466. delete appRepos[repo.key];
  13467. }
  13468. /**
  13469. * Ensures a repo doesn't already exist and then creates one using the
  13470. * provided app.
  13471. *
  13472. * @param repoInfo - The metadata about the Repo
  13473. * @returns The Repo object for the specified server / repoName.
  13474. */
  13475. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13476. let appRepos = repos[app.name];
  13477. if (!appRepos) {
  13478. appRepos = {};
  13479. repos[app.name] = appRepos;
  13480. }
  13481. let repo = appRepos[repoInfo.toURLString()];
  13482. if (repo) {
  13483. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13484. }
  13485. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13486. appRepos[repoInfo.toURLString()] = repo;
  13487. return repo;
  13488. }
  13489. /**
  13490. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13491. */
  13492. function repoManagerForceRestClient(forceRestClient) {
  13493. useRestClient = forceRestClient;
  13494. }
  13495. /**
  13496. * Class representing a Firebase Realtime Database.
  13497. */
  13498. class Database {
  13499. /** @hideconstructor */
  13500. constructor(_repoInternal,
  13501. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13502. app) {
  13503. this._repoInternal = _repoInternal;
  13504. this.app = app;
  13505. /** Represents a `Database` instance. */
  13506. this['type'] = 'database';
  13507. /** Track if the instance has been used (root or repo accessed) */
  13508. this._instanceStarted = false;
  13509. }
  13510. get _repo() {
  13511. if (!this._instanceStarted) {
  13512. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13513. this._instanceStarted = true;
  13514. }
  13515. return this._repoInternal;
  13516. }
  13517. get _root() {
  13518. if (!this._rootInternal) {
  13519. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13520. }
  13521. return this._rootInternal;
  13522. }
  13523. _delete() {
  13524. if (this._rootInternal !== null) {
  13525. repoManagerDeleteRepo(this._repo, this.app.name);
  13526. this._repoInternal = null;
  13527. this._rootInternal = null;
  13528. }
  13529. return Promise.resolve();
  13530. }
  13531. _checkNotDeleted(apiName) {
  13532. if (this._rootInternal === null) {
  13533. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13534. }
  13535. }
  13536. }
  13537. function checkTransportInit() {
  13538. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13539. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13540. }
  13541. }
  13542. /**
  13543. * Force the use of websockets instead of longPolling.
  13544. */
  13545. function forceWebSockets() {
  13546. checkTransportInit();
  13547. BrowserPollConnection.forceDisallow();
  13548. }
  13549. /**
  13550. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13551. */
  13552. function forceLongPolling() {
  13553. checkTransportInit();
  13554. WebSocketConnection.forceDisallow();
  13555. BrowserPollConnection.forceAllow();
  13556. }
  13557. /**
  13558. * Returns the instance of the Realtime Database SDK that is associated with the provided
  13559. * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if
  13560. * no instance exists or if the existing instance uses a custom database URL.
  13561. *
  13562. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13563. * Database instance is associated with.
  13564. * @param url - The URL of the Realtime Database instance to connect to. If not
  13565. * provided, the SDK connects to the default instance of the Firebase App.
  13566. * @returns The `Database` instance of the provided app.
  13567. */
  13568. function getDatabase(app$1 = app.getApp(), url) {
  13569. const db = app._getProvider(app$1, 'database').getImmediate({
  13570. identifier: url
  13571. });
  13572. if (!db._instanceStarted) {
  13573. const emulator = util.getDefaultEmulatorHostnameAndPort('database');
  13574. if (emulator) {
  13575. connectDatabaseEmulator(db, ...emulator);
  13576. }
  13577. }
  13578. return db;
  13579. }
  13580. /**
  13581. * Modify the provided instance to communicate with the Realtime Database
  13582. * emulator.
  13583. *
  13584. * <p>Note: This method must be called before performing any other operation.
  13585. *
  13586. * @param db - The instance to modify.
  13587. * @param host - The emulator host (ex: localhost)
  13588. * @param port - The emulator port (ex: 8080)
  13589. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13590. */
  13591. function connectDatabaseEmulator(db, host, port, options = {}) {
  13592. db = util.getModularInstance(db);
  13593. db._checkNotDeleted('useEmulator');
  13594. if (db._instanceStarted) {
  13595. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13596. }
  13597. const repo = db._repoInternal;
  13598. let tokenProvider = undefined;
  13599. if (repo.repoInfo_.nodeAdmin) {
  13600. if (options.mockUserToken) {
  13601. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13602. }
  13603. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13604. }
  13605. else if (options.mockUserToken) {
  13606. const token = typeof options.mockUserToken === 'string'
  13607. ? options.mockUserToken
  13608. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13609. tokenProvider = new EmulatorTokenProvider(token);
  13610. }
  13611. // Modify the repo to apply emulator settings
  13612. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13613. }
  13614. /**
  13615. * Disconnects from the server (all Database operations will be completed
  13616. * offline).
  13617. *
  13618. * The client automatically maintains a persistent connection to the Database
  13619. * server, which will remain active indefinitely and reconnect when
  13620. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13621. * to control the client connection in cases where a persistent connection is
  13622. * undesirable.
  13623. *
  13624. * While offline, the client will no longer receive data updates from the
  13625. * Database. However, all Database operations performed locally will continue to
  13626. * immediately fire events, allowing your application to continue behaving
  13627. * normally. Additionally, each operation performed locally will automatically
  13628. * be queued and retried upon reconnection to the Database server.
  13629. *
  13630. * To reconnect to the Database and begin receiving remote events, see
  13631. * `goOnline()`.
  13632. *
  13633. * @param db - The instance to disconnect.
  13634. */
  13635. function goOffline(db) {
  13636. db = util.getModularInstance(db);
  13637. db._checkNotDeleted('goOffline');
  13638. repoInterrupt(db._repo);
  13639. }
  13640. /**
  13641. * Reconnects to the server and synchronizes the offline Database state
  13642. * with the server state.
  13643. *
  13644. * This method should be used after disabling the active connection with
  13645. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13646. * and fire the appropriate events so that your client "catches up"
  13647. * automatically.
  13648. *
  13649. * @param db - The instance to reconnect.
  13650. */
  13651. function goOnline(db) {
  13652. db = util.getModularInstance(db);
  13653. db._checkNotDeleted('goOnline');
  13654. repoResume(db._repo);
  13655. }
  13656. function enableLogging(logger, persistent) {
  13657. enableLogging$1(logger, persistent);
  13658. }
  13659. /**
  13660. * @license
  13661. * Copyright 2021 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. function registerDatabase(variant) {
  13676. setSDKVersion(app.SDK_VERSION);
  13677. app._registerComponent(new component.Component('database', (container, { instanceIdentifier: url }) => {
  13678. const app = container.getProvider('app').getImmediate();
  13679. const authProvider = container.getProvider('auth-internal');
  13680. const appCheckProvider = container.getProvider('app-check-internal');
  13681. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13682. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13683. app.registerVersion(name, version, variant);
  13684. // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  13685. app.registerVersion(name, version, 'cjs2017');
  13686. }
  13687. /**
  13688. * @license
  13689. * Copyright 2020 Google LLC
  13690. *
  13691. * Licensed under the Apache License, Version 2.0 (the "License");
  13692. * you may not use this file except in compliance with the License.
  13693. * You may obtain a copy of the License at
  13694. *
  13695. * http://www.apache.org/licenses/LICENSE-2.0
  13696. *
  13697. * Unless required by applicable law or agreed to in writing, software
  13698. * distributed under the License is distributed on an "AS IS" BASIS,
  13699. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13700. * See the License for the specific language governing permissions and
  13701. * limitations under the License.
  13702. */
  13703. const SERVER_TIMESTAMP = {
  13704. '.sv': 'timestamp'
  13705. };
  13706. /**
  13707. * Returns a placeholder value for auto-populating the current timestamp (time
  13708. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13709. * servers.
  13710. */
  13711. function serverTimestamp() {
  13712. return SERVER_TIMESTAMP;
  13713. }
  13714. /**
  13715. * Returns a placeholder value that can be used to atomically increment the
  13716. * current database value by the provided delta.
  13717. *
  13718. * @param delta - the amount to modify the current value atomically.
  13719. * @returns A placeholder value for modifying data atomically server-side.
  13720. */
  13721. function increment(delta) {
  13722. return {
  13723. '.sv': {
  13724. 'increment': delta
  13725. }
  13726. };
  13727. }
  13728. /**
  13729. * @license
  13730. * Copyright 2020 Google LLC
  13731. *
  13732. * Licensed under the Apache License, Version 2.0 (the "License");
  13733. * you may not use this file except in compliance with the License.
  13734. * You may obtain a copy of the License at
  13735. *
  13736. * http://www.apache.org/licenses/LICENSE-2.0
  13737. *
  13738. * Unless required by applicable law or agreed to in writing, software
  13739. * distributed under the License is distributed on an "AS IS" BASIS,
  13740. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13741. * See the License for the specific language governing permissions and
  13742. * limitations under the License.
  13743. */
  13744. /**
  13745. * A type for the resolve value of {@link runTransaction}.
  13746. */
  13747. class TransactionResult {
  13748. /** @hideconstructor */
  13749. constructor(
  13750. /** Whether the transaction was successfully committed. */
  13751. committed,
  13752. /** The resulting data snapshot. */
  13753. snapshot) {
  13754. this.committed = committed;
  13755. this.snapshot = snapshot;
  13756. }
  13757. /** Returns a JSON-serializable representation of this object. */
  13758. toJSON() {
  13759. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13760. }
  13761. }
  13762. /**
  13763. * Atomically modifies the data at this location.
  13764. *
  13765. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13766. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13767. * used to modify the existing value to a new value, ensuring there are no
  13768. * conflicts with other clients writing to the same location at the same time.
  13769. *
  13770. * To accomplish this, you pass `runTransaction()` an update function which is
  13771. * used to transform the current value into a new value. If another client
  13772. * writes to the location before your new value is successfully written, your
  13773. * update function will be called again with the new current value, and the
  13774. * write will be retried. This will happen repeatedly until your write succeeds
  13775. * without conflict or you abort the transaction by not returning a value from
  13776. * your update function.
  13777. *
  13778. * Note: Modifying data with `set()` will cancel any pending transactions at
  13779. * that location, so extreme care should be taken if mixing `set()` and
  13780. * `runTransaction()` to update the same data.
  13781. *
  13782. * Note: When using transactions with Security and Firebase Rules in place, be
  13783. * aware that a client needs `.read` access in addition to `.write` access in
  13784. * order to perform a transaction. This is because the client-side nature of
  13785. * transactions requires the client to read the data in order to transactionally
  13786. * update it.
  13787. *
  13788. * @param ref - The location to atomically modify.
  13789. * @param transactionUpdate - A developer-supplied function which will be passed
  13790. * the current data stored at this location (as a JavaScript object). The
  13791. * function should return the new value it would like written (as a JavaScript
  13792. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13793. * transaction will be aborted and the data at this location will not be
  13794. * modified.
  13795. * @param options - An options object to configure transactions.
  13796. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13797. * callback to handle success and failure.
  13798. */
  13799. function runTransaction(ref,
  13800. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13801. transactionUpdate, options) {
  13802. var _a;
  13803. ref = util.getModularInstance(ref);
  13804. validateWritablePath('Reference.transaction', ref._path);
  13805. if (ref.key === '.length' || ref.key === '.keys') {
  13806. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13807. }
  13808. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13809. const deferred = new util.Deferred();
  13810. const promiseComplete = (error, committed, node) => {
  13811. let dataSnapshot = null;
  13812. if (error) {
  13813. deferred.reject(error);
  13814. }
  13815. else {
  13816. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13817. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13818. }
  13819. };
  13820. // Add a watch to make sure we get server updates.
  13821. const unwatcher = onValue(ref, () => { });
  13822. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13823. return deferred.promise;
  13824. }
  13825. /**
  13826. * @license
  13827. * Copyright 2017 Google LLC
  13828. *
  13829. * Licensed under the Apache License, Version 2.0 (the "License");
  13830. * you may not use this file except in compliance with the License.
  13831. * You may obtain a copy of the License at
  13832. *
  13833. * http://www.apache.org/licenses/LICENSE-2.0
  13834. *
  13835. * Unless required by applicable law or agreed to in writing, software
  13836. * distributed under the License is distributed on an "AS IS" BASIS,
  13837. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13838. * See the License for the specific language governing permissions and
  13839. * limitations under the License.
  13840. */
  13841. PersistentConnection;
  13842. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13843. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13844. this.sendRequest('q', { p: pathString }, onComplete);
  13845. };
  13846. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13847. PersistentConnection.prototype.echo = function (data, onEcho) {
  13848. this.sendRequest('echo', { d: data }, onEcho);
  13849. };
  13850. // RealTimeConnection properties that we use in tests.
  13851. Connection;
  13852. /**
  13853. * @internal
  13854. */
  13855. const hijackHash = function (newHash) {
  13856. const oldPut = PersistentConnection.prototype.put;
  13857. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13858. if (hash !== undefined) {
  13859. hash = newHash();
  13860. }
  13861. oldPut.call(this, pathString, data, onComplete, hash);
  13862. };
  13863. return function () {
  13864. PersistentConnection.prototype.put = oldPut;
  13865. };
  13866. };
  13867. RepoInfo;
  13868. /**
  13869. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13870. * @internal
  13871. */
  13872. const forceRestClient = function (forceRestClient) {
  13873. repoManagerForceRestClient(forceRestClient);
  13874. };
  13875. /**
  13876. * @license
  13877. * Copyright 2023 Google LLC
  13878. *
  13879. * Licensed under the Apache License, Version 2.0 (the "License");
  13880. * you may not use this file except in compliance with the License.
  13881. * You may obtain a copy of the License at
  13882. *
  13883. * http://www.apache.org/licenses/LICENSE-2.0
  13884. *
  13885. * Unless required by applicable law or agreed to in writing, software
  13886. * distributed under the License is distributed on an "AS IS" BASIS,
  13887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13888. * See the License for the specific language governing permissions and
  13889. * limitations under the License.
  13890. */
  13891. /**
  13892. * Used by console to create a database based on the app,
  13893. * passed database URL and a custom auth implementation.
  13894. * @internal
  13895. * @param app - A valid FirebaseApp-like object
  13896. * @param url - A valid Firebase databaseURL
  13897. * @param version - custom version e.g. firebase-admin version
  13898. * @param customAppCheckImpl - custom app check implementation
  13899. * @param customAuthImpl - custom auth implementation
  13900. */
  13901. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  13902. setSDKVersion(version);
  13903. /**
  13904. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  13905. * any actual function.
  13906. */
  13907. const componentContainer = new component.ComponentContainer('database-standalone');
  13908. const authProvider = new component.Provider('auth-internal', componentContainer);
  13909. let appCheckProvider;
  13910. if (customAppCheckImpl) {
  13911. appCheckProvider = new component.Provider('app-check-internal', componentContainer);
  13912. appCheckProvider.setComponent(new component.Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13913. }
  13914. authProvider.setComponent(new component.Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13915. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  13916. }
  13917. /**
  13918. * Firebase Realtime Database
  13919. *
  13920. * @packageDocumentation
  13921. */
  13922. registerDatabase();
  13923. exports.DataSnapshot = DataSnapshot;
  13924. exports.Database = Database;
  13925. exports.OnDisconnect = OnDisconnect;
  13926. exports.QueryConstraint = QueryConstraint;
  13927. exports.TransactionResult = TransactionResult;
  13928. exports._QueryImpl = QueryImpl;
  13929. exports._QueryParams = QueryParams;
  13930. exports._ReferenceImpl = ReferenceImpl;
  13931. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  13932. exports._TEST_ACCESS_hijackHash = hijackHash;
  13933. exports._initStandalone = _initStandalone;
  13934. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  13935. exports._setSDKVersion = setSDKVersion;
  13936. exports._validatePathString = validatePathString;
  13937. exports._validateWritablePath = validateWritablePath;
  13938. exports.child = child;
  13939. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  13940. exports.enableLogging = enableLogging;
  13941. exports.endAt = endAt;
  13942. exports.endBefore = endBefore;
  13943. exports.equalTo = equalTo;
  13944. exports.forceLongPolling = forceLongPolling;
  13945. exports.forceWebSockets = forceWebSockets;
  13946. exports.get = get;
  13947. exports.getDatabase = getDatabase;
  13948. exports.goOffline = goOffline;
  13949. exports.goOnline = goOnline;
  13950. exports.increment = increment;
  13951. exports.limitToFirst = limitToFirst;
  13952. exports.limitToLast = limitToLast;
  13953. exports.off = off;
  13954. exports.onChildAdded = onChildAdded;
  13955. exports.onChildChanged = onChildChanged;
  13956. exports.onChildMoved = onChildMoved;
  13957. exports.onChildRemoved = onChildRemoved;
  13958. exports.onDisconnect = onDisconnect;
  13959. exports.onValue = onValue;
  13960. exports.orderByChild = orderByChild;
  13961. exports.orderByKey = orderByKey;
  13962. exports.orderByPriority = orderByPriority;
  13963. exports.orderByValue = orderByValue;
  13964. exports.push = push;
  13965. exports.query = query;
  13966. exports.ref = ref;
  13967. exports.refFromURL = refFromURL;
  13968. exports.remove = remove;
  13969. exports.runTransaction = runTransaction;
  13970. exports.serverTimestamp = serverTimestamp;
  13971. exports.set = set;
  13972. exports.setPriority = setPriority;
  13973. exports.setWithPriority = setWithPriority;
  13974. exports.startAfter = startAfter;
  13975. exports.startAt = startAt;
  13976. exports.update = update;
  13977. //# sourceMappingURL=index.cjs.js.map