12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936 |
- import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
- import { Component } from '@firebase/component';
- import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
- import { Logger, LogLevel } from '@firebase/logger';
-
- const name = "@firebase/database";
- const version = "0.14.1";
-
-
-
- let SDK_VERSION = '';
-
- function setSDKVersion(version) {
- SDK_VERSION = version;
- }
-
-
-
- class DOMStorageWrapper {
-
-
- constructor(domStorage_) {
- this.domStorage_ = domStorage_;
-
- this.prefix_ = 'firebase:';
- }
-
-
- set(key, value) {
- if (value == null) {
- this.domStorage_.removeItem(this.prefixedName_(key));
- }
- else {
- this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
- }
- }
-
-
- get(key) {
- const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
- if (storedVal == null) {
- return null;
- }
- else {
- return jsonEval(storedVal);
- }
- }
- remove(key) {
- this.domStorage_.removeItem(this.prefixedName_(key));
- }
- prefixedName_(name) {
- return this.prefix_ + name;
- }
- toString() {
- return this.domStorage_.toString();
- }
- }
-
-
-
- class MemoryStorage {
- constructor() {
- this.cache_ = {};
- this.isInMemoryStorage = true;
- }
- set(key, value) {
- if (value == null) {
- delete this.cache_[key];
- }
- else {
- this.cache_[key] = value;
- }
- }
- get(key) {
- if (contains(this.cache_, key)) {
- return this.cache_[key];
- }
- return null;
- }
- remove(key) {
- delete this.cache_[key];
- }
- }
-
-
-
- const createStoragefor = function (domStorageName) {
- try {
-
-
- if (typeof window !== 'undefined' &&
- typeof window[domStorageName] !== 'undefined') {
-
- const domStorage = window[domStorageName];
- domStorage.setItem('firebase:sentinel', 'cache');
- domStorage.removeItem('firebase:sentinel');
- return new DOMStorageWrapper(domStorage);
- }
- }
- catch (e) { }
-
-
- return new MemoryStorage();
- };
-
- const PersistentStorage = createStoragefor('localStorage');
-
- const SessionStorage = createStoragefor('sessionStorage');
-
-
- const logClient = new Logger('@firebase/database');
-
- const LUIDGenerator = (function () {
- let id = 1;
- return function () {
- return id++;
- };
- })();
-
- const sha1 = function (str) {
- const utf8Bytes = stringToByteArray(str);
- const sha1 = new Sha1();
- sha1.update(utf8Bytes);
- const sha1Bytes = sha1.digest();
- return base64.encodeByteArray(sha1Bytes);
- };
- const buildLogMessage_ = function (...varArgs) {
- let message = '';
- for (let i = 0; i < varArgs.length; i++) {
- const arg = varArgs[i];
- if (Array.isArray(arg) ||
- (arg &&
- typeof arg === 'object' &&
-
- typeof arg.length === 'number')) {
- message += buildLogMessage_.apply(null, arg);
- }
- else if (typeof arg === 'object') {
- message += stringify(arg);
- }
- else {
- message += arg;
- }
- message += ' ';
- }
- return message;
- };
-
- let logger = null;
-
- let firstLog_ = true;
-
- const enableLogging$1 = function (logger_, persistent) {
- assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
- if (logger_ === true) {
- logClient.logLevel = LogLevel.VERBOSE;
- logger = logClient.log.bind(logClient);
- if (persistent) {
- SessionStorage.set('logging_enabled', true);
- }
- }
- else if (typeof logger_ === 'function') {
- logger = logger_;
- }
- else {
- logger = null;
- SessionStorage.remove('logging_enabled');
- }
- };
- const log = function (...varArgs) {
- if (firstLog_ === true) {
- firstLog_ = false;
- if (logger === null && SessionStorage.get('logging_enabled') === true) {
- enableLogging$1(true);
- }
- }
- if (logger) {
- const message = buildLogMessage_.apply(null, varArgs);
- logger(message);
- }
- };
- const logWrapper = function (prefix) {
- return function (...varArgs) {
- log(prefix, ...varArgs);
- };
- };
- const error = function (...varArgs) {
- const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
- logClient.error(message);
- };
- const fatal = function (...varArgs) {
- const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
- logClient.error(message);
- throw new Error(message);
- };
- const warn = function (...varArgs) {
- const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
- logClient.warn(message);
- };
-
- const warnIfPageIsSecure = function () {
-
- if (typeof window !== 'undefined' &&
- window.location &&
- window.location.protocol &&
- window.location.protocol.indexOf('https:') !== -1) {
- warn('Insecure Firebase access from a secure page. ' +
- 'Please use https in calls to new Firebase().');
- }
- };
-
- const isInvalidJSONNumber = function (data) {
- return (typeof data === 'number' &&
- (data !== data ||
- data === Number.POSITIVE_INFINITY ||
- data === Number.NEGATIVE_INFINITY));
- };
- const executeWhenDOMReady = function (fn) {
- if (isNodeSdk() || document.readyState === 'complete') {
- fn();
- }
- else {
-
-
- let called = false;
- const wrappedFn = function () {
- if (!document.body) {
- setTimeout(wrappedFn, Math.floor(10));
- return;
- }
- if (!called) {
- called = true;
- fn();
- }
- };
- if (document.addEventListener) {
- document.addEventListener('DOMContentLoaded', wrappedFn, false);
-
- window.addEventListener('load', wrappedFn, false);
-
- }
- else if (document.attachEvent) {
-
-
- document.attachEvent('onreadystatechange', () => {
- if (document.readyState === 'complete') {
- wrappedFn();
- }
- });
-
-
- window.attachEvent('onload', wrappedFn);
-
-
-
- }
- }
- };
-
- const MIN_NAME = '[MIN_NAME]';
-
- const MAX_NAME = '[MAX_NAME]';
-
- const nameCompare = function (a, b) {
- if (a === b) {
- return 0;
- }
- else if (a === MIN_NAME || b === MAX_NAME) {
- return -1;
- }
- else if (b === MIN_NAME || a === MAX_NAME) {
- return 1;
- }
- else {
- const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
- if (aAsInt !== null) {
- if (bAsInt !== null) {
- return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
- }
- else {
- return -1;
- }
- }
- else if (bAsInt !== null) {
- return 1;
- }
- else {
- return a < b ? -1 : 1;
- }
- }
- };
-
- const stringCompare = function (a, b) {
- if (a === b) {
- return 0;
- }
- else if (a < b) {
- return -1;
- }
- else {
- return 1;
- }
- };
- const requireKey = function (key, obj) {
- if (obj && key in obj) {
- return obj[key];
- }
- else {
- throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
- }
- };
- const ObjectToUniqueKey = function (obj) {
- if (typeof obj !== 'object' || obj === null) {
- return stringify(obj);
- }
- const keys = [];
-
- for (const k in obj) {
- keys.push(k);
- }
-
- keys.sort();
- let key = '{';
- for (let i = 0; i < keys.length; i++) {
- if (i !== 0) {
- key += ',';
- }
- key += stringify(keys[i]);
- key += ':';
- key += ObjectToUniqueKey(obj[keys[i]]);
- }
- key += '}';
- return key;
- };
-
- const splitStringBySize = function (str, segsize) {
- const len = str.length;
- if (len <= segsize) {
- return [str];
- }
- const dataSegs = [];
- for (let c = 0; c < len; c += segsize) {
- if (c + segsize > len) {
- dataSegs.push(str.substring(c, len));
- }
- else {
- dataSegs.push(str.substring(c, c + segsize));
- }
- }
- return dataSegs;
- };
-
- function each(obj, fn) {
- for (const key in obj) {
- if (obj.hasOwnProperty(key)) {
- fn(key, obj[key]);
- }
- }
- }
-
- const doubleToIEEE754String = function (v) {
- assert(!isInvalidJSONNumber(v), 'Invalid JSON number');
- const ebits = 11, fbits = 52;
- const bias = (1 << (ebits - 1)) - 1;
- let s, e, f, ln, i;
-
-
- if (v === 0) {
- e = 0;
- f = 0;
- s = 1 / v === -Infinity ? 1 : 0;
- }
- else {
- s = v < 0;
- v = Math.abs(v);
- if (v >= Math.pow(2, 1 - bias)) {
-
- ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
- e = ln + bias;
- f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
- }
- else {
-
- e = 0;
- f = Math.round(v / Math.pow(2, 1 - bias - fbits));
- }
- }
-
- const bits = [];
- for (i = fbits; i; i -= 1) {
- bits.push(f % 2 ? 1 : 0);
- f = Math.floor(f / 2);
- }
- for (i = ebits; i; i -= 1) {
- bits.push(e % 2 ? 1 : 0);
- e = Math.floor(e / 2);
- }
- bits.push(s ? 1 : 0);
- bits.reverse();
- const str = bits.join('');
-
- let hexByteString = '';
- for (i = 0; i < 64; i += 8) {
- let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
- if (hexByte.length === 1) {
- hexByte = '0' + hexByte;
- }
- hexByteString = hexByteString + hexByte;
- }
- return hexByteString.toLowerCase();
- };
-
- const isChromeExtensionContentScript = function () {
- return !!(typeof window === 'object' &&
- window['chrome'] &&
- window['chrome']['extension'] &&
- !/^chrome/.test(window.location.href));
- };
-
- const isWindowsStoreApp = function () {
-
- return typeof Windows === 'object' && typeof Windows.UI === 'object';
- };
-
- function errorForServerCode(code, query) {
- let reason = 'Unknown Error';
- if (code === 'too_big') {
- reason =
- 'The data requested exceeds the maximum size ' +
- 'that can be accessed with a single request.';
- }
- else if (code === 'permission_denied') {
- reason = "Client doesn't have permission to access the desired data.";
- }
- else if (code === 'unavailable') {
- reason = 'The service is unavailable';
- }
- const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
-
- error.code = code.toUpperCase();
- return error;
- }
-
- const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
-
- const INTEGER_32_MIN = -2147483648;
-
- const INTEGER_32_MAX = 2147483647;
-
- const tryParseInt = function (str) {
- if (INTEGER_REGEXP_.test(str)) {
- const intVal = Number(str);
- if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
- return intVal;
- }
- }
- return null;
- };
-
- const exceptionGuard = function (fn) {
- try {
- fn();
- }
- catch (e) {
-
- setTimeout(() => {
-
-
-
-
- const stack = e.stack || '';
- warn('Exception was thrown by user callback.', stack);
- throw e;
- }, Math.floor(0));
- }
- };
-
- const beingCrawled = function () {
- const userAgent = (typeof window === 'object' &&
- window['navigator'] &&
- window['navigator']['userAgent']) ||
- '';
-
-
-
-
- return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
- };
-
- const setTimeoutNonBlocking = function (fn, time) {
- const timeout = setTimeout(fn, time);
-
- if (typeof timeout === 'number' &&
-
- typeof Deno !== 'undefined' &&
-
- Deno['unrefTimer']) {
-
- Deno.unrefTimer(timeout);
-
- }
- else if (typeof timeout === 'object' && timeout['unref']) {
-
- timeout['unref']();
- }
- return timeout;
- };
-
-
-
- class AppCheckTokenProvider {
- constructor(appName_, appCheckProvider) {
- this.appName_ = appName_;
- this.appCheckProvider = appCheckProvider;
- this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
- if (!this.appCheck) {
- appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
- }
- }
- getToken(forceRefresh) {
- if (!this.appCheck) {
- return new Promise((resolve, reject) => {
-
-
-
-
- setTimeout(() => {
- if (this.appCheck) {
- this.getToken(forceRefresh).then(resolve, reject);
- }
- else {
- resolve(null);
- }
- }, 0);
- });
- }
- return this.appCheck.getToken(forceRefresh);
- }
- addTokenChangeListener(listener) {
- var _a;
- (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
- }
- notifyForInvalidToken() {
- warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
- 'are invalid. This usually indicates your app was not initialized correctly.');
- }
- }
-
-
-
- class FirebaseAuthTokenProvider {
- constructor(appName_, firebaseOptions_, authProvider_) {
- this.appName_ = appName_;
- this.firebaseOptions_ = firebaseOptions_;
- this.authProvider_ = authProvider_;
- this.auth_ = null;
- this.auth_ = authProvider_.getImmediate({ optional: true });
- if (!this.auth_) {
- authProvider_.onInit(auth => (this.auth_ = auth));
- }
- }
- getToken(forceRefresh) {
- if (!this.auth_) {
- return new Promise((resolve, reject) => {
-
-
-
-
- setTimeout(() => {
- if (this.auth_) {
- this.getToken(forceRefresh).then(resolve, reject);
- }
- else {
- resolve(null);
- }
- }, 0);
- });
- }
- return this.auth_.getToken(forceRefresh).catch(error => {
-
-
- if (error && error.code === 'auth/token-not-initialized') {
- log('Got auth/token-not-initialized error. Treating as null token.');
- return null;
- }
- else {
- return Promise.reject(error);
- }
- });
- }
- addTokenChangeListener(listener) {
-
-
- if (this.auth_) {
- this.auth_.addAuthTokenListener(listener);
- }
- else {
- this.authProvider_
- .get()
- .then(auth => auth.addAuthTokenListener(listener));
- }
- }
- removeTokenChangeListener(listener) {
- this.authProvider_
- .get()
- .then(auth => auth.removeAuthTokenListener(listener));
- }
- notifyForInvalidToken() {
- let errorMessage = 'Provided authentication credentials for the app named "' +
- this.appName_ +
- '" are invalid. This usually indicates your app was not ' +
- 'initialized correctly. ';
- if ('credential' in this.firebaseOptions_) {
- errorMessage +=
- 'Make sure the "credential" property provided to initializeApp() ' +
- 'is authorized to access the specified "databaseURL" and is from the correct ' +
- 'project.';
- }
- else if ('serviceAccount' in this.firebaseOptions_) {
- errorMessage +=
- 'Make sure the "serviceAccount" property provided to initializeApp() ' +
- 'is authorized to access the specified "databaseURL" and is from the correct ' +
- 'project.';
- }
- else {
- errorMessage +=
- 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
- 'initializeApp() match the values provided for your app at ' +
- 'https://console.firebase.google.com/.';
- }
- warn(errorMessage);
- }
- }
-
- class EmulatorTokenProvider {
- constructor(accessToken) {
- this.accessToken = accessToken;
- }
- getToken(forceRefresh) {
- return Promise.resolve({
- accessToken: this.accessToken
- });
- }
- addTokenChangeListener(listener) {
-
-
- listener(this.accessToken);
- }
- removeTokenChangeListener(listener) { }
- notifyForInvalidToken() { }
- }
-
- EmulatorTokenProvider.OWNER = 'owner';
-
-
- const PROTOCOL_VERSION = '5';
- const VERSION_PARAM = 'v';
- const TRANSPORT_SESSION_PARAM = 's';
- const REFERER_PARAM = 'r';
- const FORGE_REF = 'f';
-
-
- const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
- const LAST_SESSION_PARAM = 'ls';
- const APPLICATION_ID_PARAM = 'p';
- const APP_CHECK_TOKEN_PARAM = 'ac';
- const WEBSOCKET = 'websocket';
- const LONG_POLLING = 'long_polling';
-
-
-
- class RepoInfo {
-
-
- constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) {
- this.secure = secure;
- this.namespace = namespace;
- this.webSocketOnly = webSocketOnly;
- this.nodeAdmin = nodeAdmin;
- this.persistenceKey = persistenceKey;
- this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
- this._host = host.toLowerCase();
- this._domain = this._host.substr(this._host.indexOf('.') + 1);
- this.internalHost =
- PersistentStorage.get('host:' + host) || this._host;
- }
- isCacheableHost() {
- return this.internalHost.substr(0, 2) === 's-';
- }
- isCustomHost() {
- return (this._domain !== 'firebaseio.com' &&
- this._domain !== 'firebaseio-demo.com');
- }
- get host() {
- return this._host;
- }
- set host(newHost) {
- if (newHost !== this.internalHost) {
- this.internalHost = newHost;
- if (this.isCacheableHost()) {
- PersistentStorage.set('host:' + this._host, this.internalHost);
- }
- }
- }
- toString() {
- let str = this.toURLString();
- if (this.persistenceKey) {
- str += '<' + this.persistenceKey + '>';
- }
- return str;
- }
- toURLString() {
- const protocol = this.secure ? 'https://' : 'http://';
- const query = this.includeNamespaceInQueryParams
- ? `?ns=${this.namespace}`
- : '';
- return `${protocol}${this.host}/${query}`;
- }
- }
- function repoInfoNeedsQueryParam(repoInfo) {
- return (repoInfo.host !== repoInfo.internalHost ||
- repoInfo.isCustomHost() ||
- repoInfo.includeNamespaceInQueryParams);
- }
-
- function repoInfoConnectionURL(repoInfo, type, params) {
- assert(typeof type === 'string', 'typeof type must == string');
- assert(typeof params === 'object', 'typeof params must == object');
- let connURL;
- if (type === WEBSOCKET) {
- connURL =
- (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
- }
- else if (type === LONG_POLLING) {
- connURL =
- (repoInfo.secure ? 'https://' : 'http://') +
- repoInfo.internalHost +
- '/.lp?';
- }
- else {
- throw new Error('Unknown connection type: ' + type);
- }
- if (repoInfoNeedsQueryParam(repoInfo)) {
- params['ns'] = repoInfo.namespace;
- }
- const pairs = [];
- each(params, (key, value) => {
- pairs.push(key + '=' + value);
- });
- return connURL + pairs.join('&');
- }
-
-
-
- class StatsCollection {
- constructor() {
- this.counters_ = {};
- }
- incrementCounter(name, amount = 1) {
- if (!contains(this.counters_, name)) {
- this.counters_[name] = 0;
- }
- this.counters_[name] += amount;
- }
- get() {
- return deepCopy(this.counters_);
- }
- }
-
-
- const collections = {};
- const reporters = {};
- function statsManagerGetCollection(repoInfo) {
- const hashString = repoInfo.toString();
- if (!collections[hashString]) {
- collections[hashString] = new StatsCollection();
- }
- return collections[hashString];
- }
- function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
- const hashString = repoInfo.toString();
- if (!reporters[hashString]) {
- reporters[hashString] = creatorFunction();
- }
- return reporters[hashString];
- }
-
-
-
- class PacketReceiver {
-
-
- constructor(onMessage_) {
- this.onMessage_ = onMessage_;
- this.pendingResponses = [];
- this.currentResponseNum = 0;
- this.closeAfterResponse = -1;
- this.onClose = null;
- }
- closeAfter(responseNum, callback) {
- this.closeAfterResponse = responseNum;
- this.onClose = callback;
- if (this.closeAfterResponse < this.currentResponseNum) {
- this.onClose();
- this.onClose = null;
- }
- }
-
-
- handleResponse(requestNum, data) {
- this.pendingResponses[requestNum] = data;
- while (this.pendingResponses[this.currentResponseNum]) {
- const toProcess = this.pendingResponses[this.currentResponseNum];
- delete this.pendingResponses[this.currentResponseNum];
- for (let i = 0; i < toProcess.length; ++i) {
- if (toProcess[i]) {
- exceptionGuard(() => {
- this.onMessage_(toProcess[i]);
- });
- }
- }
- if (this.currentResponseNum === this.closeAfterResponse) {
- if (this.onClose) {
- this.onClose();
- this.onClose = null;
- }
- break;
- }
- this.currentResponseNum++;
- }
- }
- }
-
-
-
- const FIREBASE_LONGPOLL_START_PARAM = 'start';
- const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
- const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
- const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
- const FIREBASE_LONGPOLL_ID_PARAM = 'id';
- const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
- const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
- const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
- const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
- const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
- const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
- const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
-
-
-
- const MAX_URL_DATA_SIZE = 1870;
- const SEG_HEADER_SIZE = 30;
- const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
-
- const KEEPALIVE_REQUEST_INTERVAL = 25000;
-
- const LP_CONNECT_TIMEOUT = 30000;
-
- class BrowserPollConnection {
-
-
- constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
- this.connId = connId;
- this.repoInfo = repoInfo;
- this.applicationId = applicationId;
- this.appCheckToken = appCheckToken;
- this.authToken = authToken;
- this.transportSessionId = transportSessionId;
- this.lastSessionId = lastSessionId;
- this.bytesSent = 0;
- this.bytesReceived = 0;
- this.everConnected_ = false;
- this.log_ = logWrapper(connId);
- this.stats_ = statsManagerGetCollection(repoInfo);
- this.urlFn = (params) => {
-
- if (this.appCheckToken) {
- params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
- }
- return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
- };
- }
-
-
- open(onMessage, onDisconnect) {
- this.curSegmentNum = 0;
- this.onDisconnect_ = onDisconnect;
- this.myPacketOrderer = new PacketReceiver(onMessage);
- this.isClosed_ = false;
- this.connectTimeoutTimer_ = setTimeout(() => {
- this.log_('Timed out trying to connect.');
-
- this.onClosed_();
- this.connectTimeoutTimer_ = null;
-
- }, Math.floor(LP_CONNECT_TIMEOUT));
-
- executeWhenDOMReady(() => {
- if (this.isClosed_) {
- return;
- }
-
- this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
- const [command, arg1, arg2, arg3, arg4] = args;
- this.incrementIncomingBytes_(args);
- if (!this.scriptTagHolder) {
- return;
- }
- if (this.connectTimeoutTimer_) {
- clearTimeout(this.connectTimeoutTimer_);
- this.connectTimeoutTimer_ = null;
- }
- this.everConnected_ = true;
- if (command === FIREBASE_LONGPOLL_START_PARAM) {
- this.id = arg1;
- this.password = arg2;
- }
- else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
-
- if (arg1) {
-
-
- this.scriptTagHolder.sendNewPolls = false;
-
-
- this.myPacketOrderer.closeAfter(arg1, () => {
- this.onClosed_();
- });
- }
- else {
- this.onClosed_();
- }
- }
- else {
- throw new Error('Unrecognized command received: ' + command);
- }
- }, (...args) => {
- const [pN, data] = args;
- this.incrementIncomingBytes_(args);
- this.myPacketOrderer.handleResponse(pN, data);
- }, () => {
- this.onClosed_();
- }, this.urlFn);
-
-
- const urlParams = {};
- urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
- urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
- if (this.scriptTagHolder.uniqueCallbackIdentifier) {
- urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
- this.scriptTagHolder.uniqueCallbackIdentifier;
- }
- urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
- if (this.transportSessionId) {
- urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
- }
- if (this.lastSessionId) {
- urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
- }
- if (this.applicationId) {
- urlParams[APPLICATION_ID_PARAM] = this.applicationId;
- }
- if (this.appCheckToken) {
- urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
- }
- if (typeof location !== 'undefined' &&
- location.hostname &&
- FORGE_DOMAIN_RE.test(location.hostname)) {
- urlParams[REFERER_PARAM] = FORGE_REF;
- }
- const connectURL = this.urlFn(urlParams);
- this.log_('Connecting via long-poll to ' + connectURL);
- this.scriptTagHolder.addTag(connectURL, () => {
-
- });
- });
- }
-
-
- start() {
- this.scriptTagHolder.startLongPoll(this.id, this.password);
- this.addDisconnectPingFrame(this.id, this.password);
- }
-
-
- static forceAllow() {
- BrowserPollConnection.forceAllow_ = true;
- }
-
-
- static forceDisallow() {
- BrowserPollConnection.forceDisallow_ = true;
- }
-
- static isAvailable() {
- if (isNodeSdk()) {
- return false;
- }
- else if (BrowserPollConnection.forceAllow_) {
- return true;
- }
- else {
-
-
- return (!BrowserPollConnection.forceDisallow_ &&
- typeof document !== 'undefined' &&
- document.createElement != null &&
- !isChromeExtensionContentScript() &&
- !isWindowsStoreApp());
- }
- }
-
-
- markConnectionHealthy() { }
-
-
- shutdown_() {
- this.isClosed_ = true;
- if (this.scriptTagHolder) {
- this.scriptTagHolder.close();
- this.scriptTagHolder = null;
- }
-
- if (this.myDisconnFrame) {
- document.body.removeChild(this.myDisconnFrame);
- this.myDisconnFrame = null;
- }
- if (this.connectTimeoutTimer_) {
- clearTimeout(this.connectTimeoutTimer_);
- this.connectTimeoutTimer_ = null;
- }
- }
-
-
- onClosed_() {
- if (!this.isClosed_) {
- this.log_('Longpoll is closing itself');
- this.shutdown_();
- if (this.onDisconnect_) {
- this.onDisconnect_(this.everConnected_);
- this.onDisconnect_ = null;
- }
- }
- }
-
-
- close() {
- if (!this.isClosed_) {
- this.log_('Longpoll is being closed.');
- this.shutdown_();
- }
- }
-
-
- send(data) {
- const dataStr = stringify(data);
- this.bytesSent += dataStr.length;
- this.stats_.incrementCounter('bytes_sent', dataStr.length);
-
- const base64data = base64Encode(dataStr);
-
-
- const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
-
-
- for (let i = 0; i < dataSegs.length; i++) {
- this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
- this.curSegmentNum++;
- }
- }
-
-
- addDisconnectPingFrame(id, pw) {
- if (isNodeSdk()) {
- return;
- }
- this.myDisconnFrame = document.createElement('iframe');
- const urlParams = {};
- urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
- urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
- urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
- this.myDisconnFrame.src = this.urlFn(urlParams);
- this.myDisconnFrame.style.display = 'none';
- document.body.appendChild(this.myDisconnFrame);
- }
-
-
- incrementIncomingBytes_(args) {
-
- const bytesReceived = stringify(args).length;
- this.bytesReceived += bytesReceived;
- this.stats_.incrementCounter('bytes_received', bytesReceived);
- }
- }
-
- class FirebaseIFrameScriptHolder {
-
-
- constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
- this.onDisconnect = onDisconnect;
- this.urlFn = urlFn;
-
-
- this.outstandingRequests = new Set();
-
- this.pendingSegs = [];
-
-
-
-
-
- this.currentSerial = Math.floor(Math.random() * 100000000);
-
-
- this.sendNewPolls = true;
- if (!isNodeSdk()) {
-
-
-
-
- this.uniqueCallbackIdentifier = LUIDGenerator();
- window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
- window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
- onMessageCB;
-
- this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
-
- let script = '';
-
-
- if (this.myIFrame.src &&
- this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
- const currentDomain = document.domain;
- script = '<script>document.domain="' + currentDomain + '";</script>';
- }
- const iframeContents = '<html><body>' + script + '</body></html>';
- try {
- this.myIFrame.doc.open();
- this.myIFrame.doc.write(iframeContents);
- this.myIFrame.doc.close();
- }
- catch (e) {
- log('frame writing exception');
- if (e.stack) {
- log(e.stack);
- }
- log(e);
- }
- }
- else {
- this.commandCB = commandCB;
- this.onMessageCB = onMessageCB;
- }
- }
-
-
- static createIFrame_() {
- const iframe = document.createElement('iframe');
- iframe.style.display = 'none';
-
- if (document.body) {
- document.body.appendChild(iframe);
- try {
-
-
-
- const a = iframe.contentWindow.document;
- if (!a) {
-
- log('No IE domain setting required');
- }
- }
- catch (e) {
- const domain = document.domain;
- iframe.src =
- "javascript:void((function(){document.open();document.domain='" +
- domain +
- "';document.close();})())";
- }
- }
- else {
-
-
- throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
- }
-
- if (iframe.contentDocument) {
- iframe.doc = iframe.contentDocument;
- }
- else if (iframe.contentWindow) {
- iframe.doc = iframe.contentWindow.document;
-
- }
- else if (iframe.document) {
-
- iframe.doc = iframe.document;
- }
- return iframe;
- }
-
-
- close() {
-
- this.alive = false;
- if (this.myIFrame) {
-
-
-
- this.myIFrame.doc.body.textContent = '';
- setTimeout(() => {
- if (this.myIFrame !== null) {
- document.body.removeChild(this.myIFrame);
- this.myIFrame = null;
- }
- }, Math.floor(0));
- }
-
- const onDisconnect = this.onDisconnect;
- if (onDisconnect) {
- this.onDisconnect = null;
- onDisconnect();
- }
- }
-
-
- startLongPoll(id, pw) {
- this.myID = id;
- this.myPW = pw;
- this.alive = true;
-
- while (this.newRequest_()) { }
- }
-
-
- newRequest_() {
-
-
-
- if (this.alive &&
- this.sendNewPolls &&
- this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
-
- this.currentSerial++;
- const urlParams = {};
- urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
- urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
- urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
- let theURL = this.urlFn(urlParams);
-
- let curDataString = '';
- let i = 0;
- while (this.pendingSegs.length > 0) {
-
- const nextSeg = this.pendingSegs[0];
- if (nextSeg.d.length +
- SEG_HEADER_SIZE +
- curDataString.length <=
- MAX_URL_DATA_SIZE) {
-
- const theSeg = this.pendingSegs.shift();
- curDataString =
- curDataString +
- '&' +
- FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
- i +
- '=' +
- theSeg.seg +
- '&' +
- FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
- i +
- '=' +
- theSeg.ts +
- '&' +
- FIREBASE_LONGPOLL_DATA_PARAM +
- i +
- '=' +
- theSeg.d;
- i++;
- }
- else {
- break;
- }
- }
- theURL = theURL + curDataString;
- this.addLongPollTag_(theURL, this.currentSerial);
- return true;
- }
- else {
- return false;
- }
- }
-
-
- enqueueSegment(segnum, totalsegs, data) {
-
- this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
-
-
- if (this.alive) {
- this.newRequest_();
- }
- }
-
-
- addLongPollTag_(url, serial) {
-
- this.outstandingRequests.add(serial);
- const doNewRequest = () => {
- this.outstandingRequests.delete(serial);
- this.newRequest_();
- };
-
-
- const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
- const readyStateCB = () => {
-
- clearTimeout(keepaliveTimeout);
-
- doNewRequest();
- };
- this.addTag(url, readyStateCB);
- }
-
-
- addTag(url, loadCB) {
- if (isNodeSdk()) {
-
- this.doNodeLongPoll(url, loadCB);
- }
- else {
- setTimeout(() => {
- try {
-
- if (!this.sendNewPolls) {
- return;
- }
- const newScript = this.myIFrame.doc.createElement('script');
- newScript.type = 'text/javascript';
- newScript.async = true;
- newScript.src = url;
-
- newScript.onload = newScript.onreadystatechange =
- function () {
-
- const rstate = newScript.readyState;
- if (!rstate || rstate === 'loaded' || rstate === 'complete') {
-
- newScript.onload = newScript.onreadystatechange = null;
- if (newScript.parentNode) {
- newScript.parentNode.removeChild(newScript);
- }
- loadCB();
- }
- };
- newScript.onerror = () => {
- log('Long-poll script failed to load: ' + url);
- this.sendNewPolls = false;
- this.close();
- };
- this.myIFrame.doc.body.appendChild(newScript);
- }
- catch (e) {
-
- }
- }, Math.floor(1));
- }
- }
- }
-
-
- const WEBSOCKET_MAX_FRAME_SIZE = 16384;
- const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
- let WebSocketImpl = null;
- if (typeof MozWebSocket !== 'undefined') {
- WebSocketImpl = MozWebSocket;
- }
- else if (typeof WebSocket !== 'undefined') {
- WebSocketImpl = WebSocket;
- }
-
- class WebSocketConnection {
-
-
- constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
- this.connId = connId;
- this.applicationId = applicationId;
- this.appCheckToken = appCheckToken;
- this.authToken = authToken;
- this.keepaliveTimer = null;
- this.frames = null;
- this.totalFrames = 0;
- this.bytesSent = 0;
- this.bytesReceived = 0;
- this.log_ = logWrapper(this.connId);
- this.stats_ = statsManagerGetCollection(repoInfo);
- this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
- this.nodeAdmin = repoInfo.nodeAdmin;
- }
-
-
- static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
- const urlParams = {};
- urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
- if (!isNodeSdk() &&
- typeof location !== 'undefined' &&
- location.hostname &&
- FORGE_DOMAIN_RE.test(location.hostname)) {
- urlParams[REFERER_PARAM] = FORGE_REF;
- }
- if (transportSessionId) {
- urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
- }
- if (lastSessionId) {
- urlParams[LAST_SESSION_PARAM] = lastSessionId;
- }
- if (appCheckToken) {
- urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
- }
- if (applicationId) {
- urlParams[APPLICATION_ID_PARAM] = applicationId;
- }
- return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
- }
-
-
- open(onMessage, onDisconnect) {
- this.onDisconnect = onDisconnect;
- this.onMessage = onMessage;
- this.log_('Websocket connecting to ' + this.connURL);
- this.everConnected_ = false;
-
- PersistentStorage.set('previous_websocket_failure', true);
- try {
- let options;
- if (isNodeSdk()) {
- const device = this.nodeAdmin ? 'AdminNode' : 'Node';
-
- options = {
- headers: {
- 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
- 'X-Firebase-GMPID': this.applicationId || ''
- }
- };
-
-
-
-
-
- if (this.authToken) {
- options.headers['Authorization'] = `Bearer ${this.authToken}`;
- }
- if (this.appCheckToken) {
- options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
- }
-
- const env = process['env'];
- const proxy = this.connURL.indexOf('wss://') === 0
- ? env['HTTPS_PROXY'] || env['https_proxy']
- : env['HTTP_PROXY'] || env['http_proxy'];
- if (proxy) {
- options['proxy'] = { origin: proxy };
- }
- }
- this.mySock = new WebSocketImpl(this.connURL, [], options);
- }
- catch (e) {
- this.log_('Error instantiating WebSocket.');
- const error = e.message || e.data;
- if (error) {
- this.log_(error);
- }
- this.onClosed_();
- return;
- }
- this.mySock.onopen = () => {
- this.log_('Websocket connected.');
- this.everConnected_ = true;
- };
- this.mySock.onclose = () => {
- this.log_('Websocket connection was disconnected.');
- this.mySock = null;
- this.onClosed_();
- };
- this.mySock.onmessage = m => {
- this.handleIncomingFrame(m);
- };
- this.mySock.onerror = e => {
- this.log_('WebSocket error. Closing connection.');
-
- const error = e.message || e.data;
- if (error) {
- this.log_(error);
- }
- this.onClosed_();
- };
- }
-
-
- start() { }
- static forceDisallow() {
- WebSocketConnection.forceDisallow_ = true;
- }
- static isAvailable() {
- let isOldAndroid = false;
- if (typeof navigator !== 'undefined' && navigator.userAgent) {
- const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
- const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
- if (oldAndroidMatch && oldAndroidMatch.length > 1) {
- if (parseFloat(oldAndroidMatch[1]) < 4.4) {
- isOldAndroid = true;
- }
- }
- }
- return (!isOldAndroid &&
- WebSocketImpl !== null &&
- !WebSocketConnection.forceDisallow_);
- }
-
-
- static previouslyFailed() {
-
-
- return (PersistentStorage.isInMemoryStorage ||
- PersistentStorage.get('previous_websocket_failure') === true);
- }
- markConnectionHealthy() {
- PersistentStorage.remove('previous_websocket_failure');
- }
- appendFrame_(data) {
- this.frames.push(data);
- if (this.frames.length === this.totalFrames) {
- const fullMess = this.frames.join('');
- this.frames = null;
- const jsonMess = jsonEval(fullMess);
-
- this.onMessage(jsonMess);
- }
- }
-
-
- handleNewFrameCount_(frameCount) {
- this.totalFrames = frameCount;
- this.frames = [];
- }
-
-
- extractFrameCount_(data) {
- assert(this.frames === null, 'We already have a frame buffer');
-
-
- if (data.length <= 6) {
- const frameCount = Number(data);
- if (!isNaN(frameCount)) {
- this.handleNewFrameCount_(frameCount);
- return null;
- }
- }
- this.handleNewFrameCount_(1);
- return data;
- }
-
-
- handleIncomingFrame(mess) {
- if (this.mySock === null) {
- return;
- }
- const data = mess['data'];
- this.bytesReceived += data.length;
- this.stats_.incrementCounter('bytes_received', data.length);
- this.resetKeepAlive();
- if (this.frames !== null) {
-
- this.appendFrame_(data);
- }
- else {
-
- const remainingData = this.extractFrameCount_(data);
- if (remainingData !== null) {
- this.appendFrame_(remainingData);
- }
- }
- }
-
-
- send(data) {
- this.resetKeepAlive();
- const dataStr = stringify(data);
- this.bytesSent += dataStr.length;
- this.stats_.incrementCounter('bytes_sent', dataStr.length);
-
-
- const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
-
- if (dataSegs.length > 1) {
- this.sendString_(String(dataSegs.length));
- }
-
- for (let i = 0; i < dataSegs.length; i++) {
- this.sendString_(dataSegs[i]);
- }
- }
- shutdown_() {
- this.isClosed_ = true;
- if (this.keepaliveTimer) {
- clearInterval(this.keepaliveTimer);
- this.keepaliveTimer = null;
- }
- if (this.mySock) {
- this.mySock.close();
- this.mySock = null;
- }
- }
- onClosed_() {
- if (!this.isClosed_) {
- this.log_('WebSocket is closing itself');
- this.shutdown_();
-
- if (this.onDisconnect) {
- this.onDisconnect(this.everConnected_);
- this.onDisconnect = null;
- }
- }
- }
-
-
- close() {
- if (!this.isClosed_) {
- this.log_('WebSocket is being closed');
- this.shutdown_();
- }
- }
-
-
- resetKeepAlive() {
- clearInterval(this.keepaliveTimer);
- this.keepaliveTimer = setInterval(() => {
-
- if (this.mySock) {
- this.sendString_('0');
- }
- this.resetKeepAlive();
-
- }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
- }
-
-
- sendString_(str) {
-
-
-
- try {
- this.mySock.send(str);
- }
- catch (e) {
- this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
- setTimeout(this.onClosed_.bind(this), 0);
- }
- }
- }
-
- WebSocketConnection.responsesRequiredToBeHealthy = 2;
-
- WebSocketConnection.healthyTimeout = 30000;
-
-
-
- class TransportManager {
-
-
- constructor(repoInfo) {
- this.initTransports_(repoInfo);
- }
- static get ALL_TRANSPORTS() {
- return [BrowserPollConnection, WebSocketConnection];
- }
-
-
- static get IS_TRANSPORT_INITIALIZED() {
- return this.globalTransportInitialized_;
- }
- initTransports_(repoInfo) {
- const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
- let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
- if (repoInfo.webSocketOnly) {
- if (!isWebSocketsAvailable) {
- warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
- }
- isSkipPollConnection = true;
- }
- if (isSkipPollConnection) {
- this.transports_ = [WebSocketConnection];
- }
- else {
- const transports = (this.transports_ = []);
- for (const transport of TransportManager.ALL_TRANSPORTS) {
- if (transport && transport['isAvailable']()) {
- transports.push(transport);
- }
- }
- TransportManager.globalTransportInitialized_ = true;
- }
- }
-
-
- initialTransport() {
- if (this.transports_.length > 0) {
- return this.transports_[0];
- }
- else {
- throw new Error('No transports available');
- }
- }
-
-
- upgradeTransport() {
- if (this.transports_.length > 1) {
- return this.transports_[1];
- }
- else {
- return null;
- }
- }
- }
-
- TransportManager.globalTransportInitialized_ = false;
-
-
-
- const UPGRADE_TIMEOUT = 60000;
-
-
- const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
-
-
-
- const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
- const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
- const MESSAGE_TYPE = 't';
- const MESSAGE_DATA = 'd';
- const CONTROL_SHUTDOWN = 's';
- const CONTROL_RESET = 'r';
- const CONTROL_ERROR = 'e';
- const CONTROL_PONG = 'o';
- const SWITCH_ACK = 'a';
- const END_TRANSMISSION = 'n';
- const PING = 'p';
- const SERVER_HELLO = 'h';
-
- class Connection {
-
-
- constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
- this.id = id;
- this.repoInfo_ = repoInfo_;
- this.applicationId_ = applicationId_;
- this.appCheckToken_ = appCheckToken_;
- this.authToken_ = authToken_;
- this.onMessage_ = onMessage_;
- this.onReady_ = onReady_;
- this.onDisconnect_ = onDisconnect_;
- this.onKill_ = onKill_;
- this.lastSessionId = lastSessionId;
- this.connectionCount = 0;
- this.pendingDataMessages = [];
- this.state_ = 0 ;
- this.log_ = logWrapper('c:' + this.id + ':');
- this.transportManager_ = new TransportManager(repoInfo_);
- this.log_('Connection created');
- this.start_();
- }
-
-
- start_() {
- const conn = this.transportManager_.initialTransport();
- this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
-
-
- this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
- const onMessageReceived = this.connReceiver_(this.conn_);
- const onConnectionLost = this.disconnReceiver_(this.conn_);
- this.tx_ = this.conn_;
- this.rx_ = this.conn_;
- this.secondaryConn_ = null;
- this.isHealthy_ = false;
-
-
- setTimeout(() => {
-
- this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
- }, Math.floor(0));
- const healthyTimeoutMS = conn['healthyTimeout'] || 0;
- if (healthyTimeoutMS > 0) {
- this.healthyTimeout_ = setTimeoutNonBlocking(() => {
- this.healthyTimeout_ = null;
- if (!this.isHealthy_) {
- if (this.conn_ &&
- this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
- this.log_('Connection exceeded healthy timeout but has received ' +
- this.conn_.bytesReceived +
- ' bytes. Marking connection healthy.');
- this.isHealthy_ = true;
- this.conn_.markConnectionHealthy();
- }
- else if (this.conn_ &&
- this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
- this.log_('Connection exceeded healthy timeout but has sent ' +
- this.conn_.bytesSent +
- ' bytes. Leaving connection alive.');
-
-
- }
- else {
- this.log_('Closing unhealthy connection after timeout.');
- this.close();
- }
- }
-
- }, Math.floor(healthyTimeoutMS));
- }
- }
- nextTransportId_() {
- return 'c:' + this.id + ':' + this.connectionCount++;
- }
- disconnReceiver_(conn) {
- return everConnected => {
- if (conn === this.conn_) {
- this.onConnectionLost_(everConnected);
- }
- else if (conn === this.secondaryConn_) {
- this.log_('Secondary connection lost.');
- this.onSecondaryConnectionLost_();
- }
- else {
- this.log_('closing an old connection');
- }
- };
- }
- connReceiver_(conn) {
- return (message) => {
- if (this.state_ !== 2 ) {
- if (conn === this.rx_) {
- this.onPrimaryMessageReceived_(message);
- }
- else if (conn === this.secondaryConn_) {
- this.onSecondaryMessageReceived_(message);
- }
- else {
- this.log_('message on old connection');
- }
- }
- };
- }
-
-
- sendRequest(dataMsg) {
-
- const msg = { t: 'd', d: dataMsg };
- this.sendData_(msg);
- }
- tryCleanupConnection() {
- if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
- this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
- this.conn_ = this.secondaryConn_;
- this.secondaryConn_ = null;
-
- }
- }
- onSecondaryControl_(controlData) {
- if (MESSAGE_TYPE in controlData) {
- const cmd = controlData[MESSAGE_TYPE];
- if (cmd === SWITCH_ACK) {
- this.upgradeIfSecondaryHealthy_();
- }
- else if (cmd === CONTROL_RESET) {
-
- this.log_('Got a reset on secondary, closing it');
- this.secondaryConn_.close();
-
- if (this.tx_ === this.secondaryConn_ ||
- this.rx_ === this.secondaryConn_) {
- this.close();
- }
- }
- else if (cmd === CONTROL_PONG) {
- this.log_('got pong on secondary.');
- this.secondaryResponsesRequired_--;
- this.upgradeIfSecondaryHealthy_();
- }
- }
- }
- onSecondaryMessageReceived_(parsedData) {
- const layer = requireKey('t', parsedData);
- const data = requireKey('d', parsedData);
- if (layer === 'c') {
- this.onSecondaryControl_(data);
- }
- else if (layer === 'd') {
-
- this.pendingDataMessages.push(data);
- }
- else {
- throw new Error('Unknown protocol layer: ' + layer);
- }
- }
- upgradeIfSecondaryHealthy_() {
- if (this.secondaryResponsesRequired_ <= 0) {
- this.log_('Secondary connection is healthy.');
- this.isHealthy_ = true;
- this.secondaryConn_.markConnectionHealthy();
- this.proceedWithUpgrade_();
- }
- else {
-
- this.log_('sending ping on secondary.');
- this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
- }
- }
- proceedWithUpgrade_() {
-
- this.secondaryConn_.start();
-
- this.log_('sending client ack on secondary');
- this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
-
-
- this.log_('Ending transmission on primary');
- this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
- this.tx_ = this.secondaryConn_;
- this.tryCleanupConnection();
- }
- onPrimaryMessageReceived_(parsedData) {
-
- const layer = requireKey('t', parsedData);
- const data = requireKey('d', parsedData);
- if (layer === 'c') {
- this.onControl_(data);
- }
- else if (layer === 'd') {
- this.onDataMessage_(data);
- }
- }
- onDataMessage_(message) {
- this.onPrimaryResponse_();
-
- this.onMessage_(message);
- }
- onPrimaryResponse_() {
- if (!this.isHealthy_) {
- this.primaryResponsesRequired_--;
- if (this.primaryResponsesRequired_ <= 0) {
- this.log_('Primary connection is healthy.');
- this.isHealthy_ = true;
- this.conn_.markConnectionHealthy();
- }
- }
- }
- onControl_(controlData) {
- const cmd = requireKey(MESSAGE_TYPE, controlData);
- if (MESSAGE_DATA in controlData) {
- const payload = controlData[MESSAGE_DATA];
- if (cmd === SERVER_HELLO) {
- this.onHandshake_(payload);
- }
- else if (cmd === END_TRANSMISSION) {
- this.log_('recvd end transmission on primary');
- this.rx_ = this.secondaryConn_;
- for (let i = 0; i < this.pendingDataMessages.length; ++i) {
- this.onDataMessage_(this.pendingDataMessages[i]);
- }
- this.pendingDataMessages = [];
- this.tryCleanupConnection();
- }
- else if (cmd === CONTROL_SHUTDOWN) {
-
-
- this.onConnectionShutdown_(payload);
- }
- else if (cmd === CONTROL_RESET) {
-
- this.onReset_(payload);
- }
- else if (cmd === CONTROL_ERROR) {
- error('Server Error: ' + payload);
- }
- else if (cmd === CONTROL_PONG) {
- this.log_('got pong on primary.');
- this.onPrimaryResponse_();
- this.sendPingOnPrimaryIfNecessary_();
- }
- else {
- error('Unknown control packet command: ' + cmd);
- }
- }
- }
-
-
- onHandshake_(handshake) {
- const timestamp = handshake.ts;
- const version = handshake.v;
- const host = handshake.h;
- this.sessionId = handshake.s;
- this.repoInfo_.host = host;
-
- if (this.state_ === 0 ) {
- this.conn_.start();
- this.onConnectionEstablished_(this.conn_, timestamp);
- if (PROTOCOL_VERSION !== version) {
- warn('Protocol version mismatch detected');
- }
-
- this.tryStartUpgrade_();
- }
- }
- tryStartUpgrade_() {
- const conn = this.transportManager_.upgradeTransport();
- if (conn) {
- this.startUpgrade_(conn);
- }
- }
- startUpgrade_(conn) {
- this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
-
-
- this.secondaryResponsesRequired_ =
- conn['responsesRequiredToBeHealthy'] || 0;
- const onMessage = this.connReceiver_(this.secondaryConn_);
- const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
- this.secondaryConn_.open(onMessage, onDisconnect);
-
- setTimeoutNonBlocking(() => {
- if (this.secondaryConn_) {
- this.log_('Timed out trying to upgrade.');
- this.secondaryConn_.close();
- }
- }, Math.floor(UPGRADE_TIMEOUT));
- }
- onReset_(host) {
- this.log_('Reset packet received. New host: ' + host);
- this.repoInfo_.host = host;
-
-
- if (this.state_ === 1 ) {
- this.close();
- }
- else {
-
- this.closeConnections_();
- this.start_();
- }
- }
- onConnectionEstablished_(conn, timestamp) {
- this.log_('Realtime connection established.');
- this.conn_ = conn;
- this.state_ = 1 ;
- if (this.onReady_) {
- this.onReady_(timestamp, this.sessionId);
- this.onReady_ = null;
- }
-
-
- if (this.primaryResponsesRequired_ === 0) {
- this.log_('Primary connection is healthy.');
- this.isHealthy_ = true;
- }
- else {
- setTimeoutNonBlocking(() => {
- this.sendPingOnPrimaryIfNecessary_();
- }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
- }
- }
- sendPingOnPrimaryIfNecessary_() {
-
- if (!this.isHealthy_ && this.state_ === 1 ) {
- this.log_('sending ping on primary.');
- this.sendData_({ t: 'c', d: { t: PING, d: {} } });
- }
- }
- onSecondaryConnectionLost_() {
- const conn = this.secondaryConn_;
- this.secondaryConn_ = null;
- if (this.tx_ === conn || this.rx_ === conn) {
-
- this.close();
- }
- }
-
-
- onConnectionLost_(everConnected) {
- this.conn_ = null;
-
-
- if (!everConnected && this.state_ === 0 ) {
- this.log_('Realtime connection failed.');
-
- if (this.repoInfo_.isCacheableHost()) {
- PersistentStorage.remove('host:' + this.repoInfo_.host);
-
- this.repoInfo_.internalHost = this.repoInfo_.host;
- }
- }
- else if (this.state_ === 1 ) {
- this.log_('Realtime connection lost.');
- }
- this.close();
- }
- onConnectionShutdown_(reason) {
- this.log_('Connection shutdown command received. Shutting down...');
- if (this.onKill_) {
- this.onKill_(reason);
- this.onKill_ = null;
- }
-
-
- this.onDisconnect_ = null;
- this.close();
- }
- sendData_(data) {
- if (this.state_ !== 1 ) {
- throw 'Connection is not connected';
- }
- else {
- this.tx_.send(data);
- }
- }
-
-
- close() {
- if (this.state_ !== 2 ) {
- this.log_('Closing realtime connection.');
- this.state_ = 2 ;
- this.closeConnections_();
- if (this.onDisconnect_) {
- this.onDisconnect_();
- this.onDisconnect_ = null;
- }
- }
- }
- closeConnections_() {
- this.log_('Shutting down all connections');
- if (this.conn_) {
- this.conn_.close();
- this.conn_ = null;
- }
- if (this.secondaryConn_) {
- this.secondaryConn_.close();
- this.secondaryConn_ = null;
- }
- if (this.healthyTimeout_) {
- clearTimeout(this.healthyTimeout_);
- this.healthyTimeout_ = null;
- }
- }
- }
-
-
-
- class ServerActions {
- put(pathString, data, onComplete, hash) { }
- merge(pathString, data, onComplete, hash) { }
-
-
- refreshAuthToken(token) { }
-
-
- refreshAppCheckToken(token) { }
- onDisconnectPut(pathString, data, onComplete) { }
- onDisconnectMerge(pathString, data, onComplete) { }
- onDisconnectCancel(pathString, onComplete) { }
- reportStats(stats) { }
- }
-
-
-
- class EventEmitter {
- constructor(allowedEvents_) {
- this.allowedEvents_ = allowedEvents_;
- this.listeners_ = {};
- assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
- }
-
-
- trigger(eventType, ...varArgs) {
- if (Array.isArray(this.listeners_[eventType])) {
-
- const listeners = [...this.listeners_[eventType]];
- for (let i = 0; i < listeners.length; i++) {
- listeners[i].callback.apply(listeners[i].context, varArgs);
- }
- }
- }
- on(eventType, callback, context) {
- this.validateEventType_(eventType);
- this.listeners_[eventType] = this.listeners_[eventType] || [];
- this.listeners_[eventType].push({ callback, context });
- const eventData = this.getInitialEvent(eventType);
- if (eventData) {
- callback.apply(context, eventData);
- }
- }
- off(eventType, callback, context) {
- this.validateEventType_(eventType);
- const listeners = this.listeners_[eventType] || [];
- for (let i = 0; i < listeners.length; i++) {
- if (listeners[i].callback === callback &&
- (!context || context === listeners[i].context)) {
- listeners.splice(i, 1);
- return;
- }
- }
- }
- validateEventType_(eventType) {
- assert(this.allowedEvents_.find(et => {
- return et === eventType;
- }), 'Unknown event: ' + eventType);
- }
- }
-
-
-
- class OnlineMonitor extends EventEmitter {
- constructor() {
- super(['online']);
- this.online_ = true;
-
-
-
-
- if (typeof window !== 'undefined' &&
- typeof window.addEventListener !== 'undefined' &&
- !isMobileCordova()) {
- window.addEventListener('online', () => {
- if (!this.online_) {
- this.online_ = true;
- this.trigger('online', true);
- }
- }, false);
- window.addEventListener('offline', () => {
- if (this.online_) {
- this.online_ = false;
- this.trigger('online', false);
- }
- }, false);
- }
- }
- static getInstance() {
- return new OnlineMonitor();
- }
- getInitialEvent(eventType) {
- assert(eventType === 'online', 'Unknown event type: ' + eventType);
- return [this.online_];
- }
- currentlyOnline() {
- return this.online_;
- }
- }
-
-
-
- const MAX_PATH_DEPTH = 32;
-
- const MAX_PATH_LENGTH_BYTES = 768;
-
- class Path {
-
-
- constructor(pathOrString, pieceNum) {
- if (pieceNum === void 0) {
- this.pieces_ = pathOrString.split('/');
-
- let copyTo = 0;
- for (let i = 0; i < this.pieces_.length; i++) {
- if (this.pieces_[i].length > 0) {
- this.pieces_[copyTo] = this.pieces_[i];
- copyTo++;
- }
- }
- this.pieces_.length = copyTo;
- this.pieceNum_ = 0;
- }
- else {
- this.pieces_ = pathOrString;
- this.pieceNum_ = pieceNum;
- }
- }
- toString() {
- let pathString = '';
- for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
- if (this.pieces_[i] !== '') {
- pathString += '/' + this.pieces_[i];
- }
- }
- return pathString || '/';
- }
- }
- function newEmptyPath() {
- return new Path('');
- }
- function pathGetFront(path) {
- if (path.pieceNum_ >= path.pieces_.length) {
- return null;
- }
- return path.pieces_[path.pieceNum_];
- }
-
- function pathGetLength(path) {
- return path.pieces_.length - path.pieceNum_;
- }
- function pathPopFront(path) {
- let pieceNum = path.pieceNum_;
- if (pieceNum < path.pieces_.length) {
- pieceNum++;
- }
- return new Path(path.pieces_, pieceNum);
- }
- function pathGetBack(path) {
- if (path.pieceNum_ < path.pieces_.length) {
- return path.pieces_[path.pieces_.length - 1];
- }
- return null;
- }
- function pathToUrlEncodedString(path) {
- let pathString = '';
- for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
- if (path.pieces_[i] !== '') {
- pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
- }
- }
- return pathString || '/';
- }
-
- function pathSlice(path, begin = 0) {
- return path.pieces_.slice(path.pieceNum_ + begin);
- }
- function pathParent(path) {
- if (path.pieceNum_ >= path.pieces_.length) {
- return null;
- }
- const pieces = [];
- for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
- pieces.push(path.pieces_[i]);
- }
- return new Path(pieces, 0);
- }
- function pathChild(path, childPathObj) {
- const pieces = [];
- for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
- pieces.push(path.pieces_[i]);
- }
- if (childPathObj instanceof Path) {
- for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
- pieces.push(childPathObj.pieces_[i]);
- }
- }
- else {
- const childPieces = childPathObj.split('/');
- for (let i = 0; i < childPieces.length; i++) {
- if (childPieces[i].length > 0) {
- pieces.push(childPieces[i]);
- }
- }
- }
- return new Path(pieces, 0);
- }
-
- function pathIsEmpty(path) {
- return path.pieceNum_ >= path.pieces_.length;
- }
-
- function newRelativePath(outerPath, innerPath) {
- const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
- if (outer === null) {
- return innerPath;
- }
- else if (outer === inner) {
- return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
- }
- else {
- throw new Error('INTERNAL ERROR: innerPath (' +
- innerPath +
- ') is not within ' +
- 'outerPath (' +
- outerPath +
- ')');
- }
- }
-
- function pathCompare(left, right) {
- const leftKeys = pathSlice(left, 0);
- const rightKeys = pathSlice(right, 0);
- for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
- const cmp = nameCompare(leftKeys[i], rightKeys[i]);
- if (cmp !== 0) {
- return cmp;
- }
- }
- if (leftKeys.length === rightKeys.length) {
- return 0;
- }
- return leftKeys.length < rightKeys.length ? -1 : 1;
- }
-
- function pathEquals(path, other) {
- if (pathGetLength(path) !== pathGetLength(other)) {
- return false;
- }
- for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
- if (path.pieces_[i] !== other.pieces_[j]) {
- return false;
- }
- }
- return true;
- }
-
- function pathContains(path, other) {
- let i = path.pieceNum_;
- let j = other.pieceNum_;
- if (pathGetLength(path) > pathGetLength(other)) {
- return false;
- }
- while (i < path.pieces_.length) {
- if (path.pieces_[i] !== other.pieces_[j]) {
- return false;
- }
- ++i;
- ++j;
- }
- return true;
- }
-
- class ValidationPath {
-
-
- constructor(path, errorPrefix_) {
- this.errorPrefix_ = errorPrefix_;
- this.parts_ = pathSlice(path, 0);
-
- this.byteLength_ = Math.max(1, this.parts_.length);
- for (let i = 0; i < this.parts_.length; i++) {
- this.byteLength_ += stringLength(this.parts_[i]);
- }
- validationPathCheckValid(this);
- }
- }
- function validationPathPush(validationPath, child) {
-
- if (validationPath.parts_.length > 0) {
- validationPath.byteLength_ += 1;
- }
- validationPath.parts_.push(child);
- validationPath.byteLength_ += stringLength(child);
- validationPathCheckValid(validationPath);
- }
- function validationPathPop(validationPath) {
- const last = validationPath.parts_.pop();
- validationPath.byteLength_ -= stringLength(last);
-
- if (validationPath.parts_.length > 0) {
- validationPath.byteLength_ -= 1;
- }
- }
- function validationPathCheckValid(validationPath) {
- if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
- throw new Error(validationPath.errorPrefix_ +
- 'has a key path longer than ' +
- MAX_PATH_LENGTH_BYTES +
- ' bytes (' +
- validationPath.byteLength_ +
- ').');
- }
- if (validationPath.parts_.length > MAX_PATH_DEPTH) {
- throw new Error(validationPath.errorPrefix_ +
- 'path specified exceeds the maximum depth that can be written (' +
- MAX_PATH_DEPTH +
- ') or object contains a cycle ' +
- validationPathToErrorString(validationPath));
- }
- }
-
- function validationPathToErrorString(validationPath) {
- if (validationPath.parts_.length === 0) {
- return '';
- }
- return "in property '" + validationPath.parts_.join('.') + "'";
- }
-
-
- class VisibilityMonitor extends EventEmitter {
- constructor() {
- super(['visible']);
- let hidden;
- let visibilityChange;
- if (typeof document !== 'undefined' &&
- typeof document.addEventListener !== 'undefined') {
- if (typeof document['hidden'] !== 'undefined') {
-
- visibilityChange = 'visibilitychange';
- hidden = 'hidden';
- }
- else if (typeof document['mozHidden'] !== 'undefined') {
- visibilityChange = 'mozvisibilitychange';
- hidden = 'mozHidden';
- }
- else if (typeof document['msHidden'] !== 'undefined') {
- visibilityChange = 'msvisibilitychange';
- hidden = 'msHidden';
- }
- else if (typeof document['webkitHidden'] !== 'undefined') {
- visibilityChange = 'webkitvisibilitychange';
- hidden = 'webkitHidden';
- }
- }
-
-
-
-
- this.visible_ = true;
- if (visibilityChange) {
- document.addEventListener(visibilityChange, () => {
- const visible = !document[hidden];
- if (visible !== this.visible_) {
- this.visible_ = visible;
- this.trigger('visible', visible);
- }
- }, false);
- }
- }
- static getInstance() {
- return new VisibilityMonitor();
- }
- getInitialEvent(eventType) {
- assert(eventType === 'visible', 'Unknown event type: ' + eventType);
- return [this.visible_];
- }
- }
-
-
- const RECONNECT_MIN_DELAY = 1000;
- const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000;
- const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000;
- const RECONNECT_DELAY_MULTIPLIER = 1.3;
- const RECONNECT_DELAY_RESET_TIMEOUT = 30000;
- const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
-
- const INVALID_TOKEN_THRESHOLD = 3;
-
- class PersistentConnection extends ServerActions {
-
-
- constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
- super();
- this.repoInfo_ = repoInfo_;
- this.applicationId_ = applicationId_;
- this.onDataUpdate_ = onDataUpdate_;
- this.onConnectStatus_ = onConnectStatus_;
- this.onServerInfoUpdate_ = onServerInfoUpdate_;
- this.authTokenProvider_ = authTokenProvider_;
- this.appCheckTokenProvider_ = appCheckTokenProvider_;
- this.authOverride_ = authOverride_;
-
- this.id = PersistentConnection.nextPersistentConnectionId_++;
- this.log_ = logWrapper('p:' + this.id + ':');
- this.interruptReasons_ = {};
- this.listens = new Map();
- this.outstandingPuts_ = [];
- this.outstandingGets_ = [];
- this.outstandingPutCount_ = 0;
- this.outstandingGetCount_ = 0;
- this.onDisconnectRequestQueue_ = [];
- this.connected_ = false;
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
- this.securityDebugCallback_ = null;
- this.lastSessionId = null;
- this.establishConnectionTimer_ = null;
- this.visible_ = false;
-
- this.requestCBHash_ = {};
- this.requestNumber_ = 0;
- this.realtime_ = null;
- this.authToken_ = null;
- this.appCheckToken_ = null;
- this.forceTokenRefresh_ = false;
- this.invalidAuthTokenCount_ = 0;
- this.invalidAppCheckTokenCount_ = 0;
- this.firstConnection_ = true;
- this.lastConnectionAttemptTime_ = null;
- this.lastConnectionEstablishedTime_ = null;
- if (authOverride_ && !isNodeSdk()) {
- throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
- }
- VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
- if (repoInfo_.host.indexOf('fblocal') === -1) {
- OnlineMonitor.getInstance().on('online', this.onOnline_, this);
- }
- }
- sendRequest(action, body, onResponse) {
- const curReqNum = ++this.requestNumber_;
- const msg = { r: curReqNum, a: action, b: body };
- this.log_(stringify(msg));
- assert(this.connected_, "sendRequest call when we're not connected not allowed.");
- this.realtime_.sendRequest(msg);
- if (onResponse) {
- this.requestCBHash_[curReqNum] = onResponse;
- }
- }
- get(query) {
- this.initConnection_();
- const deferred = new Deferred();
- const request = {
- p: query._path.toString(),
- q: query._queryObject
- };
- const outstandingGet = {
- action: 'g',
- request,
- onComplete: (message) => {
- const payload = message['d'];
- if (message['s'] === 'ok') {
- deferred.resolve(payload);
- }
- else {
- deferred.reject(payload);
- }
- }
- };
- this.outstandingGets_.push(outstandingGet);
- this.outstandingGetCount_++;
- const index = this.outstandingGets_.length - 1;
- if (this.connected_) {
- this.sendGet_(index);
- }
- return deferred.promise;
- }
- listen(query, currentHashFn, tag, onComplete) {
- this.initConnection_();
- const queryId = query._queryIdentifier;
- const pathString = query._path.toString();
- this.log_('Listen called for ' + pathString + ' ' + queryId);
- if (!this.listens.has(pathString)) {
- this.listens.set(pathString, new Map());
- }
- assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
- assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
- const listenSpec = {
- onComplete,
- hashFn: currentHashFn,
- query,
- tag
- };
- this.listens.get(pathString).set(queryId, listenSpec);
- if (this.connected_) {
- this.sendListen_(listenSpec);
- }
- }
- sendGet_(index) {
- const get = this.outstandingGets_[index];
- this.sendRequest('g', get.request, (message) => {
- delete this.outstandingGets_[index];
- this.outstandingGetCount_--;
- if (this.outstandingGetCount_ === 0) {
- this.outstandingGets_ = [];
- }
- if (get.onComplete) {
- get.onComplete(message);
- }
- });
- }
- sendListen_(listenSpec) {
- const query = listenSpec.query;
- const pathString = query._path.toString();
- const queryId = query._queryIdentifier;
- this.log_('Listen on ' + pathString + ' for ' + queryId);
- const req = { p: pathString };
- const action = 'q';
-
- if (listenSpec.tag) {
- req['q'] = query._queryObject;
- req['t'] = listenSpec.tag;
- }
- req[ 'h'] = listenSpec.hashFn();
- this.sendRequest(action, req, (message) => {
- const payload = message[ 'd'];
- const status = message[ 's'];
-
- PersistentConnection.warnOnListenWarnings_(payload, query);
- const currentListenSpec = this.listens.get(pathString) &&
- this.listens.get(pathString).get(queryId);
-
- if (currentListenSpec === listenSpec) {
- this.log_('listen response', message);
- if (status !== 'ok') {
- this.removeListen_(pathString, queryId);
- }
- if (listenSpec.onComplete) {
- listenSpec.onComplete(status, payload);
- }
- }
- });
- }
- static warnOnListenWarnings_(payload, query) {
- if (payload && typeof payload === 'object' && contains(payload, 'w')) {
-
- const warnings = safeGet(payload, 'w');
- if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
- const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
- const indexPath = query._path.toString();
- warn(`Using an unspecified index. Your data will be downloaded and ` +
- `filtered on the client. Consider adding ${indexSpec} at ` +
- `${indexPath} to your security rules for better performance.`);
- }
- }
- }
- refreshAuthToken(token) {
- this.authToken_ = token;
- this.log_('Auth token refreshed');
- if (this.authToken_) {
- this.tryAuth();
- }
- else {
-
-
- if (this.connected_) {
- this.sendRequest('unauth', {}, () => { });
- }
- }
- this.reduceReconnectDelayIfAdminCredential_(token);
- }
- reduceReconnectDelayIfAdminCredential_(credential) {
-
-
- const isFirebaseSecret = credential && credential.length === 40;
- if (isFirebaseSecret || isAdmin(credential)) {
- this.log_('Admin auth credential detected. Reducing max reconnect time.');
- this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
- }
- }
- refreshAppCheckToken(token) {
- this.appCheckToken_ = token;
- this.log_('App check token refreshed');
- if (this.appCheckToken_) {
- this.tryAppCheck();
- }
- else {
-
-
-
- if (this.connected_) {
- this.sendRequest('unappeck', {}, () => { });
- }
- }
- }
-
-
- tryAuth() {
- if (this.connected_ && this.authToken_) {
- const token = this.authToken_;
- const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
- const requestData = { cred: token };
- if (this.authOverride_ === null) {
- requestData['noauth'] = true;
- }
- else if (typeof this.authOverride_ === 'object') {
- requestData['authvar'] = this.authOverride_;
- }
- this.sendRequest(authMethod, requestData, (res) => {
- const status = res[ 's'];
- const data = res[ 'd'] || 'error';
- if (this.authToken_ === token) {
- if (status === 'ok') {
- this.invalidAuthTokenCount_ = 0;
- }
- else {
-
- this.onAuthRevoked_(status, data);
- }
- }
- });
- }
- }
-
-
- tryAppCheck() {
- if (this.connected_ && this.appCheckToken_) {
- this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
- const status = res[ 's'];
- const data = res[ 'd'] || 'error';
- if (status === 'ok') {
- this.invalidAppCheckTokenCount_ = 0;
- }
- else {
- this.onAppCheckRevoked_(status, data);
- }
- });
- }
- }
-
-
- unlisten(query, tag) {
- const pathString = query._path.toString();
- const queryId = query._queryIdentifier;
- this.log_('Unlisten called for ' + pathString + ' ' + queryId);
- assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
- const listen = this.removeListen_(pathString, queryId);
- if (listen && this.connected_) {
- this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
- }
- }
- sendUnlisten_(pathString, queryId, queryObj, tag) {
- this.log_('Unlisten on ' + pathString + ' for ' + queryId);
- const req = { p: pathString };
- const action = 'n';
-
- if (tag) {
- req['q'] = queryObj;
- req['t'] = tag;
- }
- this.sendRequest(action, req);
- }
- onDisconnectPut(pathString, data, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('o', pathString, data, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString,
- action: 'o',
- data,
- onComplete
- });
- }
- }
- onDisconnectMerge(pathString, data, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('om', pathString, data, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString,
- action: 'om',
- data,
- onComplete
- });
- }
- }
- onDisconnectCancel(pathString, onComplete) {
- this.initConnection_();
- if (this.connected_) {
- this.sendOnDisconnect_('oc', pathString, null, onComplete);
- }
- else {
- this.onDisconnectRequestQueue_.push({
- pathString,
- action: 'oc',
- data: null,
- onComplete
- });
- }
- }
- sendOnDisconnect_(action, pathString, data, onComplete) {
- const request = { p: pathString, d: data };
- this.log_('onDisconnect ' + action, request);
- this.sendRequest(action, request, (response) => {
- if (onComplete) {
- setTimeout(() => {
- onComplete(response[ 's'], response[ 'd']);
- }, Math.floor(0));
- }
- });
- }
- put(pathString, data, onComplete, hash) {
- this.putInternal('p', pathString, data, onComplete, hash);
- }
- merge(pathString, data, onComplete, hash) {
- this.putInternal('m', pathString, data, onComplete, hash);
- }
- putInternal(action, pathString, data, onComplete, hash) {
- this.initConnection_();
- const request = {
- p: pathString,
- d: data
- };
- if (hash !== undefined) {
- request[ 'h'] = hash;
- }
-
- this.outstandingPuts_.push({
- action,
- request,
- onComplete
- });
- this.outstandingPutCount_++;
- const index = this.outstandingPuts_.length - 1;
- if (this.connected_) {
- this.sendPut_(index);
- }
- else {
- this.log_('Buffering put: ' + pathString);
- }
- }
- sendPut_(index) {
- const action = this.outstandingPuts_[index].action;
- const request = this.outstandingPuts_[index].request;
- const onComplete = this.outstandingPuts_[index].onComplete;
- this.outstandingPuts_[index].queued = this.connected_;
- this.sendRequest(action, request, (message) => {
- this.log_(action + ' response', message);
- delete this.outstandingPuts_[index];
- this.outstandingPutCount_--;
-
- if (this.outstandingPutCount_ === 0) {
- this.outstandingPuts_ = [];
- }
- if (onComplete) {
- onComplete(message[ 's'], message[ 'd']);
- }
- });
- }
- reportStats(stats) {
-
- if (this.connected_) {
- const request = { c: stats };
- this.log_('reportStats', request);
- this.sendRequest( 's', request, result => {
- const status = result[ 's'];
- if (status !== 'ok') {
- const errorReason = result[ 'd'];
- this.log_('reportStats', 'Error sending stats: ' + errorReason);
- }
- });
- }
- }
- onDataMessage_(message) {
- if ('r' in message) {
-
- this.log_('from server: ' + stringify(message));
- const reqNum = message['r'];
- const onResponse = this.requestCBHash_[reqNum];
- if (onResponse) {
- delete this.requestCBHash_[reqNum];
- onResponse(message[ 'b']);
- }
- }
- else if ('error' in message) {
- throw 'A server-side error has occurred: ' + message['error'];
- }
- else if ('a' in message) {
-
- this.onDataPush_(message['a'], message['b']);
- }
- }
- onDataPush_(action, body) {
- this.log_('handleServerMessage', action, body);
- if (action === 'd') {
- this.onDataUpdate_(body[ 'p'], body[ 'd'],
- false, body['t']);
- }
- else if (action === 'm') {
- this.onDataUpdate_(body[ 'p'], body[ 'd'],
- true, body['t']);
- }
- else if (action === 'c') {
- this.onListenRevoked_(body[ 'p'], body[ 'q']);
- }
- else if (action === 'ac') {
- this.onAuthRevoked_(body[ 's'], body[ 'd']);
- }
- else if (action === 'apc') {
- this.onAppCheckRevoked_(body[ 's'], body[ 'd']);
- }
- else if (action === 'sd') {
- this.onSecurityDebugPacket_(body);
- }
- else {
- error('Unrecognized action received from server: ' +
- stringify(action) +
- '\nAre you using the latest client?');
- }
- }
- onReady_(timestamp, sessionId) {
- this.log_('connection ready');
- this.connected_ = true;
- this.lastConnectionEstablishedTime_ = new Date().getTime();
- this.handleTimestamp_(timestamp);
- this.lastSessionId = sessionId;
- if (this.firstConnection_) {
- this.sendConnectStats_();
- }
- this.restoreState_();
- this.firstConnection_ = false;
- this.onConnectStatus_(true);
- }
- scheduleConnect_(timeout) {
- assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
- if (this.establishConnectionTimer_) {
- clearTimeout(this.establishConnectionTimer_);
- }
-
-
- this.establishConnectionTimer_ = setTimeout(() => {
- this.establishConnectionTimer_ = null;
- this.establishConnection_();
-
- }, Math.floor(timeout));
- }
- initConnection_() {
- if (!this.realtime_ && this.firstConnection_) {
- this.scheduleConnect_(0);
- }
- }
- onVisible_(visible) {
-
- if (visible &&
- !this.visible_ &&
- this.reconnectDelay_ === this.maxReconnectDelay_) {
- this.log_('Window became visible. Reducing delay.');
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- this.visible_ = visible;
- }
- onOnline_(online) {
- if (online) {
- this.log_('Browser went online.');
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- else {
- this.log_('Browser went offline. Killing connection.');
- if (this.realtime_) {
- this.realtime_.close();
- }
- }
- }
- onRealtimeDisconnect_() {
- this.log_('data client disconnected');
- this.connected_ = false;
- this.realtime_ = null;
-
- this.cancelSentTransactions_();
-
- this.requestCBHash_ = {};
- if (this.shouldReconnect_()) {
- if (!this.visible_) {
- this.log_("Window isn't visible. Delaying reconnect.");
- this.reconnectDelay_ = this.maxReconnectDelay_;
- this.lastConnectionAttemptTime_ = new Date().getTime();
- }
- else if (this.lastConnectionEstablishedTime_) {
-
- const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
- if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- }
- this.lastConnectionEstablishedTime_ = null;
- }
- const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
- let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
- reconnectDelay = Math.random() * reconnectDelay;
- this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
- this.scheduleConnect_(reconnectDelay);
-
- this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
- }
- this.onConnectStatus_(false);
- }
- async establishConnection_() {
- if (this.shouldReconnect_()) {
- this.log_('Making a connection attempt');
- this.lastConnectionAttemptTime_ = new Date().getTime();
- this.lastConnectionEstablishedTime_ = null;
- const onDataMessage = this.onDataMessage_.bind(this);
- const onReady = this.onReady_.bind(this);
- const onDisconnect = this.onRealtimeDisconnect_.bind(this);
- const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
- const lastSessionId = this.lastSessionId;
- let canceled = false;
- let connection = null;
- const closeFn = function () {
- if (connection) {
- connection.close();
- }
- else {
- canceled = true;
- onDisconnect();
- }
- };
- const sendRequestFn = function (msg) {
- assert(connection, "sendRequest call when we're not connected not allowed.");
- connection.sendRequest(msg);
- };
- this.realtime_ = {
- close: closeFn,
- sendRequest: sendRequestFn
- };
- const forceRefresh = this.forceTokenRefresh_;
- this.forceTokenRefresh_ = false;
- try {
-
-
- const [authToken, appCheckToken] = await Promise.all([
- this.authTokenProvider_.getToken(forceRefresh),
- this.appCheckTokenProvider_.getToken(forceRefresh)
- ]);
- if (!canceled) {
- log('getToken() completed. Creating connection.');
- this.authToken_ = authToken && authToken.accessToken;
- this.appCheckToken_ = appCheckToken && appCheckToken.token;
- connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
- reason => {
- warn(reason + ' (' + this.repoInfo_.toString() + ')');
- this.interrupt(SERVER_KILL_INTERRUPT_REASON);
- }, lastSessionId);
- }
- else {
- log('getToken() completed but was canceled');
- }
- }
- catch (error) {
- this.log_('Failed to get token: ' + error);
- if (!canceled) {
- if (this.repoInfo_.nodeAdmin) {
-
-
-
- warn(error);
- }
- closeFn();
- }
- }
- }
- }
- interrupt(reason) {
- log('Interrupting connection for reason: ' + reason);
- this.interruptReasons_[reason] = true;
- if (this.realtime_) {
- this.realtime_.close();
- }
- else {
- if (this.establishConnectionTimer_) {
- clearTimeout(this.establishConnectionTimer_);
- this.establishConnectionTimer_ = null;
- }
- if (this.connected_) {
- this.onRealtimeDisconnect_();
- }
- }
- }
- resume(reason) {
- log('Resuming connection for reason: ' + reason);
- delete this.interruptReasons_[reason];
- if (isEmpty(this.interruptReasons_)) {
- this.reconnectDelay_ = RECONNECT_MIN_DELAY;
- if (!this.realtime_) {
- this.scheduleConnect_(0);
- }
- }
- }
- handleTimestamp_(timestamp) {
- const delta = timestamp - new Date().getTime();
- this.onServerInfoUpdate_({ serverTimeOffset: delta });
- }
- cancelSentTransactions_() {
- for (let i = 0; i < this.outstandingPuts_.length; i++) {
- const put = this.outstandingPuts_[i];
- if (put && 'h' in put.request && put.queued) {
- if (put.onComplete) {
- put.onComplete('disconnect');
- }
- delete this.outstandingPuts_[i];
- this.outstandingPutCount_--;
- }
- }
-
- if (this.outstandingPutCount_ === 0) {
- this.outstandingPuts_ = [];
- }
- }
- onListenRevoked_(pathString, query) {
-
- let queryId;
- if (!query) {
- queryId = 'default';
- }
- else {
- queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
- }
- const listen = this.removeListen_(pathString, queryId);
- if (listen && listen.onComplete) {
- listen.onComplete('permission_denied');
- }
- }
- removeListen_(pathString, queryId) {
- const normalizedPathString = new Path(pathString).toString();
- let listen;
- if (this.listens.has(normalizedPathString)) {
- const map = this.listens.get(normalizedPathString);
- listen = map.get(queryId);
- map.delete(queryId);
- if (map.size === 0) {
- this.listens.delete(normalizedPathString);
- }
- }
- else {
-
- listen = undefined;
- }
- return listen;
- }
- onAuthRevoked_(statusCode, explanation) {
- log('Auth token revoked: ' + statusCode + '/' + explanation);
- this.authToken_ = null;
- this.forceTokenRefresh_ = true;
- this.realtime_.close();
- if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
-
-
-
- this.invalidAuthTokenCount_++;
- if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
-
- this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
-
-
- this.authTokenProvider_.notifyForInvalidToken();
- }
- }
- }
- onAppCheckRevoked_(statusCode, explanation) {
- log('App check token revoked: ' + statusCode + '/' + explanation);
- this.appCheckToken_ = null;
- this.forceTokenRefresh_ = true;
-
-
- if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
-
-
-
- this.invalidAppCheckTokenCount_++;
- if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
- this.appCheckTokenProvider_.notifyForInvalidToken();
- }
- }
- }
- onSecurityDebugPacket_(body) {
- if (this.securityDebugCallback_) {
- this.securityDebugCallback_(body);
- }
- else {
- if ('msg' in body) {
- console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
- }
- }
- }
- restoreState_() {
-
- this.tryAuth();
- this.tryAppCheck();
-
-
- for (const queries of this.listens.values()) {
- for (const listenSpec of queries.values()) {
- this.sendListen_(listenSpec);
- }
- }
- for (let i = 0; i < this.outstandingPuts_.length; i++) {
- if (this.outstandingPuts_[i]) {
- this.sendPut_(i);
- }
- }
- while (this.onDisconnectRequestQueue_.length) {
- const request = this.onDisconnectRequestQueue_.shift();
- this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
- }
- for (let i = 0; i < this.outstandingGets_.length; i++) {
- if (this.outstandingGets_[i]) {
- this.sendGet_(i);
- }
- }
- }
-
-
- sendConnectStats_() {
- const stats = {};
- let clientName = 'js';
- if (isNodeSdk()) {
- if (this.repoInfo_.nodeAdmin) {
- clientName = 'admin_node';
- }
- else {
- clientName = 'node';
- }
- }
- stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
- if (isMobileCordova()) {
- stats['framework.cordova'] = 1;
- }
- else if (isReactNative()) {
- stats['framework.reactnative'] = 1;
- }
- this.reportStats(stats);
- }
- shouldReconnect_() {
- const online = OnlineMonitor.getInstance().currentlyOnline();
- return isEmpty(this.interruptReasons_) && online;
- }
- }
- PersistentConnection.nextPersistentConnectionId_ = 0;
-
- PersistentConnection.nextConnectionId_ = 0;
-
-
- class NamedNode {
- constructor(name, node) {
- this.name = name;
- this.node = node;
- }
- static Wrap(name, node) {
- return new NamedNode(name, node);
- }
- }
-
-
- class Index {
-
-
- getCompare() {
- return this.compare.bind(this);
- }
-
-
- indexedValueChanged(oldNode, newNode) {
- const oldWrapped = new NamedNode(MIN_NAME, oldNode);
- const newWrapped = new NamedNode(MIN_NAME, newNode);
- return this.compare(oldWrapped, newWrapped) !== 0;
- }
-
-
- minPost() {
-
- return NamedNode.MIN;
- }
- }
-
-
- let __EMPTY_NODE;
- class KeyIndex extends Index {
- static get __EMPTY_NODE() {
- return __EMPTY_NODE;
- }
- static set __EMPTY_NODE(val) {
- __EMPTY_NODE = val;
- }
- compare(a, b) {
- return nameCompare(a.name, b.name);
- }
- isDefinedOn(node) {
-
-
- throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
- }
- indexedValueChanged(oldNode, newNode) {
- return false;
- }
- minPost() {
-
- return NamedNode.MIN;
- }
- maxPost() {
-
-
- return new NamedNode(MAX_NAME, __EMPTY_NODE);
- }
- makePost(indexValue, name) {
- assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
-
- return new NamedNode(indexValue, __EMPTY_NODE);
- }
-
-
- toString() {
- return '.key';
- }
- }
- const KEY_INDEX = new KeyIndex();
-
-
-
- class SortedMapIterator {
-
-
- constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
- this.isReverse_ = isReverse_;
- this.resultGenerator_ = resultGenerator_;
- this.nodeStack_ = [];
- let cmp = 1;
- while (!node.isEmpty()) {
- node = node;
- cmp = startKey ? comparator(node.key, startKey) : 1;
-
- if (isReverse_) {
- cmp *= -1;
- }
- if (cmp < 0) {
-
- if (this.isReverse_) {
- node = node.left;
- }
- else {
- node = node.right;
- }
- }
- else if (cmp === 0) {
-
- this.nodeStack_.push(node);
- break;
- }
- else {
-
- this.nodeStack_.push(node);
- if (this.isReverse_) {
- node = node.right;
- }
- else {
- node = node.left;
- }
- }
- }
- }
- getNext() {
- if (this.nodeStack_.length === 0) {
- return null;
- }
- let node = this.nodeStack_.pop();
- let result;
- if (this.resultGenerator_) {
- result = this.resultGenerator_(node.key, node.value);
- }
- else {
- result = { key: node.key, value: node.value };
- }
- if (this.isReverse_) {
- node = node.left;
- while (!node.isEmpty()) {
- this.nodeStack_.push(node);
- node = node.right;
- }
- }
- else {
- node = node.right;
- while (!node.isEmpty()) {
- this.nodeStack_.push(node);
- node = node.left;
- }
- }
- return result;
- }
- hasNext() {
- return this.nodeStack_.length > 0;
- }
- peek() {
- if (this.nodeStack_.length === 0) {
- return null;
- }
- const node = this.nodeStack_[this.nodeStack_.length - 1];
- if (this.resultGenerator_) {
- return this.resultGenerator_(node.key, node.value);
- }
- else {
- return { key: node.key, value: node.value };
- }
- }
- }
-
- class LLRBNode {
-
-
- constructor(key, value, color, left, right) {
- this.key = key;
- this.value = value;
- this.color = color != null ? color : LLRBNode.RED;
- this.left =
- left != null ? left : SortedMap.EMPTY_NODE;
- this.right =
- right != null ? right : SortedMap.EMPTY_NODE;
- }
-
-
- copy(key, value, color, left, right) {
- 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);
- }
-
-
- count() {
- return this.left.count() + 1 + this.right.count();
- }
-
-
- isEmpty() {
- return false;
- }
-
-
- inorderTraversal(action) {
- return (this.left.inorderTraversal(action) ||
- !!action(this.key, this.value) ||
- this.right.inorderTraversal(action));
- }
-
-
- reverseTraversal(action) {
- return (this.right.reverseTraversal(action) ||
- action(this.key, this.value) ||
- this.left.reverseTraversal(action));
- }
-
-
- min_() {
- if (this.left.isEmpty()) {
- return this;
- }
- else {
- return this.left.min_();
- }
- }
-
-
- minKey() {
- return this.min_().key;
- }
-
-
- maxKey() {
- if (this.right.isEmpty()) {
- return this.key;
- }
- else {
- return this.right.maxKey();
- }
- }
-
-
- insert(key, value, comparator) {
- let n = this;
- const cmp = comparator(key, n.key);
- if (cmp < 0) {
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
- }
- else if (cmp === 0) {
- n = n.copy(null, value, null, null, null);
- }
- else {
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
- }
- return n.fixUp_();
- }
-
-
- removeMin_() {
- if (this.left.isEmpty()) {
- return SortedMap.EMPTY_NODE;
- }
- let n = this;
- if (!n.left.isRed_() && !n.left.left.isRed_()) {
- n = n.moveRedLeft_();
- }
- n = n.copy(null, null, null, n.left.removeMin_(), null);
- return n.fixUp_();
- }
-
-
- remove(key, comparator) {
- let n, smallest;
- n = this;
- if (comparator(key, n.key) < 0) {
- if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
- n = n.moveRedLeft_();
- }
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
- }
- else {
- if (n.left.isRed_()) {
- n = n.rotateRight_();
- }
- if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
- n = n.moveRedRight_();
- }
- if (comparator(key, n.key) === 0) {
- if (n.right.isEmpty()) {
- return SortedMap.EMPTY_NODE;
- }
- else {
- smallest = n.right.min_();
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
- }
- }
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
- }
- return n.fixUp_();
- }
-
-
- isRed_() {
- return this.color;
- }
-
-
- fixUp_() {
- let n = this;
- if (n.right.isRed_() && !n.left.isRed_()) {
- n = n.rotateLeft_();
- }
- if (n.left.isRed_() && n.left.left.isRed_()) {
- n = n.rotateRight_();
- }
- if (n.left.isRed_() && n.right.isRed_()) {
- n = n.colorFlip_();
- }
- return n;
- }
-
-
- moveRedLeft_() {
- let n = this.colorFlip_();
- if (n.right.left.isRed_()) {
- n = n.copy(null, null, null, null, n.right.rotateRight_());
- n = n.rotateLeft_();
- n = n.colorFlip_();
- }
- return n;
- }
-
-
- moveRedRight_() {
- let n = this.colorFlip_();
- if (n.left.left.isRed_()) {
- n = n.rotateRight_();
- n = n.colorFlip_();
- }
- return n;
- }
-
-
- rotateLeft_() {
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
- return this.right.copy(null, null, this.color, nl, null);
- }
-
-
- rotateRight_() {
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
- return this.left.copy(null, null, this.color, null, nr);
- }
-
-
- colorFlip_() {
- const left = this.left.copy(null, null, !this.left.color, null, null);
- const right = this.right.copy(null, null, !this.right.color, null, null);
- return this.copy(null, null, !this.color, left, right);
- }
-
-
- checkMaxDepth_() {
- const blackDepth = this.check_();
- return Math.pow(2.0, blackDepth) <= this.count() + 1;
- }
- check_() {
- if (this.isRed_() && this.left.isRed_()) {
- throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
- }
- if (this.right.isRed_()) {
- throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
- }
- const blackDepth = this.left.check_();
- if (blackDepth !== this.right.check_()) {
- throw new Error('Black depths differ');
- }
- else {
- return blackDepth + (this.isRed_() ? 0 : 1);
- }
- }
- }
- LLRBNode.RED = true;
- LLRBNode.BLACK = false;
-
- class LLRBEmptyNode {
-
-
- copy(key, value, color, left, right) {
- return this;
- }
-
-
- insert(key, value, comparator) {
- return new LLRBNode(key, value, null);
- }
-
-
- remove(key, comparator) {
- return this;
- }
-
-
- count() {
- return 0;
- }
-
-
- isEmpty() {
- return true;
- }
-
-
- inorderTraversal(action) {
- return false;
- }
-
-
- reverseTraversal(action) {
- return false;
- }
- minKey() {
- return null;
- }
- maxKey() {
- return null;
- }
- check_() {
- return 0;
- }
-
-
- isRed_() {
- return false;
- }
- }
-
- class SortedMap {
-
-
- constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
- this.comparator_ = comparator_;
- this.root_ = root_;
- }
-
-
- insert(key, value) {
- return new SortedMap(this.comparator_, this.root_
- .insert(key, value, this.comparator_)
- .copy(null, null, LLRBNode.BLACK, null, null));
- }
-
-
- remove(key) {
- return new SortedMap(this.comparator_, this.root_
- .remove(key, this.comparator_)
- .copy(null, null, LLRBNode.BLACK, null, null));
- }
-
-
- get(key) {
- let cmp;
- let node = this.root_;
- while (!node.isEmpty()) {
- cmp = this.comparator_(key, node.key);
- if (cmp === 0) {
- return node.value;
- }
- else if (cmp < 0) {
- node = node.left;
- }
- else if (cmp > 0) {
- node = node.right;
- }
- }
- return null;
- }
-
-
- getPredecessorKey(key) {
- let cmp, node = this.root_, rightParent = null;
- while (!node.isEmpty()) {
- cmp = this.comparator_(key, node.key);
- if (cmp === 0) {
- if (!node.left.isEmpty()) {
- node = node.left;
- while (!node.right.isEmpty()) {
- node = node.right;
- }
- return node.key;
- }
- else if (rightParent) {
- return rightParent.key;
- }
- else {
- return null;
- }
- }
- else if (cmp < 0) {
- node = node.left;
- }
- else if (cmp > 0) {
- rightParent = node;
- node = node.right;
- }
- }
- throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
- }
-
-
- isEmpty() {
- return this.root_.isEmpty();
- }
-
-
- count() {
- return this.root_.count();
- }
-
-
- minKey() {
- return this.root_.minKey();
- }
-
-
- maxKey() {
- return this.root_.maxKey();
- }
-
-
- inorderTraversal(action) {
- return this.root_.inorderTraversal(action);
- }
-
-
- reverseTraversal(action) {
- return this.root_.reverseTraversal(action);
- }
-
-
- getIterator(resultGenerator) {
- return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
- }
- getIteratorFrom(key, resultGenerator) {
- return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
- }
- getReverseIteratorFrom(key, resultGenerator) {
- return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
- }
- getReverseIterator(resultGenerator) {
- return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
- }
- }
-
- SortedMap.EMPTY_NODE = new LLRBEmptyNode();
-
-
- function NAME_ONLY_COMPARATOR(left, right) {
- return nameCompare(left.name, right.name);
- }
- function NAME_COMPARATOR(left, right) {
- return nameCompare(left, right);
- }
-
-
- let MAX_NODE$2;
- function setMaxNode$1(val) {
- MAX_NODE$2 = val;
- }
- const priorityHashText = function (priority) {
- if (typeof priority === 'number') {
- return 'number:' + doubleToIEEE754String(priority);
- }
- else {
- return 'string:' + priority;
- }
- };
-
- const validatePriorityNode = function (priorityNode) {
- if (priorityNode.isLeafNode()) {
- const val = priorityNode.val();
- assert(typeof val === 'string' ||
- typeof val === 'number' ||
- (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
- }
- else {
- assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
- }
-
- assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
- };
-
-
- let __childrenNodeConstructor;
-
- class LeafNode {
-
-
- constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
- this.value_ = value_;
- this.priorityNode_ = priorityNode_;
- this.lazyHash_ = null;
- assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
- validatePriorityNode(this.priorityNode_);
- }
- static set __childrenNodeConstructor(val) {
- __childrenNodeConstructor = val;
- }
- static get __childrenNodeConstructor() {
- return __childrenNodeConstructor;
- }
-
- isLeafNode() {
- return true;
- }
-
- getPriority() {
- return this.priorityNode_;
- }
-
- updatePriority(newPriorityNode) {
- return new LeafNode(this.value_, newPriorityNode);
- }
-
- getImmediateChild(childName) {
-
- if (childName === '.priority') {
- return this.priorityNode_;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
- }
- }
-
- getChild(path) {
- if (pathIsEmpty(path)) {
- return this;
- }
- else if (pathGetFront(path) === '.priority') {
- return this.priorityNode_;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
- }
- }
- hasChild() {
- return false;
- }
-
- getPredecessorChildName(childName, childNode) {
- return null;
- }
-
- updateImmediateChild(childName, newChildNode) {
- if (childName === '.priority') {
- return this.updatePriority(newChildNode);
- }
- else if (newChildNode.isEmpty() && childName !== '.priority') {
- return this;
- }
- else {
- return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
- }
- }
-
- updateChild(path, newChildNode) {
- const front = pathGetFront(path);
- if (front === null) {
- return newChildNode;
- }
- else if (newChildNode.isEmpty() && front !== '.priority') {
- return this;
- }
- else {
- assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
- return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
- }
- }
-
- isEmpty() {
- return false;
- }
-
- numChildren() {
- return 0;
- }
-
- forEachChild(index, action) {
- return false;
- }
- val(exportFormat) {
- if (exportFormat && !this.getPriority().isEmpty()) {
- return {
- '.value': this.getValue(),
- '.priority': this.getPriority().val()
- };
- }
- else {
- return this.getValue();
- }
- }
-
- hash() {
- if (this.lazyHash_ === null) {
- let toHash = '';
- if (!this.priorityNode_.isEmpty()) {
- toHash +=
- 'priority:' +
- priorityHashText(this.priorityNode_.val()) +
- ':';
- }
- const type = typeof this.value_;
- toHash += type + ':';
- if (type === 'number') {
- toHash += doubleToIEEE754String(this.value_);
- }
- else {
- toHash += this.value_;
- }
- this.lazyHash_ = sha1(toHash);
- }
- return this.lazyHash_;
- }
-
-
- getValue() {
- return this.value_;
- }
- compareTo(other) {
- if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
- return 1;
- }
- else if (other instanceof LeafNode.__childrenNodeConstructor) {
- return -1;
- }
- else {
- assert(other.isLeafNode(), 'Unknown node type');
- return this.compareToLeafNode_(other);
- }
- }
-
-
- compareToLeafNode_(otherLeaf) {
- const otherLeafType = typeof otherLeaf.value_;
- const thisLeafType = typeof this.value_;
- const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
- const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
- assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
- assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
- if (otherIndex === thisIndex) {
-
- if (thisLeafType === 'object') {
-
- return 0;
- }
- else {
-
- if (this.value_ < otherLeaf.value_) {
- return -1;
- }
- else if (this.value_ === otherLeaf.value_) {
- return 0;
- }
- else {
- return 1;
- }
- }
- }
- else {
- return thisIndex - otherIndex;
- }
- }
- withIndex() {
- return this;
- }
- isIndexed() {
- return true;
- }
- equals(other) {
- if (other === this) {
- return true;
- }
- else if (other.isLeafNode()) {
- const otherLeaf = other;
- return (this.value_ === otherLeaf.value_ &&
- this.priorityNode_.equals(otherLeaf.priorityNode_));
- }
- else {
- return false;
- }
- }
- }
-
- LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
-
-
- let nodeFromJSON$1;
- let MAX_NODE$1;
- function setNodeFromJSON(val) {
- nodeFromJSON$1 = val;
- }
- function setMaxNode(val) {
- MAX_NODE$1 = val;
- }
- class PriorityIndex extends Index {
- compare(a, b) {
- const aPriority = a.node.getPriority();
- const bPriority = b.node.getPriority();
- const indexCmp = aPriority.compareTo(bPriority);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- }
- isDefinedOn(node) {
- return !node.getPriority().isEmpty();
- }
- indexedValueChanged(oldNode, newNode) {
- return !oldNode.getPriority().equals(newNode.getPriority());
- }
- minPost() {
-
- return NamedNode.MIN;
- }
- maxPost() {
- return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
- }
- makePost(indexValue, name) {
- const priorityNode = nodeFromJSON$1(indexValue);
- return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
- }
-
-
- toString() {
- return '.priority';
- }
- }
- const PRIORITY_INDEX = new PriorityIndex();
-
-
- const LOG_2 = Math.log(2);
- class Base12Num {
- constructor(length) {
- const logBase2 = (num) =>
-
- parseInt((Math.log(num) / LOG_2), 10);
- const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
- this.count = logBase2(length + 1);
- this.current_ = this.count - 1;
- const mask = bitMask(this.count);
- this.bits_ = (length + 1) & mask;
- }
- nextBitIsOne() {
-
- const result = !(this.bits_ & (0x1 << this.current_));
- this.current_--;
- return result;
- }
- }
-
- const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
- childList.sort(cmp);
- const buildBalancedTree = function (low, high) {
- const length = high - low;
- let namedNode;
- let key;
- if (length === 0) {
- return null;
- }
- else if (length === 1) {
- namedNode = childList[low];
- key = keyFn ? keyFn(namedNode) : namedNode;
- return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
- }
- else {
-
- const middle = parseInt((length / 2), 10) + low;
- const left = buildBalancedTree(low, middle);
- const right = buildBalancedTree(middle + 1, high);
- namedNode = childList[middle];
- key = keyFn ? keyFn(namedNode) : namedNode;
- return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
- }
- };
- const buildFrom12Array = function (base12) {
- let node = null;
- let root = null;
- let index = childList.length;
- const buildPennant = function (chunkSize, color) {
- const low = index - chunkSize;
- const high = index;
- index -= chunkSize;
- const childTree = buildBalancedTree(low + 1, high);
- const namedNode = childList[low];
- const key = keyFn ? keyFn(namedNode) : namedNode;
- attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
- };
- const attachPennant = function (pennant) {
- if (node) {
- node.left = pennant;
- node = pennant;
- }
- else {
- root = pennant;
- node = pennant;
- }
- };
- for (let i = 0; i < base12.count; ++i) {
- const isOne = base12.nextBitIsOne();
-
- const chunkSize = Math.pow(2, base12.count - (i + 1));
- if (isOne) {
- buildPennant(chunkSize, LLRBNode.BLACK);
- }
- else {
-
- buildPennant(chunkSize, LLRBNode.BLACK);
- buildPennant(chunkSize, LLRBNode.RED);
- }
- }
- return root;
- };
- const base12 = new Base12Num(childList.length);
- const root = buildFrom12Array(base12);
-
- return new SortedMap(mapSortFn || cmp, root);
- };
-
-
- let _defaultIndexMap;
- const fallbackObject = {};
- class IndexMap {
- constructor(indexes_, indexSet_) {
- this.indexes_ = indexes_;
- this.indexSet_ = indexSet_;
- }
-
-
- static get Default() {
- assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
- _defaultIndexMap =
- _defaultIndexMap ||
- new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
- return _defaultIndexMap;
- }
- get(indexKey) {
- const sortedMap = safeGet(this.indexes_, indexKey);
- if (!sortedMap) {
- throw new Error('No index defined for ' + indexKey);
- }
- if (sortedMap instanceof SortedMap) {
- return sortedMap;
- }
- else {
-
-
- return null;
- }
- }
- hasIndex(indexDefinition) {
- return contains(this.indexSet_, indexDefinition.toString());
- }
- addIndex(indexDefinition, existingChildren) {
- assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
- const childList = [];
- let sawIndexedValue = false;
- const iter = existingChildren.getIterator(NamedNode.Wrap);
- let next = iter.getNext();
- while (next) {
- sawIndexedValue =
- sawIndexedValue || indexDefinition.isDefinedOn(next.node);
- childList.push(next);
- next = iter.getNext();
- }
- let newIndex;
- if (sawIndexedValue) {
- newIndex = buildChildSet(childList, indexDefinition.getCompare());
- }
- else {
- newIndex = fallbackObject;
- }
- const indexName = indexDefinition.toString();
- const newIndexSet = Object.assign({}, this.indexSet_);
- newIndexSet[indexName] = indexDefinition;
- const newIndexes = Object.assign({}, this.indexes_);
- newIndexes[indexName] = newIndex;
- return new IndexMap(newIndexes, newIndexSet);
- }
-
-
- addToIndexes(namedNode, existingChildren) {
- const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
- const index = safeGet(this.indexSet_, indexName);
- assert(index, 'Missing index implementation for ' + indexName);
- if (indexedChildren === fallbackObject) {
-
- if (index.isDefinedOn(namedNode.node)) {
-
- const childList = [];
- const iter = existingChildren.getIterator(NamedNode.Wrap);
- let next = iter.getNext();
- while (next) {
- if (next.name !== namedNode.name) {
- childList.push(next);
- }
- next = iter.getNext();
- }
- childList.push(namedNode);
- return buildChildSet(childList, index.getCompare());
- }
- else {
-
- return fallbackObject;
- }
- }
- else {
- const existingSnap = existingChildren.get(namedNode.name);
- let newChildren = indexedChildren;
- if (existingSnap) {
- newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
- }
- return newChildren.insert(namedNode, namedNode.node);
- }
- });
- return new IndexMap(newIndexes, this.indexSet_);
- }
-
-
- removeFromIndexes(namedNode, existingChildren) {
- const newIndexes = map(this.indexes_, (indexedChildren) => {
- if (indexedChildren === fallbackObject) {
-
- return indexedChildren;
- }
- else {
- const existingSnap = existingChildren.get(namedNode.name);
- if (existingSnap) {
- return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
- }
- else {
-
- return indexedChildren;
- }
- }
- });
- return new IndexMap(newIndexes, this.indexSet_);
- }
- }
-
-
-
- let EMPTY_NODE;
-
- class ChildrenNode {
-
-
- constructor(children_, priorityNode_, indexMap_) {
- this.children_ = children_;
- this.priorityNode_ = priorityNode_;
- this.indexMap_ = indexMap_;
- this.lazyHash_ = null;
-
-
- if (this.priorityNode_) {
- validatePriorityNode(this.priorityNode_);
- }
- if (this.children_.isEmpty()) {
- assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
- }
- }
- static get EMPTY_NODE() {
- return (EMPTY_NODE ||
- (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
- }
-
- isLeafNode() {
- return false;
- }
-
- getPriority() {
- return this.priorityNode_ || EMPTY_NODE;
- }
-
- updatePriority(newPriorityNode) {
- if (this.children_.isEmpty()) {
-
- return this;
- }
- else {
- return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
- }
- }
-
- getImmediateChild(childName) {
-
- if (childName === '.priority') {
- return this.getPriority();
- }
- else {
- const child = this.children_.get(childName);
- return child === null ? EMPTY_NODE : child;
- }
- }
-
- getChild(path) {
- const front = pathGetFront(path);
- if (front === null) {
- return this;
- }
- return this.getImmediateChild(front).getChild(pathPopFront(path));
- }
-
- hasChild(childName) {
- return this.children_.get(childName) !== null;
- }
-
- updateImmediateChild(childName, newChildNode) {
- assert(newChildNode, 'We should always be passing snapshot nodes');
- if (childName === '.priority') {
- return this.updatePriority(newChildNode);
- }
- else {
- const namedNode = new NamedNode(childName, newChildNode);
- let newChildren, newIndexMap;
- if (newChildNode.isEmpty()) {
- newChildren = this.children_.remove(childName);
- newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
- }
- else {
- newChildren = this.children_.insert(childName, newChildNode);
- newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
- }
- const newPriority = newChildren.isEmpty()
- ? EMPTY_NODE
- : this.priorityNode_;
- return new ChildrenNode(newChildren, newPriority, newIndexMap);
- }
- }
-
- updateChild(path, newChildNode) {
- const front = pathGetFront(path);
- if (front === null) {
- return newChildNode;
- }
- else {
- assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
- const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
- return this.updateImmediateChild(front, newImmediateChild);
- }
- }
-
- isEmpty() {
- return this.children_.isEmpty();
- }
-
- numChildren() {
- return this.children_.count();
- }
-
- val(exportFormat) {
- if (this.isEmpty()) {
- return null;
- }
- const obj = {};
- let numKeys = 0, maxKey = 0, allIntegerKeys = true;
- this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- obj[key] = childNode.val(exportFormat);
- numKeys++;
- if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
- maxKey = Math.max(maxKey, Number(key));
- }
- else {
- allIntegerKeys = false;
- }
- });
- if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
-
- const array = [];
-
- for (const key in obj) {
- array[key] = obj[key];
- }
- return array;
- }
- else {
- if (exportFormat && !this.getPriority().isEmpty()) {
- obj['.priority'] = this.getPriority().val();
- }
- return obj;
- }
- }
-
- hash() {
- if (this.lazyHash_ === null) {
- let toHash = '';
- if (!this.getPriority().isEmpty()) {
- toHash +=
- 'priority:' +
- priorityHashText(this.getPriority().val()) +
- ':';
- }
- this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- const childHash = childNode.hash();
- if (childHash !== '') {
- toHash += ':' + key + ':' + childHash;
- }
- });
- this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
- }
- return this.lazyHash_;
- }
-
- getPredecessorChildName(childName, childNode, index) {
- const idx = this.resolveIndex_(index);
- if (idx) {
- const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
- return predecessor ? predecessor.name : null;
- }
- else {
- return this.children_.getPredecessorKey(childName);
- }
- }
- getFirstChildName(indexDefinition) {
- const idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- const minKey = idx.minKey();
- return minKey && minKey.name;
- }
- else {
- return this.children_.minKey();
- }
- }
- getFirstChild(indexDefinition) {
- const minKey = this.getFirstChildName(indexDefinition);
- if (minKey) {
- return new NamedNode(minKey, this.children_.get(minKey));
- }
- else {
- return null;
- }
- }
-
-
- getLastChildName(indexDefinition) {
- const idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- const maxKey = idx.maxKey();
- return maxKey && maxKey.name;
- }
- else {
- return this.children_.maxKey();
- }
- }
- getLastChild(indexDefinition) {
- const maxKey = this.getLastChildName(indexDefinition);
- if (maxKey) {
- return new NamedNode(maxKey, this.children_.get(maxKey));
- }
- else {
- return null;
- }
- }
- forEachChild(index, action) {
- const idx = this.resolveIndex_(index);
- if (idx) {
- return idx.inorderTraversal(wrappedNode => {
- return action(wrappedNode.name, wrappedNode.node);
- });
- }
- else {
- return this.children_.inorderTraversal(action);
- }
- }
- getIterator(indexDefinition) {
- return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
- }
- getIteratorFrom(startPost, indexDefinition) {
- const idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- return idx.getIteratorFrom(startPost, key => key);
- }
- else {
- const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
- let next = iterator.peek();
- while (next != null && indexDefinition.compare(next, startPost) < 0) {
- iterator.getNext();
- next = iterator.peek();
- }
- return iterator;
- }
- }
- getReverseIterator(indexDefinition) {
- return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
- }
- getReverseIteratorFrom(endPost, indexDefinition) {
- const idx = this.resolveIndex_(indexDefinition);
- if (idx) {
- return idx.getReverseIteratorFrom(endPost, key => {
- return key;
- });
- }
- else {
- const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
- let next = iterator.peek();
- while (next != null && indexDefinition.compare(next, endPost) > 0) {
- iterator.getNext();
- next = iterator.peek();
- }
- return iterator;
- }
- }
- compareTo(other) {
- if (this.isEmpty()) {
- if (other.isEmpty()) {
- return 0;
- }
- else {
- return -1;
- }
- }
- else if (other.isLeafNode() || other.isEmpty()) {
- return 1;
- }
- else if (other === MAX_NODE) {
- return -1;
- }
- else {
-
- return 0;
- }
- }
- withIndex(indexDefinition) {
- if (indexDefinition === KEY_INDEX ||
- this.indexMap_.hasIndex(indexDefinition)) {
- return this;
- }
- else {
- const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
- return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
- }
- }
- isIndexed(index) {
- return index === KEY_INDEX || this.indexMap_.hasIndex(index);
- }
- equals(other) {
- if (other === this) {
- return true;
- }
- else if (other.isLeafNode()) {
- return false;
- }
- else {
- const otherChildrenNode = other;
- if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
- return false;
- }
- else if (this.children_.count() === otherChildrenNode.children_.count()) {
- const thisIter = this.getIterator(PRIORITY_INDEX);
- const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
- let thisCurrent = thisIter.getNext();
- let otherCurrent = otherIter.getNext();
- while (thisCurrent && otherCurrent) {
- if (thisCurrent.name !== otherCurrent.name ||
- !thisCurrent.node.equals(otherCurrent.node)) {
- return false;
- }
- thisCurrent = thisIter.getNext();
- otherCurrent = otherIter.getNext();
- }
- return thisCurrent === null && otherCurrent === null;
- }
- else {
- return false;
- }
- }
- }
-
-
- resolveIndex_(indexDefinition) {
- if (indexDefinition === KEY_INDEX) {
- return null;
- }
- else {
- return this.indexMap_.get(indexDefinition.toString());
- }
- }
- }
- ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
- class MaxNode extends ChildrenNode {
- constructor() {
- super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
- }
- compareTo(other) {
- if (other === this) {
- return 0;
- }
- else {
- return 1;
- }
- }
- equals(other) {
-
- return other === this;
- }
- getPriority() {
- return this;
- }
- getImmediateChild(childName) {
- return ChildrenNode.EMPTY_NODE;
- }
- isEmpty() {
- return false;
- }
- }
-
- const MAX_NODE = new MaxNode();
- Object.defineProperties(NamedNode, {
- MIN: {
- value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
- },
- MAX: {
- value: new NamedNode(MAX_NAME, MAX_NODE)
- }
- });
-
- KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
- LeafNode.__childrenNodeConstructor = ChildrenNode;
- setMaxNode$1(MAX_NODE);
- setMaxNode(MAX_NODE);
-
-
- const USE_HINZE = true;
-
- function nodeFromJSON(json, priority = null) {
- if (json === null) {
- return ChildrenNode.EMPTY_NODE;
- }
- if (typeof json === 'object' && '.priority' in json) {
- priority = json['.priority'];
- }
- assert(priority === null ||
- typeof priority === 'string' ||
- typeof priority === 'number' ||
- (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
- if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
- json = json['.value'];
- }
-
- if (typeof json !== 'object' || '.sv' in json) {
- const jsonLeaf = json;
- return new LeafNode(jsonLeaf, nodeFromJSON(priority));
- }
- if (!(json instanceof Array) && USE_HINZE) {
- const children = [];
- let childrenHavePriority = false;
- const hinzeJsonObj = json;
- each(hinzeJsonObj, (key, child) => {
- if (key.substring(0, 1) !== '.') {
-
- const childNode = nodeFromJSON(child);
- if (!childNode.isEmpty()) {
- childrenHavePriority =
- childrenHavePriority || !childNode.getPriority().isEmpty();
- children.push(new NamedNode(key, childNode));
- }
- }
- });
- if (children.length === 0) {
- return ChildrenNode.EMPTY_NODE;
- }
- const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
- if (childrenHavePriority) {
- const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
- return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
- }
- else {
- return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
- }
- }
- else {
- let node = ChildrenNode.EMPTY_NODE;
- each(json, (key, childData) => {
- if (contains(json, key)) {
- if (key.substring(0, 1) !== '.') {
-
- const childNode = nodeFromJSON(childData);
- if (childNode.isLeafNode() || !childNode.isEmpty()) {
- node = node.updateImmediateChild(key, childNode);
- }
- }
- }
- });
- return node.updatePriority(nodeFromJSON(priority));
- }
- }
- setNodeFromJSON(nodeFromJSON);
-
-
- class PathIndex extends Index {
- constructor(indexPath_) {
- super();
- this.indexPath_ = indexPath_;
- assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
- }
- extractChild(snap) {
- return snap.getChild(this.indexPath_);
- }
- isDefinedOn(node) {
- return !node.getChild(this.indexPath_).isEmpty();
- }
- compare(a, b) {
- const aChild = this.extractChild(a.node);
- const bChild = this.extractChild(b.node);
- const indexCmp = aChild.compareTo(bChild);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- }
- makePost(indexValue, name) {
- const valueNode = nodeFromJSON(indexValue);
- const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
- return new NamedNode(name, node);
- }
- maxPost() {
- const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
- return new NamedNode(MAX_NAME, node);
- }
- toString() {
- return pathSlice(this.indexPath_, 0).join('/');
- }
- }
-
-
- class ValueIndex extends Index {
- compare(a, b) {
- const indexCmp = a.node.compareTo(b.node);
- if (indexCmp === 0) {
- return nameCompare(a.name, b.name);
- }
- else {
- return indexCmp;
- }
- }
- isDefinedOn(node) {
- return true;
- }
- indexedValueChanged(oldNode, newNode) {
- return !oldNode.equals(newNode);
- }
- minPost() {
-
- return NamedNode.MIN;
- }
- maxPost() {
-
- return NamedNode.MAX;
- }
- makePost(indexValue, name) {
- const valueNode = nodeFromJSON(indexValue);
- return new NamedNode(name, valueNode);
- }
-
-
- toString() {
- return '.value';
- }
- }
- const VALUE_INDEX = new ValueIndex();
-
-
- function changeValue(snapshotNode) {
- return { type: "value" , snapshotNode };
- }
- function changeChildAdded(childName, snapshotNode) {
- return { type: "child_added" , snapshotNode, childName };
- }
- function changeChildRemoved(childName, snapshotNode) {
- return { type: "child_removed" , snapshotNode, childName };
- }
- function changeChildChanged(childName, snapshotNode, oldSnap) {
- return {
- type: "child_changed" ,
- snapshotNode,
- childName,
- oldSnap
- };
- }
- function changeChildMoved(childName, snapshotNode) {
- return { type: "child_moved" , snapshotNode, childName };
- }
-
-
-
- class IndexedFilter {
- constructor(index_) {
- this.index_ = index_;
- }
- updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
- const oldChild = snap.getImmediateChild(key);
-
- if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
-
-
-
- if (oldChild.isEmpty() === newChild.isEmpty()) {
-
-
-
- return snap;
- }
- }
- if (optChangeAccumulator != null) {
- if (newChild.isEmpty()) {
- if (snap.hasChild(key)) {
- optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
- }
- else {
- assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
- }
- }
- else if (oldChild.isEmpty()) {
- optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
- }
- else {
- optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
- }
- }
- if (snap.isLeafNode() && newChild.isEmpty()) {
- return snap;
- }
- else {
-
- return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
- }
- }
- updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
- if (optChangeAccumulator != null) {
- if (!oldSnap.isLeafNode()) {
- oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- if (!newSnap.hasChild(key)) {
- optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
- }
- });
- }
- if (!newSnap.isLeafNode()) {
- newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- if (oldSnap.hasChild(key)) {
- const oldChild = oldSnap.getImmediateChild(key);
- if (!oldChild.equals(childNode)) {
- optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
- }
- }
- else {
- optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
- }
- });
- }
- }
- return newSnap.withIndex(this.index_);
- }
- updatePriority(oldSnap, newPriority) {
- if (oldSnap.isEmpty()) {
- return ChildrenNode.EMPTY_NODE;
- }
- else {
- return oldSnap.updatePriority(newPriority);
- }
- }
- filtersNodes() {
- return false;
- }
- getIndexedFilter() {
- return this;
- }
- getIndex() {
- return this.index_;
- }
- }
-
-
-
- class RangedFilter {
- constructor(params) {
- this.indexedFilter_ = new IndexedFilter(params.getIndex());
- this.index_ = params.getIndex();
- this.startPost_ = RangedFilter.getStartPost_(params);
- this.endPost_ = RangedFilter.getEndPost_(params);
- this.startIsInclusive_ = !params.startAfterSet_;
- this.endIsInclusive_ = !params.endBeforeSet_;
- }
- getStartPost() {
- return this.startPost_;
- }
- getEndPost() {
- return this.endPost_;
- }
- matches(node) {
- const isWithinStart = this.startIsInclusive_
- ? this.index_.compare(this.getStartPost(), node) <= 0
- : this.index_.compare(this.getStartPost(), node) < 0;
- const isWithinEnd = this.endIsInclusive_
- ? this.index_.compare(node, this.getEndPost()) <= 0
- : this.index_.compare(node, this.getEndPost()) < 0;
- return isWithinStart && isWithinEnd;
- }
- updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- if (!this.matches(new NamedNode(key, newChild))) {
- newChild = ChildrenNode.EMPTY_NODE;
- }
- return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
- }
- updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
- if (newSnap.isLeafNode()) {
-
- newSnap = ChildrenNode.EMPTY_NODE;
- }
- let filtered = newSnap.withIndex(this.index_);
-
- filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
- const self = this;
- newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- if (!self.matches(new NamedNode(key, childNode))) {
- filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
- }
- });
- return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
- }
- updatePriority(oldSnap, newPriority) {
-
- return oldSnap;
- }
- filtersNodes() {
- return true;
- }
- getIndexedFilter() {
- return this.indexedFilter_;
- }
- getIndex() {
- return this.index_;
- }
- static getStartPost_(params) {
- if (params.hasStart()) {
- const startName = params.getIndexStartName();
- return params.getIndex().makePost(params.getIndexStartValue(), startName);
- }
- else {
- return params.getIndex().minPost();
- }
- }
- static getEndPost_(params) {
- if (params.hasEnd()) {
- const endName = params.getIndexEndName();
- return params.getIndex().makePost(params.getIndexEndValue(), endName);
- }
- else {
- return params.getIndex().maxPost();
- }
- }
- }
-
-
-
- class LimitedFilter {
- constructor(params) {
- this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
- this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
- this.withinStartPost = (node) => {
- const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
- return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
- };
- this.withinEndPost = (node) => {
- const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
- return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
- };
- this.rangedFilter_ = new RangedFilter(params);
- this.index_ = params.getIndex();
- this.limit_ = params.getLimit();
- this.reverse_ = !params.isViewFromLeft();
- this.startIsInclusive_ = !params.startAfterSet_;
- this.endIsInclusive_ = !params.endBeforeSet_;
- }
- updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
- if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
- newChild = ChildrenNode.EMPTY_NODE;
- }
- if (snap.getImmediateChild(key).equals(newChild)) {
-
- return snap;
- }
- else if (snap.numChildren() < this.limit_) {
- return this.rangedFilter_
- .getIndexedFilter()
- .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
- }
- else {
- return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
- }
- }
- updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
- let filtered;
- if (newSnap.isLeafNode() || newSnap.isEmpty()) {
-
- filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
- }
- else {
- if (this.limit_ * 2 < newSnap.numChildren() &&
- newSnap.isIndexed(this.index_)) {
-
- filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
-
- let iterator;
- if (this.reverse_) {
- iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
- }
- else {
- iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
- }
- let count = 0;
- while (iterator.hasNext() && count < this.limit_) {
- const next = iterator.getNext();
- if (!this.withinDirectionalStart(next)) {
-
- continue;
- }
- else if (!this.withinDirectionalEnd(next)) {
-
- break;
- }
- else {
- filtered = filtered.updateImmediateChild(next.name, next.node);
- count++;
- }
- }
- }
- else {
-
- filtered = newSnap.withIndex(this.index_);
-
- filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
- let iterator;
- if (this.reverse_) {
- iterator = filtered.getReverseIterator(this.index_);
- }
- else {
- iterator = filtered.getIterator(this.index_);
- }
- let count = 0;
- while (iterator.hasNext()) {
- const next = iterator.getNext();
- const inRange = count < this.limit_ &&
- this.withinDirectionalStart(next) &&
- this.withinDirectionalEnd(next);
- if (inRange) {
- count++;
- }
- else {
- filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
- }
- }
- }
- }
- return this.rangedFilter_
- .getIndexedFilter()
- .updateFullNode(oldSnap, filtered, optChangeAccumulator);
- }
- updatePriority(oldSnap, newPriority) {
-
- return oldSnap;
- }
- filtersNodes() {
- return true;
- }
- getIndexedFilter() {
- return this.rangedFilter_.getIndexedFilter();
- }
- getIndex() {
- return this.index_;
- }
- fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
-
- let cmp;
- if (this.reverse_) {
- const indexCmp = this.index_.getCompare();
- cmp = (a, b) => indexCmp(b, a);
- }
- else {
- cmp = this.index_.getCompare();
- }
- const oldEventCache = snap;
- assert(oldEventCache.numChildren() === this.limit_, '');
- const newChildNamedNode = new NamedNode(childKey, childSnap);
- const windowBoundary = this.reverse_
- ? oldEventCache.getFirstChild(this.index_)
- : oldEventCache.getLastChild(this.index_);
- const inRange = this.rangedFilter_.matches(newChildNamedNode);
- if (oldEventCache.hasChild(childKey)) {
- const oldChildSnap = oldEventCache.getImmediateChild(childKey);
- let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
- while (nextChild != null &&
- (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
-
-
-
- nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
- }
- const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
- const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
- if (remainsInWindow) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
- }
- return oldEventCache.updateImmediateChild(childKey, childSnap);
- }
- else {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
- }
- const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
- const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
- if (nextChildInRange) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
- }
- return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
- }
- else {
- return newEventCache;
- }
- }
- }
- else if (childSnap.isEmpty()) {
-
- return snap;
- }
- else if (inRange) {
- if (cmp(windowBoundary, newChildNamedNode) >= 0) {
- if (changeAccumulator != null) {
- changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
- changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
- }
- return oldEventCache
- .updateImmediateChild(childKey, childSnap)
- .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
- }
- else {
- return snap;
- }
- }
- else {
- return snap;
- }
- }
- }
-
-
-
- class QueryParams {
- constructor() {
- this.limitSet_ = false;
- this.startSet_ = false;
- this.startNameSet_ = false;
- this.startAfterSet_ = false;
- this.endSet_ = false;
- this.endNameSet_ = false;
- this.endBeforeSet_ = false;
- this.limit_ = 0;
- this.viewFrom_ = '';
- this.indexStartValue_ = null;
- this.indexStartName_ = '';
- this.indexEndValue_ = null;
- this.indexEndName_ = '';
- this.index_ = PRIORITY_INDEX;
- }
- hasStart() {
- return this.startSet_;
- }
-
-
- isViewFromLeft() {
- if (this.viewFrom_ === '') {
-
-
-
-
- return this.startSet_;
- }
- else {
- return this.viewFrom_ === "l" ;
- }
- }
-
-
- getIndexStartValue() {
- assert(this.startSet_, 'Only valid if start has been set');
- return this.indexStartValue_;
- }
-
-
- getIndexStartName() {
- assert(this.startSet_, 'Only valid if start has been set');
- if (this.startNameSet_) {
- return this.indexStartName_;
- }
- else {
- return MIN_NAME;
- }
- }
- hasEnd() {
- return this.endSet_;
- }
-
-
- getIndexEndValue() {
- assert(this.endSet_, 'Only valid if end has been set');
- return this.indexEndValue_;
- }
-
-
- getIndexEndName() {
- assert(this.endSet_, 'Only valid if end has been set');
- if (this.endNameSet_) {
- return this.indexEndName_;
- }
- else {
- return MAX_NAME;
- }
- }
- hasLimit() {
- return this.limitSet_;
- }
-
-
- hasAnchoredLimit() {
- return this.limitSet_ && this.viewFrom_ !== '';
- }
-
-
- getLimit() {
- assert(this.limitSet_, 'Only valid if limit has been set');
- return this.limit_;
- }
- getIndex() {
- return this.index_;
- }
- loadsAllData() {
- return !(this.startSet_ || this.endSet_ || this.limitSet_);
- }
- isDefault() {
- return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
- }
- copy() {
- const copy = new QueryParams();
- copy.limitSet_ = this.limitSet_;
- copy.limit_ = this.limit_;
- copy.startSet_ = this.startSet_;
- copy.startAfterSet_ = this.startAfterSet_;
- copy.indexStartValue_ = this.indexStartValue_;
- copy.startNameSet_ = this.startNameSet_;
- copy.indexStartName_ = this.indexStartName_;
- copy.endSet_ = this.endSet_;
- copy.endBeforeSet_ = this.endBeforeSet_;
- copy.indexEndValue_ = this.indexEndValue_;
- copy.endNameSet_ = this.endNameSet_;
- copy.indexEndName_ = this.indexEndName_;
- copy.index_ = this.index_;
- copy.viewFrom_ = this.viewFrom_;
- return copy;
- }
- }
- function queryParamsGetNodeFilter(queryParams) {
- if (queryParams.loadsAllData()) {
- return new IndexedFilter(queryParams.getIndex());
- }
- else if (queryParams.hasLimit()) {
- return new LimitedFilter(queryParams);
- }
- else {
- return new RangedFilter(queryParams);
- }
- }
- function queryParamsLimitToFirst(queryParams, newLimit) {
- const newParams = queryParams.copy();
- newParams.limitSet_ = true;
- newParams.limit_ = newLimit;
- newParams.viewFrom_ = "l" ;
- return newParams;
- }
- function queryParamsLimitToLast(queryParams, newLimit) {
- const newParams = queryParams.copy();
- newParams.limitSet_ = true;
- newParams.limit_ = newLimit;
- newParams.viewFrom_ = "r" ;
- return newParams;
- }
- function queryParamsStartAt(queryParams, indexValue, key) {
- const newParams = queryParams.copy();
- newParams.startSet_ = true;
- if (indexValue === undefined) {
- indexValue = null;
- }
- newParams.indexStartValue_ = indexValue;
- if (key != null) {
- newParams.startNameSet_ = true;
- newParams.indexStartName_ = key;
- }
- else {
- newParams.startNameSet_ = false;
- newParams.indexStartName_ = '';
- }
- return newParams;
- }
- function queryParamsStartAfter(queryParams, indexValue, key) {
- let params;
- if (queryParams.index_ === KEY_INDEX || !!key) {
- params = queryParamsStartAt(queryParams, indexValue, key);
- }
- else {
- params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
- }
- params.startAfterSet_ = true;
- return params;
- }
- function queryParamsEndAt(queryParams, indexValue, key) {
- const newParams = queryParams.copy();
- newParams.endSet_ = true;
- if (indexValue === undefined) {
- indexValue = null;
- }
- newParams.indexEndValue_ = indexValue;
- if (key !== undefined) {
- newParams.endNameSet_ = true;
- newParams.indexEndName_ = key;
- }
- else {
- newParams.endNameSet_ = false;
- newParams.indexEndName_ = '';
- }
- return newParams;
- }
- function queryParamsEndBefore(queryParams, indexValue, key) {
- let params;
- if (queryParams.index_ === KEY_INDEX || !!key) {
- params = queryParamsEndAt(queryParams, indexValue, key);
- }
- else {
- params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
- }
- params.endBeforeSet_ = true;
- return params;
- }
- function queryParamsOrderBy(queryParams, index) {
- const newParams = queryParams.copy();
- newParams.index_ = index;
- return newParams;
- }
-
- function queryParamsToRestQueryStringParameters(queryParams) {
- const qs = {};
- if (queryParams.isDefault()) {
- return qs;
- }
- let orderBy;
- if (queryParams.index_ === PRIORITY_INDEX) {
- orderBy = "$priority" ;
- }
- else if (queryParams.index_ === VALUE_INDEX) {
- orderBy = "$value" ;
- }
- else if (queryParams.index_ === KEY_INDEX) {
- orderBy = "$key" ;
- }
- else {
- assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
- orderBy = queryParams.index_.toString();
- }
- qs["orderBy" ] = stringify(orderBy);
- if (queryParams.startSet_) {
- const startParam = queryParams.startAfterSet_
- ? "startAfter"
- : "startAt" ;
- qs[startParam] = stringify(queryParams.indexStartValue_);
- if (queryParams.startNameSet_) {
- qs[startParam] += ',' + stringify(queryParams.indexStartName_);
- }
- }
- if (queryParams.endSet_) {
- const endParam = queryParams.endBeforeSet_
- ? "endBefore"
- : "endAt" ;
- qs[endParam] = stringify(queryParams.indexEndValue_);
- if (queryParams.endNameSet_) {
- qs[endParam] += ',' + stringify(queryParams.indexEndName_);
- }
- }
- if (queryParams.limitSet_) {
- if (queryParams.isViewFromLeft()) {
- qs["limitToFirst" ] = queryParams.limit_;
- }
- else {
- qs["limitToLast" ] = queryParams.limit_;
- }
- }
- return qs;
- }
- function queryParamsGetQueryObject(queryParams) {
- const obj = {};
- if (queryParams.startSet_) {
- obj["sp" ] =
- queryParams.indexStartValue_;
- if (queryParams.startNameSet_) {
- obj["sn" ] =
- queryParams.indexStartName_;
- }
- obj["sin" ] =
- !queryParams.startAfterSet_;
- }
- if (queryParams.endSet_) {
- obj["ep" ] = queryParams.indexEndValue_;
- if (queryParams.endNameSet_) {
- obj["en" ] = queryParams.indexEndName_;
- }
- obj["ein" ] =
- !queryParams.endBeforeSet_;
- }
- if (queryParams.limitSet_) {
- obj["l" ] = queryParams.limit_;
- let viewFrom = queryParams.viewFrom_;
- if (viewFrom === '') {
- if (queryParams.isViewFromLeft()) {
- viewFrom = "l" ;
- }
- else {
- viewFrom = "r" ;
- }
- }
- obj["vf" ] = viewFrom;
- }
-
- if (queryParams.index_ !== PRIORITY_INDEX) {
- obj["i" ] = queryParams.index_.toString();
- }
- return obj;
- }
-
-
-
- class ReadonlyRestClient extends ServerActions {
-
-
- constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
- super();
- this.repoInfo_ = repoInfo_;
- this.onDataUpdate_ = onDataUpdate_;
- this.authTokenProvider_ = authTokenProvider_;
- this.appCheckTokenProvider_ = appCheckTokenProvider_;
-
- this.log_ = logWrapper('p:rest:');
-
-
- this.listens_ = {};
- }
- reportStats(stats) {
- throw new Error('Method not implemented.');
- }
- static getListenId_(query, tag) {
- if (tag !== undefined) {
- return 'tag$' + tag;
- }
- else {
- assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
- return query._path.toString();
- }
- }
-
- listen(query, currentHashFn, tag, onComplete) {
- const pathString = query._path.toString();
- this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
-
- const listenId = ReadonlyRestClient.getListenId_(query, tag);
- const thisListen = {};
- this.listens_[listenId] = thisListen;
- const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
- this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
- let data = result;
- if (error === 404) {
- data = null;
- error = null;
- }
- if (error === null) {
- this.onDataUpdate_(pathString, data, false, tag);
- }
- if (safeGet(this.listens_, listenId) === thisListen) {
- let status;
- if (!error) {
- status = 'ok';
- }
- else if (error === 401) {
- status = 'permission_denied';
- }
- else {
- status = 'rest_error:' + error;
- }
- onComplete(status, null);
- }
- });
- }
-
- unlisten(query, tag) {
- const listenId = ReadonlyRestClient.getListenId_(query, tag);
- delete this.listens_[listenId];
- }
- get(query) {
- const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
- const pathString = query._path.toString();
- const deferred = new Deferred();
- this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
- let data = result;
- if (error === 404) {
- data = null;
- error = null;
- }
- if (error === null) {
- this.onDataUpdate_(pathString, data,
- false,
- null);
- deferred.resolve(data);
- }
- else {
- deferred.reject(new Error(data));
- }
- });
- return deferred.promise;
- }
-
- refreshAuthToken(token) {
-
- }
-
-
- restRequest_(pathString, queryStringParameters = {}, callback) {
- queryStringParameters['format'] = 'export';
- return Promise.all([
- this.authTokenProvider_.getToken( false),
- this.appCheckTokenProvider_.getToken( false)
- ]).then(([authToken, appCheckToken]) => {
- if (authToken && authToken.accessToken) {
- queryStringParameters['auth'] = authToken.accessToken;
- }
- if (appCheckToken && appCheckToken.token) {
- queryStringParameters['ac'] = appCheckToken.token;
- }
- const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
- this.repoInfo_.host +
- pathString +
- '?' +
- 'ns=' +
- this.repoInfo_.namespace +
- querystring(queryStringParameters);
- this.log_('Sending REST request for ' + url);
- const xhr = new XMLHttpRequest();
- xhr.onreadystatechange = () => {
- if (callback && xhr.readyState === 4) {
- this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
- let res = null;
- if (xhr.status >= 200 && xhr.status < 300) {
- try {
- res = jsonEval(xhr.responseText);
- }
- catch (e) {
- warn('Failed to parse JSON response for ' +
- url +
- ': ' +
- xhr.responseText);
- }
- callback(null, res);
- }
- else {
-
- if (xhr.status !== 401 && xhr.status !== 404) {
- warn('Got unsuccessful REST response for ' +
- url +
- ' Status: ' +
- xhr.status);
- }
- callback(xhr.status);
- }
- callback = null;
- }
- };
- xhr.open('GET', url, true);
- xhr.send();
- });
- }
- }
-
-
-
- class SnapshotHolder {
- constructor() {
- this.rootNode_ = ChildrenNode.EMPTY_NODE;
- }
- getNode(path) {
- return this.rootNode_.getChild(path);
- }
- updateSnapshot(path, newSnapshotNode) {
- this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
- }
- }
-
-
- function newSparseSnapshotTree() {
- return {
- value: null,
- children: new Map()
- };
- }
-
- function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
- if (pathIsEmpty(path)) {
- sparseSnapshotTree.value = data;
- sparseSnapshotTree.children.clear();
- }
- else if (sparseSnapshotTree.value !== null) {
- sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
- }
- else {
- const childKey = pathGetFront(path);
- if (!sparseSnapshotTree.children.has(childKey)) {
- sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
- }
- const child = sparseSnapshotTree.children.get(childKey);
- path = pathPopFront(path);
- sparseSnapshotTreeRemember(child, path, data);
- }
- }
-
- function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
- if (pathIsEmpty(path)) {
- sparseSnapshotTree.value = null;
- sparseSnapshotTree.children.clear();
- return true;
- }
- else {
- if (sparseSnapshotTree.value !== null) {
- if (sparseSnapshotTree.value.isLeafNode()) {
-
- return false;
- }
- else {
- const value = sparseSnapshotTree.value;
- sparseSnapshotTree.value = null;
- value.forEachChild(PRIORITY_INDEX, (key, tree) => {
- sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
- });
- return sparseSnapshotTreeForget(sparseSnapshotTree, path);
- }
- }
- else if (sparseSnapshotTree.children.size > 0) {
- const childKey = pathGetFront(path);
- path = pathPopFront(path);
- if (sparseSnapshotTree.children.has(childKey)) {
- const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
- if (safeToRemove) {
- sparseSnapshotTree.children.delete(childKey);
- }
- }
- return sparseSnapshotTree.children.size === 0;
- }
- else {
- return true;
- }
- }
- }
-
- function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
- if (sparseSnapshotTree.value !== null) {
- func(prefixPath, sparseSnapshotTree.value);
- }
- else {
- sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
- const path = new Path(prefixPath.toString() + '/' + key);
- sparseSnapshotTreeForEachTree(tree, path, func);
- });
- }
- }
-
- function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
- sparseSnapshotTree.children.forEach((tree, key) => {
- func(key, tree);
- });
- }
-
-
-
- class StatsListener {
- constructor(collection_) {
- this.collection_ = collection_;
- this.last_ = null;
- }
- get() {
- const newStats = this.collection_.get();
- const delta = Object.assign({}, newStats);
- if (this.last_) {
- each(this.last_, (stat, value) => {
- delta[stat] = delta[stat] - value;
- });
- }
- this.last_ = newStats;
- return delta;
- }
- }
-
-
-
-
-
- const FIRST_STATS_MIN_TIME = 10 * 1000;
- const FIRST_STATS_MAX_TIME = 30 * 1000;
-
- const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
- class StatsReporter {
- constructor(collection, server_) {
- this.server_ = server_;
- this.statsToReport_ = {};
- this.statsListener_ = new StatsListener(collection);
- const timeout = FIRST_STATS_MIN_TIME +
- (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
- setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
- }
- reportStats_() {
- const stats = this.statsListener_.get();
- const reportedStats = {};
- let haveStatsToReport = false;
- each(stats, (stat, value) => {
- if (value > 0 && contains(this.statsToReport_, stat)) {
- reportedStats[stat] = value;
- haveStatsToReport = true;
- }
- });
- if (haveStatsToReport) {
- this.server_.reportStats(reportedStats);
- }
-
- setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
- }
- }
-
-
-
- var OperationType;
- (function (OperationType) {
- OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
- OperationType[OperationType["MERGE"] = 1] = "MERGE";
- OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
- OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
- })(OperationType || (OperationType = {}));
- function newOperationSourceUser() {
- return {
- fromUser: true,
- fromServer: false,
- queryId: null,
- tagged: false
- };
- }
- function newOperationSourceServer() {
- return {
- fromUser: false,
- fromServer: true,
- queryId: null,
- tagged: false
- };
- }
- function newOperationSourceServerTaggedQuery(queryId) {
- return {
- fromUser: false,
- fromServer: true,
- queryId,
- tagged: true
- };
- }
-
-
- class AckUserWrite {
-
-
- constructor(
- /** @inheritDoc */ path,
- /** @inheritDoc */ affectedTree,
- /** @inheritDoc */ revert) {
- this.path = path;
- this.affectedTree = affectedTree;
- this.revert = revert;
-
- this.type = OperationType.ACK_USER_WRITE;
-
- this.source = newOperationSourceUser();
- }
- operationForChild(childName) {
- if (!pathIsEmpty(this.path)) {
- assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
- return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
- }
- else if (this.affectedTree.value != null) {
- assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
-
- return this;
- }
- else {
- const childTree = this.affectedTree.subtree(new Path(childName));
- return new AckUserWrite(newEmptyPath(), childTree, this.revert);
- }
- }
- }
-
-
- class ListenComplete {
- constructor(source, path) {
- this.source = source;
- this.path = path;
-
- this.type = OperationType.LISTEN_COMPLETE;
- }
- operationForChild(childName) {
- if (pathIsEmpty(this.path)) {
- return new ListenComplete(this.source, newEmptyPath());
- }
- else {
- return new ListenComplete(this.source, pathPopFront(this.path));
- }
- }
- }
-
-
- class Overwrite {
- constructor(source, path, snap) {
- this.source = source;
- this.path = path;
- this.snap = snap;
-
- this.type = OperationType.OVERWRITE;
- }
- operationForChild(childName) {
- if (pathIsEmpty(this.path)) {
- return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
- }
- else {
- return new Overwrite(this.source, pathPopFront(this.path), this.snap);
- }
- }
- }
-
-
- class Merge {
- constructor(
- /** @inheritDoc */ source,
- /** @inheritDoc */ path,
- /** @inheritDoc */ children) {
- this.source = source;
- this.path = path;
- this.children = children;
-
- this.type = OperationType.MERGE;
- }
- operationForChild(childName) {
- if (pathIsEmpty(this.path)) {
- const childTree = this.children.subtree(new Path(childName));
- if (childTree.isEmpty()) {
-
- return null;
- }
- else if (childTree.value) {
-
- return new Overwrite(this.source, newEmptyPath(), childTree.value);
- }
- else {
-
- return new Merge(this.source, newEmptyPath(), childTree);
- }
- }
- else {
- assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
- return new Merge(this.source, pathPopFront(this.path), this.children);
- }
- }
- toString() {
- return ('Operation(' +
- this.path +
- ': ' +
- this.source.toString() +
- ' merge: ' +
- this.children.toString() +
- ')');
- }
- }
-
-
-
- class CacheNode {
- constructor(node_, fullyInitialized_, filtered_) {
- this.node_ = node_;
- this.fullyInitialized_ = fullyInitialized_;
- this.filtered_ = filtered_;
- }
-
-
- isFullyInitialized() {
- return this.fullyInitialized_;
- }
-
-
- isFiltered() {
- return this.filtered_;
- }
- isCompleteForPath(path) {
- if (pathIsEmpty(path)) {
- return this.isFullyInitialized() && !this.filtered_;
- }
- const childKey = pathGetFront(path);
- return this.isCompleteForChild(childKey);
- }
- isCompleteForChild(key) {
- return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
- }
- getNode() {
- return this.node_;
- }
- }
-
-
-
- class EventGenerator {
- constructor(query_) {
- this.query_ = query_;
- this.index_ = this.query_._queryParams.getIndex();
- }
- }
-
- function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
- const events = [];
- const moves = [];
- changes.forEach(change => {
- if (change.type === "child_changed" &&
- eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
- moves.push(changeChildMoved(change.childName, change.snapshotNode));
- }
- });
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" , moves, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" , changes, eventRegistrations, eventCache);
- eventGeneratorGenerateEventsForType(eventGenerator, events, "value" , changes, eventRegistrations, eventCache);
- return events;
- }
-
- function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
- const filteredChanges = changes.filter(change => change.type === eventType);
- filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
- filteredChanges.forEach(change => {
- const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
- registrations.forEach(registration => {
- if (registration.respondsTo(change.type)) {
- events.push(registration.createEvent(materializedChange, eventGenerator.query_));
- }
- });
- });
- }
- function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
- if (change.type === 'value' || change.type === 'child_removed') {
- return change;
- }
- else {
- change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
- return change;
- }
- }
- function eventGeneratorCompareChanges(eventGenerator, a, b) {
- if (a.childName == null || b.childName == null) {
- throw assertionError('Should only compare child_ events.');
- }
- const aWrapped = new NamedNode(a.childName, a.snapshotNode);
- const bWrapped = new NamedNode(b.childName, b.snapshotNode);
- return eventGenerator.index_.compare(aWrapped, bWrapped);
- }
-
-
- function newViewCache(eventCache, serverCache) {
- return { eventCache, serverCache };
- }
- function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
- return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
- }
- function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
- return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
- }
- function viewCacheGetCompleteEventSnap(viewCache) {
- return viewCache.eventCache.isFullyInitialized()
- ? viewCache.eventCache.getNode()
- : null;
- }
- function viewCacheGetCompleteServerSnap(viewCache) {
- return viewCache.serverCache.isFullyInitialized()
- ? viewCache.serverCache.getNode()
- : null;
- }
-
-
- let emptyChildrenSingleton;
-
- const EmptyChildren = () => {
- if (!emptyChildrenSingleton) {
- emptyChildrenSingleton = new SortedMap(stringCompare);
- }
- return emptyChildrenSingleton;
- };
-
- class ImmutableTree {
- constructor(value, children = EmptyChildren()) {
- this.value = value;
- this.children = children;
- }
- static fromObject(obj) {
- let tree = new ImmutableTree(null);
- each(obj, (childPath, childSnap) => {
- tree = tree.set(new Path(childPath), childSnap);
- });
- return tree;
- }
-
-
- isEmpty() {
- return this.value === null && this.children.isEmpty();
- }
-
-
- findRootMostMatchingPathAndValue(relativePath, predicate) {
- if (this.value != null && predicate(this.value)) {
- return { path: newEmptyPath(), value: this.value };
- }
- else {
- if (pathIsEmpty(relativePath)) {
- return null;
- }
- else {
- const front = pathGetFront(relativePath);
- const child = this.children.get(front);
- if (child !== null) {
- const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
- if (childExistingPathAndValue != null) {
- const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
- return { path: fullPath, value: childExistingPathAndValue.value };
- }
- else {
- return null;
- }
- }
- else {
- return null;
- }
- }
- }
- }
-
-
- findRootMostValueAndPath(relativePath) {
- return this.findRootMostMatchingPathAndValue(relativePath, () => true);
- }
-
-
- subtree(relativePath) {
- if (pathIsEmpty(relativePath)) {
- return this;
- }
- else {
- const front = pathGetFront(relativePath);
- const childTree = this.children.get(front);
- if (childTree !== null) {
- return childTree.subtree(pathPopFront(relativePath));
- }
- else {
- return new ImmutableTree(null);
- }
- }
- }
-
-
- set(relativePath, toSet) {
- if (pathIsEmpty(relativePath)) {
- return new ImmutableTree(toSet, this.children);
- }
- else {
- const front = pathGetFront(relativePath);
- const child = this.children.get(front) || new ImmutableTree(null);
- const newChild = child.set(pathPopFront(relativePath), toSet);
- const newChildren = this.children.insert(front, newChild);
- return new ImmutableTree(this.value, newChildren);
- }
- }
-
-
- remove(relativePath) {
- if (pathIsEmpty(relativePath)) {
- if (this.children.isEmpty()) {
- return new ImmutableTree(null);
- }
- else {
- return new ImmutableTree(null, this.children);
- }
- }
- else {
- const front = pathGetFront(relativePath);
- const child = this.children.get(front);
- if (child) {
- const newChild = child.remove(pathPopFront(relativePath));
- let newChildren;
- if (newChild.isEmpty()) {
- newChildren = this.children.remove(front);
- }
- else {
- newChildren = this.children.insert(front, newChild);
- }
- if (this.value === null && newChildren.isEmpty()) {
- return new ImmutableTree(null);
- }
- else {
- return new ImmutableTree(this.value, newChildren);
- }
- }
- else {
- return this;
- }
- }
- }
-
-
- get(relativePath) {
- if (pathIsEmpty(relativePath)) {
- return this.value;
- }
- else {
- const front = pathGetFront(relativePath);
- const child = this.children.get(front);
- if (child) {
- return child.get(pathPopFront(relativePath));
- }
- else {
- return null;
- }
- }
- }
-
-
- setTree(relativePath, newTree) {
- if (pathIsEmpty(relativePath)) {
- return newTree;
- }
- else {
- const front = pathGetFront(relativePath);
- const child = this.children.get(front) || new ImmutableTree(null);
- const newChild = child.setTree(pathPopFront(relativePath), newTree);
- let newChildren;
- if (newChild.isEmpty()) {
- newChildren = this.children.remove(front);
- }
- else {
- newChildren = this.children.insert(front, newChild);
- }
- return new ImmutableTree(this.value, newChildren);
- }
- }
-
-
- fold(fn) {
- return this.fold_(newEmptyPath(), fn);
- }
-
-
- fold_(pathSoFar, fn) {
- const accum = {};
- this.children.inorderTraversal((childKey, childTree) => {
- accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
- });
- return fn(pathSoFar, this.value, accum);
- }
-
-
- findOnPath(path, f) {
- return this.findOnPath_(path, newEmptyPath(), f);
- }
- findOnPath_(pathToFollow, pathSoFar, f) {
- const result = this.value ? f(pathSoFar, this.value) : false;
- if (result) {
- return result;
- }
- else {
- if (pathIsEmpty(pathToFollow)) {
- return null;
- }
- else {
- const front = pathGetFront(pathToFollow);
- const nextChild = this.children.get(front);
- if (nextChild) {
- return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
- }
- else {
- return null;
- }
- }
- }
- }
- foreachOnPath(path, f) {
- return this.foreachOnPath_(path, newEmptyPath(), f);
- }
- foreachOnPath_(pathToFollow, currentRelativePath, f) {
- if (pathIsEmpty(pathToFollow)) {
- return this;
- }
- else {
- if (this.value) {
- f(currentRelativePath, this.value);
- }
- const front = pathGetFront(pathToFollow);
- const nextChild = this.children.get(front);
- if (nextChild) {
- return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
- }
- else {
- return new ImmutableTree(null);
- }
- }
- }
-
-
- foreach(f) {
- this.foreach_(newEmptyPath(), f);
- }
- foreach_(currentRelativePath, f) {
- this.children.inorderTraversal((childName, childTree) => {
- childTree.foreach_(pathChild(currentRelativePath, childName), f);
- });
- if (this.value) {
- f(currentRelativePath, this.value);
- }
- }
- foreachChild(f) {
- this.children.inorderTraversal((childName, childTree) => {
- if (childTree.value) {
- f(childName, childTree.value);
- }
- });
- }
- }
-
-
-
- class CompoundWrite {
- constructor(writeTree_) {
- this.writeTree_ = writeTree_;
- }
- static empty() {
- return new CompoundWrite(new ImmutableTree(null));
- }
- }
- function compoundWriteAddWrite(compoundWrite, path, node) {
- if (pathIsEmpty(path)) {
- return new CompoundWrite(new ImmutableTree(node));
- }
- else {
- const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
- if (rootmost != null) {
- const rootMostPath = rootmost.path;
- let value = rootmost.value;
- const relativePath = newRelativePath(rootMostPath, path);
- value = value.updateChild(relativePath, node);
- return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
- }
- else {
- const subtree = new ImmutableTree(node);
- const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
- return new CompoundWrite(newWriteTree);
- }
- }
- }
- function compoundWriteAddWrites(compoundWrite, path, updates) {
- let newWrite = compoundWrite;
- each(updates, (childKey, node) => {
- newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
- });
- return newWrite;
- }
-
- function compoundWriteRemoveWrite(compoundWrite, path) {
- if (pathIsEmpty(path)) {
- return CompoundWrite.empty();
- }
- else {
- const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
- return new CompoundWrite(newWriteTree);
- }
- }
-
- function compoundWriteHasCompleteWrite(compoundWrite, path) {
- return compoundWriteGetCompleteNode(compoundWrite, path) != null;
- }
-
- function compoundWriteGetCompleteNode(compoundWrite, path) {
- const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
- if (rootmost != null) {
- return compoundWrite.writeTree_
- .get(rootmost.path)
- .getChild(newRelativePath(rootmost.path, path));
- }
- else {
- return null;
- }
- }
-
- function compoundWriteGetCompleteChildren(compoundWrite) {
- const children = [];
- const node = compoundWrite.writeTree_.value;
- if (node != null) {
-
- if (!node.isLeafNode()) {
- node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
- children.push(new NamedNode(childName, childNode));
- });
- }
- }
- else {
- compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
- if (childTree.value != null) {
- children.push(new NamedNode(childName, childTree.value));
- }
- });
- }
- return children;
- }
- function compoundWriteChildCompoundWrite(compoundWrite, path) {
- if (pathIsEmpty(path)) {
- return compoundWrite;
- }
- else {
- const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
- if (shadowingNode != null) {
- return new CompoundWrite(new ImmutableTree(shadowingNode));
- }
- else {
- return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
- }
- }
- }
-
- function compoundWriteIsEmpty(compoundWrite) {
- return compoundWrite.writeTree_.isEmpty();
- }
-
- function compoundWriteApply(compoundWrite, node) {
- return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
- }
- function applySubtreeWrite(relativePath, writeTree, node) {
- if (writeTree.value != null) {
-
- return node.updateChild(relativePath, writeTree.value);
- }
- else {
- let priorityWrite = null;
- writeTree.children.inorderTraversal((childKey, childTree) => {
- if (childKey === '.priority') {
-
-
- assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
- priorityWrite = childTree.value;
- }
- else {
- node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
- }
- });
-
- if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
- node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
- }
- return node;
- }
- }
-
-
-
- function writeTreeChildWrites(writeTree, path) {
- return newWriteTreeRef(path, writeTree);
- }
-
- function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
- assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
- if (visible === undefined) {
- visible = true;
- }
- writeTree.allWrites.push({
- path,
- snap,
- writeId,
- visible
- });
- if (visible) {
- writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
- }
- writeTree.lastWriteId = writeId;
- }
-
- function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
- assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
- writeTree.allWrites.push({
- path,
- children: changedChildren,
- writeId,
- visible: true
- });
- writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
- writeTree.lastWriteId = writeId;
- }
- function writeTreeGetWrite(writeTree, writeId) {
- for (let i = 0; i < writeTree.allWrites.length; i++) {
- const record = writeTree.allWrites[i];
- if (record.writeId === writeId) {
- return record;
- }
- }
- return null;
- }
-
- function writeTreeRemoveWrite(writeTree, writeId) {
-
-
-
-
- const idx = writeTree.allWrites.findIndex(s => {
- return s.writeId === writeId;
- });
- assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
- const writeToRemove = writeTree.allWrites[idx];
- writeTree.allWrites.splice(idx, 1);
- let removedWriteWasVisible = writeToRemove.visible;
- let removedWriteOverlapsWithOtherWrites = false;
- let i = writeTree.allWrites.length - 1;
- while (removedWriteWasVisible && i >= 0) {
- const currentWrite = writeTree.allWrites[i];
- if (currentWrite.visible) {
- if (i >= idx &&
- writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
-
- removedWriteWasVisible = false;
- }
- else if (pathContains(writeToRemove.path, currentWrite.path)) {
-
- removedWriteOverlapsWithOtherWrites = true;
- }
- }
- i--;
- }
- if (!removedWriteWasVisible) {
- return false;
- }
- else if (removedWriteOverlapsWithOtherWrites) {
-
- writeTreeResetTree_(writeTree);
- return true;
- }
- else {
-
- if (writeToRemove.snap) {
- writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
- }
- else {
- const children = writeToRemove.children;
- each(children, (childName) => {
- writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
- });
- }
- return true;
- }
- }
- function writeTreeRecordContainsPath_(writeRecord, path) {
- if (writeRecord.snap) {
- return pathContains(writeRecord.path, path);
- }
- else {
- for (const childName in writeRecord.children) {
- if (writeRecord.children.hasOwnProperty(childName) &&
- pathContains(pathChild(writeRecord.path, childName), path)) {
- return true;
- }
- }
- return false;
- }
- }
-
- function writeTreeResetTree_(writeTree) {
- writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
- if (writeTree.allWrites.length > 0) {
- writeTree.lastWriteId =
- writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
- }
- else {
- writeTree.lastWriteId = -1;
- }
- }
-
- function writeTreeDefaultFilter_(write) {
- return write.visible;
- }
-
- function writeTreeLayerTree_(writes, filter, treeRoot) {
- let compoundWrite = CompoundWrite.empty();
- for (let i = 0; i < writes.length; ++i) {
- const write = writes[i];
-
-
-
- if (filter(write)) {
- const writePath = write.path;
- let relativePath;
- if (write.snap) {
- if (pathContains(treeRoot, writePath)) {
- relativePath = newRelativePath(treeRoot, writePath);
- compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
- }
- else if (pathContains(writePath, treeRoot)) {
- relativePath = newRelativePath(writePath, treeRoot);
- compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
- }
- else ;
- }
- else if (write.children) {
- if (pathContains(treeRoot, writePath)) {
- relativePath = newRelativePath(treeRoot, writePath);
- compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
- }
- else if (pathContains(writePath, treeRoot)) {
- relativePath = newRelativePath(writePath, treeRoot);
- if (pathIsEmpty(relativePath)) {
- compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
- }
- else {
- const child = safeGet(write.children, pathGetFront(relativePath));
- if (child) {
-
- const deepNode = child.getChild(pathPopFront(relativePath));
- compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
- }
- }
- }
- else ;
- }
- else {
- throw assertionError('WriteRecord should have .snap or .children');
- }
- }
- }
- return compoundWrite;
- }
-
- function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
- if (!writeIdsToExclude && !includeHiddenWrites) {
- const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
- if (shadowingNode != null) {
- return shadowingNode;
- }
- else {
- const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- if (compoundWriteIsEmpty(subMerge)) {
- return completeServerCache;
- }
- else if (completeServerCache == null &&
- !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
-
- return null;
- }
- else {
- const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
- return compoundWriteApply(subMerge, layeredCache);
- }
- }
- }
- else {
- const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
- return completeServerCache;
- }
- else {
-
- if (!includeHiddenWrites &&
- completeServerCache == null &&
- !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
- return null;
- }
- else {
- const filter = function (write) {
- return ((write.visible || includeHiddenWrites) &&
- (!writeIdsToExclude ||
- !~writeIdsToExclude.indexOf(write.writeId)) &&
- (pathContains(write.path, treePath) ||
- pathContains(treePath, write.path)));
- };
- const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
- const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
- return compoundWriteApply(mergeAtPath, layeredCache);
- }
- }
- }
- }
-
- function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
- let completeChildren = ChildrenNode.EMPTY_NODE;
- const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
- if (topLevelSet) {
- if (!topLevelSet.isLeafNode()) {
-
- topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
- completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
- });
- }
- return completeChildren;
- }
- else if (completeServerChildren) {
-
-
- const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
- const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
- completeChildren = completeChildren.updateImmediateChild(childName, node);
- });
-
- compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
- completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
- });
- return completeChildren;
- }
- else {
-
-
- const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
- completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
- });
- return completeChildren;
- }
- }
-
- function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
- assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
- const path = pathChild(treePath, childPath);
- if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
-
-
- return null;
- }
- else {
-
- const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
- if (compoundWriteIsEmpty(childMerge)) {
-
- return existingServerSnap.getChild(childPath);
- }
- else {
-
-
-
-
-
-
- return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
- }
- }
- }
-
- function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
- const path = pathChild(treePath, childKey);
- const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
- if (shadowingNode != null) {
- return shadowingNode;
- }
- else {
- if (existingServerSnap.isCompleteForChild(childKey)) {
- const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
- return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
- }
- else {
- return null;
- }
- }
- }
-
- function writeTreeShadowingWrite(writeTree, path) {
- return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
- }
-
- function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
- let toIterate;
- const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
- const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
- if (shadowingNode != null) {
- toIterate = shadowingNode;
- }
- else if (completeServerData != null) {
- toIterate = compoundWriteApply(merge, completeServerData);
- }
- else {
-
- return [];
- }
- toIterate = toIterate.withIndex(index);
- if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
- const nodes = [];
- const cmp = index.getCompare();
- const iter = reverse
- ? toIterate.getReverseIteratorFrom(startPost, index)
- : toIterate.getIteratorFrom(startPost, index);
- let next = iter.getNext();
- while (next && nodes.length < count) {
- if (cmp(next, startPost) !== 0) {
- nodes.push(next);
- }
- next = iter.getNext();
- }
- return nodes;
- }
- else {
- return [];
- }
- }
- function newWriteTree() {
- return {
- visibleWrites: CompoundWrite.empty(),
- allWrites: [],
- lastWriteId: -1
- };
- }
-
- function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
- return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
- }
-
- function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
- return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
- }
-
- function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
- return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
- }
-
- function writeTreeRefShadowingWrite(writeTreeRef, path) {
- return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
- }
-
- function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
- return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
- }
-
- function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
- return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
- }
-
- function writeTreeRefChild(writeTreeRef, childName) {
- return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
- }
- function newWriteTreeRef(path, writeTree) {
- return {
- treePath: path,
- writeTree
- };
- }
-
-
- class ChildChangeAccumulator {
- constructor() {
- this.changeMap = new Map();
- }
- trackChildChange(change) {
- const type = change.type;
- const childKey = change.childName;
- assert(type === "child_added" ||
- type === "child_changed" ||
- type === "child_removed" , 'Only child changes supported for tracking');
- assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
- const oldChange = this.changeMap.get(childKey);
- if (oldChange) {
- const oldType = oldChange.type;
- if (type === "child_added" &&
- oldType === "child_removed" ) {
- this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
- }
- else if (type === "child_removed" &&
- oldType === "child_added" ) {
- this.changeMap.delete(childKey);
- }
- else if (type === "child_removed" &&
- oldType === "child_changed" ) {
- this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
- }
- else if (type === "child_changed" &&
- oldType === "child_added" ) {
- this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
- }
- else if (type === "child_changed" &&
- oldType === "child_changed" ) {
- this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
- }
- else {
- throw assertionError('Illegal combination of changes: ' +
- change +
- ' occurred after ' +
- oldChange);
- }
- }
- else {
- this.changeMap.set(childKey, change);
- }
- }
- getChanges() {
- return Array.from(this.changeMap.values());
- }
- }
-
-
-
-
- class NoCompleteChildSource_ {
- getCompleteChild(childKey) {
- return null;
- }
- getChildAfterChild(index, child, reverse) {
- return null;
- }
- }
-
- const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
-
- class WriteTreeCompleteChildSource {
- constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
- this.writes_ = writes_;
- this.viewCache_ = viewCache_;
- this.optCompleteServerCache_ = optCompleteServerCache_;
- }
- getCompleteChild(childKey) {
- const node = this.viewCache_.eventCache;
- if (node.isCompleteForChild(childKey)) {
- return node.getNode().getImmediateChild(childKey);
- }
- else {
- const serverNode = this.optCompleteServerCache_ != null
- ? new CacheNode(this.optCompleteServerCache_, true, false)
- : this.viewCache_.serverCache;
- return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
- }
- }
- getChildAfterChild(index, child, reverse) {
- const completeServerData = this.optCompleteServerCache_ != null
- ? this.optCompleteServerCache_
- : viewCacheGetCompleteServerSnap(this.viewCache_);
- const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
- if (nodes.length === 0) {
- return null;
- }
- else {
- return nodes[0];
- }
- }
- }
-
-
- function newViewProcessor(filter) {
- return { filter };
- }
- function viewProcessorAssertIndexed(viewProcessor, viewCache) {
- assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
- assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
- }
- function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
- const accumulator = new ChildChangeAccumulator();
- let newViewCache, filterServerNode;
- if (operation.type === OperationType.OVERWRITE) {
- const overwrite = operation;
- if (overwrite.source.fromUser) {
- newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
- }
- else {
- assert(overwrite.source.fromServer, 'Unknown source.');
-
-
-
- filterServerNode =
- overwrite.source.tagged ||
- (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
- newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- else if (operation.type === OperationType.MERGE) {
- const merge = operation;
- if (merge.source.fromUser) {
- newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
- }
- else {
- assert(merge.source.fromServer, 'Unknown source.');
-
- filterServerNode =
- merge.source.tagged || oldViewCache.serverCache.isFiltered();
- newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- else if (operation.type === OperationType.ACK_USER_WRITE) {
- const ackUserWrite = operation;
- if (!ackUserWrite.revert) {
- newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
- }
- else {
- newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
- }
- }
- else if (operation.type === OperationType.LISTEN_COMPLETE) {
- newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
- }
- else {
- throw assertionError('Unknown operation type: ' + operation.type);
- }
- const changes = accumulator.getChanges();
- viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
- return { viewCache: newViewCache, changes };
- }
- function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
- const eventSnap = newViewCache.eventCache;
- if (eventSnap.isFullyInitialized()) {
- const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
- const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
- if (accumulator.length > 0 ||
- !oldViewCache.eventCache.isFullyInitialized() ||
- (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
- !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
- accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
- }
- }
- }
- function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
- const oldEventSnap = viewCache.eventCache;
- if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
-
- return viewCache;
- }
- else {
- let newEventCache, serverNode;
- if (pathIsEmpty(changePath)) {
-
- assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
- if (viewCache.serverCache.isFiltered()) {
-
-
-
- const serverCache = viewCacheGetCompleteServerSnap(viewCache);
- const completeChildren = serverCache instanceof ChildrenNode
- ? serverCache
- : ChildrenNode.EMPTY_NODE;
- const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
- newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
- }
- else {
- const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
- }
- }
- else {
- const childKey = pathGetFront(changePath);
- if (childKey === '.priority') {
- assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
- const oldEventNode = oldEventSnap.getNode();
- serverNode = viewCache.serverCache.getNode();
-
- const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
- if (updatedPriority != null) {
- newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
- }
- else {
-
- newEventCache = oldEventSnap.getNode();
- }
- }
- else {
- const childChangePath = pathPopFront(changePath);
-
- let newEventChild;
- if (oldEventSnap.isCompleteForChild(childKey)) {
- serverNode = viewCache.serverCache.getNode();
- const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
- if (eventChildUpdate != null) {
- newEventChild = oldEventSnap
- .getNode()
- .getImmediateChild(childKey)
- .updateChild(childChangePath, eventChildUpdate);
- }
- else {
-
- newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
- }
- }
- else {
- newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
- }
- if (newEventChild != null) {
- newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
- }
- else {
-
- newEventCache = oldEventSnap.getNode();
- }
- }
- }
- return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
- }
- }
- function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
- const oldServerSnap = oldViewCache.serverCache;
- let newServerCache;
- const serverFilter = filterServerNode
- ? viewProcessor.filter
- : viewProcessor.filter.getIndexedFilter();
- if (pathIsEmpty(changePath)) {
- newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
- }
- else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
-
- const newServerNode = oldServerSnap
- .getNode()
- .updateChild(changePath, changedSnap);
- newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
- }
- else {
- const childKey = pathGetFront(changePath);
- if (!oldServerSnap.isCompleteForPath(changePath) &&
- pathGetLength(changePath) > 1) {
-
- return oldViewCache;
- }
- const childChangePath = pathPopFront(changePath);
- const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
- const newChildNode = childNode.updateChild(childChangePath, changedSnap);
- if (childKey === '.priority') {
- newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
- }
- else {
- newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
- }
- }
- const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
- const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
- return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
- }
- function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
- const oldEventSnap = oldViewCache.eventCache;
- let newViewCache, newEventCache;
- const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
- if (pathIsEmpty(changePath)) {
- newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
- }
- else {
- const childKey = pathGetFront(changePath);
- if (childKey === '.priority') {
- newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
- }
- else {
- const childChangePath = pathPopFront(changePath);
- const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
- let newChild;
- if (pathIsEmpty(childChangePath)) {
-
- newChild = changedSnap;
- }
- else {
- const childNode = source.getCompleteChild(childKey);
- if (childNode != null) {
- if (pathGetBack(childChangePath) === '.priority' &&
- childNode.getChild(pathParent(childChangePath)).isEmpty()) {
-
-
- newChild = childNode;
- }
- else {
- newChild = childNode.updateChild(childChangePath, changedSnap);
- }
- }
- else {
-
- newChild = ChildrenNode.EMPTY_NODE;
- }
- }
- if (!oldChild.equals(newChild)) {
- const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
- newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
- }
- else {
- newViewCache = oldViewCache;
- }
- }
- }
- return newViewCache;
- }
- function viewProcessorCacheHasChild(viewCache, childKey) {
- return viewCache.eventCache.isCompleteForChild(childKey);
- }
- function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
-
-
-
-
-
-
- let curViewCache = viewCache;
- changedChildren.foreach((relativePath, childNode) => {
- const writePath = pathChild(path, relativePath);
- if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
- curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
- }
- });
- changedChildren.foreach((relativePath, childNode) => {
- const writePath = pathChild(path, relativePath);
- if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
- curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
- }
- });
- return curViewCache;
- }
- function viewProcessorApplyMerge(viewProcessor, node, merge) {
- merge.foreach((relativePath, childNode) => {
- node = node.updateChild(relativePath, childNode);
- });
- return node;
- }
- function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
-
-
- if (viewCache.serverCache.getNode().isEmpty() &&
- !viewCache.serverCache.isFullyInitialized()) {
- return viewCache;
- }
-
-
-
-
-
-
- let curViewCache = viewCache;
- let viewMergeTree;
- if (pathIsEmpty(path)) {
- viewMergeTree = changedChildren;
- }
- else {
- viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
- }
- const serverNode = viewCache.serverCache.getNode();
- viewMergeTree.children.inorderTraversal((childKey, childTree) => {
- if (serverNode.hasChild(childKey)) {
- const serverChild = viewCache.serverCache
- .getNode()
- .getImmediateChild(childKey);
- const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
- curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
- }
- });
- viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
- const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
- childMergeTree.value === null;
- if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
- const serverChild = viewCache.serverCache
- .getNode()
- .getImmediateChild(childKey);
- const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
- curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
- }
- });
- return curViewCache;
- }
- function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
- if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
- return viewCache;
- }
-
- const filterServerNode = viewCache.serverCache.isFiltered();
-
-
- const serverCache = viewCache.serverCache;
- if (affectedTree.value != null) {
-
- if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
- serverCache.isCompleteForPath(ackPath)) {
- return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
- }
- else if (pathIsEmpty(ackPath)) {
-
-
- let changedChildren = new ImmutableTree(null);
- serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
- changedChildren = changedChildren.set(new Path(name), node);
- });
- return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
- }
- else {
- return viewCache;
- }
- }
- else {
-
- let changedChildren = new ImmutableTree(null);
- affectedTree.foreach((mergePath, value) => {
- const serverCachePath = pathChild(ackPath, mergePath);
- if (serverCache.isCompleteForPath(serverCachePath)) {
- changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
- }
- });
- return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
- }
- }
- function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
- const oldServerNode = viewCache.serverCache;
- const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
- return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
- }
- function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
- let complete;
- if (writeTreeRefShadowingWrite(writesCache, path) != null) {
- return viewCache;
- }
- else {
- const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
- const oldEventCache = viewCache.eventCache.getNode();
- let newEventCache;
- if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
- let newNode;
- if (viewCache.serverCache.isFullyInitialized()) {
- newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- }
- else {
- const serverChildren = viewCache.serverCache.getNode();
- assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
- newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
- }
- newNode = newNode;
- newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
- }
- else {
- const childKey = pathGetFront(path);
- let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
- if (newChild == null &&
- viewCache.serverCache.isCompleteForChild(childKey)) {
- newChild = oldEventCache.getImmediateChild(childKey);
- }
- if (newChild != null) {
- newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
- }
- else if (viewCache.eventCache.getNode().hasChild(childKey)) {
-
- newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
- }
- else {
- newEventCache = oldEventCache;
- }
- if (newEventCache.isEmpty() &&
- viewCache.serverCache.isFullyInitialized()) {
-
- complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
- if (complete.isLeafNode()) {
- newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
- }
- }
- }
- complete =
- viewCache.serverCache.isFullyInitialized() ||
- writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
- return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
- }
- }
-
-
-
- class View {
- constructor(query_, initialViewCache) {
- this.query_ = query_;
- this.eventRegistrations_ = [];
- const params = this.query_._queryParams;
- const indexFilter = new IndexedFilter(params.getIndex());
- const filter = queryParamsGetNodeFilter(params);
- this.processor_ = newViewProcessor(filter);
- const initialServerCache = initialViewCache.serverCache;
- const initialEventCache = initialViewCache.eventCache;
-
- const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
- const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
- const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
- const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
- this.viewCache_ = newViewCache(newEventCache, newServerCache);
- this.eventGenerator_ = new EventGenerator(this.query_);
- }
- get query() {
- return this.query_;
- }
- }
- function viewGetServerCache(view) {
- return view.viewCache_.serverCache.getNode();
- }
- function viewGetCompleteNode(view) {
- return viewCacheGetCompleteEventSnap(view.viewCache_);
- }
- function viewGetCompleteServerCache(view, path) {
- const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
- if (cache) {
-
-
- if (view.query._queryParams.loadsAllData() ||
- (!pathIsEmpty(path) &&
- !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
- return cache.getChild(path);
- }
- }
- return null;
- }
- function viewIsEmpty(view) {
- return view.eventRegistrations_.length === 0;
- }
- function viewAddEventRegistration(view, eventRegistration) {
- view.eventRegistrations_.push(eventRegistration);
- }
-
- function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
- const cancelEvents = [];
- if (cancelError) {
- assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
- const path = view.query._path;
- view.eventRegistrations_.forEach(registration => {
- const maybeEvent = registration.createCancelEvent(cancelError, path);
- if (maybeEvent) {
- cancelEvents.push(maybeEvent);
- }
- });
- }
- if (eventRegistration) {
- let remaining = [];
- for (let i = 0; i < view.eventRegistrations_.length; ++i) {
- const existing = view.eventRegistrations_[i];
- if (!existing.matches(eventRegistration)) {
- remaining.push(existing);
- }
- else if (eventRegistration.hasAnyCallback()) {
-
- remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
- break;
- }
- }
- view.eventRegistrations_ = remaining;
- }
- else {
- view.eventRegistrations_ = [];
- }
- return cancelEvents;
- }
-
- function viewApplyOperation(view, operation, writesCache, completeServerCache) {
- if (operation.type === OperationType.MERGE &&
- operation.source.queryId !== null) {
- assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
- assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
- }
- const oldViewCache = view.viewCache_;
- const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
- viewProcessorAssertIndexed(view.processor_, result.viewCache);
- assert(result.viewCache.serverCache.isFullyInitialized() ||
- !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
- view.viewCache_ = result.viewCache;
- return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
- }
- function viewGetInitialEvents(view, registration) {
- const eventSnap = view.viewCache_.eventCache;
- const initialChanges = [];
- if (!eventSnap.getNode().isLeafNode()) {
- const eventNode = eventSnap.getNode();
- eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
- initialChanges.push(changeChildAdded(key, childNode));
- });
- }
- if (eventSnap.isFullyInitialized()) {
- initialChanges.push(changeValue(eventSnap.getNode()));
- }
- return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
- }
- function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
- const registrations = eventRegistration
- ? [eventRegistration]
- : view.eventRegistrations_;
- return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
- }
-
-
- let referenceConstructor$1;
-
- class SyncPoint {
- constructor() {
-
-
- this.views = new Map();
- }
- }
- function syncPointSetReferenceConstructor(val) {
- assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
- referenceConstructor$1 = val;
- }
- function syncPointGetReferenceConstructor() {
- assert(referenceConstructor$1, 'Reference.ts has not been loaded');
- return referenceConstructor$1;
- }
- function syncPointIsEmpty(syncPoint) {
- return syncPoint.views.size === 0;
- }
- function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
- const queryId = operation.source.queryId;
- if (queryId !== null) {
- const view = syncPoint.views.get(queryId);
- assert(view != null, 'SyncTree gave us an op for an invalid query.');
- return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
- }
- else {
- let events = [];
- for (const view of syncPoint.views.values()) {
- events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
- }
- return events;
- }
- }
-
- function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
- const queryId = query._queryIdentifier;
- const view = syncPoint.views.get(queryId);
- if (!view) {
-
- let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
- let eventCacheComplete = false;
- if (eventCache) {
- eventCacheComplete = true;
- }
- else if (serverCache instanceof ChildrenNode) {
- eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
- eventCacheComplete = false;
- }
- else {
- eventCache = ChildrenNode.EMPTY_NODE;
- eventCacheComplete = false;
- }
- const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
- return new View(query, viewCache);
- }
- return view;
- }
-
- function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
- const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
- if (!syncPoint.views.has(query._queryIdentifier)) {
- syncPoint.views.set(query._queryIdentifier, view);
- }
-
- viewAddEventRegistration(view, eventRegistration);
- return viewGetInitialEvents(view, eventRegistration);
- }
-
- function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
- const queryId = query._queryIdentifier;
- const removed = [];
- let cancelEvents = [];
- const hadCompleteView = syncPointHasCompleteView(syncPoint);
- if (queryId === 'default') {
-
- for (const [viewQueryId, view] of syncPoint.views.entries()) {
- cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
- if (viewIsEmpty(view)) {
- syncPoint.views.delete(viewQueryId);
-
- if (!view.query._queryParams.loadsAllData()) {
- removed.push(view.query);
- }
- }
- }
- }
- else {
-
- const view = syncPoint.views.get(queryId);
- if (view) {
- cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
- if (viewIsEmpty(view)) {
- syncPoint.views.delete(queryId);
-
- if (!view.query._queryParams.loadsAllData()) {
- removed.push(view.query);
- }
- }
- }
- }
- if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
-
- removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
- }
- return { removed, events: cancelEvents };
- }
- function syncPointGetQueryViews(syncPoint) {
- const result = [];
- for (const view of syncPoint.views.values()) {
- if (!view.query._queryParams.loadsAllData()) {
- result.push(view);
- }
- }
- return result;
- }
-
- function syncPointGetCompleteServerCache(syncPoint, path) {
- let serverCache = null;
- for (const view of syncPoint.views.values()) {
- serverCache = serverCache || viewGetCompleteServerCache(view, path);
- }
- return serverCache;
- }
- function syncPointViewForQuery(syncPoint, query) {
- const params = query._queryParams;
- if (params.loadsAllData()) {
- return syncPointGetCompleteView(syncPoint);
- }
- else {
- const queryId = query._queryIdentifier;
- return syncPoint.views.get(queryId);
- }
- }
- function syncPointViewExistsForQuery(syncPoint, query) {
- return syncPointViewForQuery(syncPoint, query) != null;
- }
- function syncPointHasCompleteView(syncPoint) {
- return syncPointGetCompleteView(syncPoint) != null;
- }
- function syncPointGetCompleteView(syncPoint) {
- for (const view of syncPoint.views.values()) {
- if (view.query._queryParams.loadsAllData()) {
- return view;
- }
- }
- return null;
- }
-
-
- let referenceConstructor;
- function syncTreeSetReferenceConstructor(val) {
- assert(!referenceConstructor, '__referenceConstructor has already been defined');
- referenceConstructor = val;
- }
- function syncTreeGetReferenceConstructor() {
- assert(referenceConstructor, 'Reference.ts has not been loaded');
- return referenceConstructor;
- }
-
- let syncTreeNextQueryTag_ = 1;
-
- class SyncTree {
-
-
- constructor(listenProvider_) {
- this.listenProvider_ = listenProvider_;
-
-
- this.syncPointTree_ = new ImmutableTree(null);
-
-
- this.pendingWriteTree_ = newWriteTree();
- this.tagToQueryMap = new Map();
- this.queryToTagMap = new Map();
- }
- }
-
- function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
-
- writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
- if (!visible) {
- return [];
- }
- else {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
- }
- }
-
- function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
-
- writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
- const changeTree = ImmutableTree.fromObject(changedChildren);
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
- }
-
- function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
- const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
- const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
- if (!needToReevaluate) {
- return [];
- }
- else {
- let affectedTree = new ImmutableTree(null);
- if (write.snap != null) {
-
- affectedTree = affectedTree.set(newEmptyPath(), true);
- }
- else {
- each(write.children, (pathString) => {
- affectedTree = affectedTree.set(new Path(pathString), true);
- });
- }
- return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
- }
- }
-
- function syncTreeApplyServerOverwrite(syncTree, path, newData) {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
- }
-
- function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
- const changeTree = ImmutableTree.fromObject(changedChildren);
- return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
- }
-
- function syncTreeApplyListenComplete(syncTree, path) {
- return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
- }
-
- function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
- const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey) {
- const r = syncTreeParseQueryKey_(queryKey);
- const queryPath = r.path, queryId = r.queryId;
- const relativePath = newRelativePath(queryPath, path);
- const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
-
- const path = query._path;
- const maybeSyncPoint = syncTree.syncPointTree_.get(path);
- let cancelEvents = [];
-
-
-
- if (maybeSyncPoint &&
- (query._queryIdentifier === 'default' ||
- syncPointViewExistsForQuery(maybeSyncPoint, query))) {
- const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
- if (syncPointIsEmpty(maybeSyncPoint)) {
- syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
- }
- const removed = removedAndEvents.removed;
- cancelEvents = removedAndEvents.events;
- if (!skipListenerDedup) {
-
-
-
-
- const removingDefault = -1 !==
- removed.findIndex(query => {
- return query._queryParams.loadsAllData();
- });
- const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
- if (removingDefault && !covered) {
- const subtree = syncTree.syncPointTree_.subtree(path);
-
-
- if (!subtree.isEmpty()) {
-
- const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
-
- for (let i = 0; i < newViews.length; ++i) {
- const view = newViews[i], newQuery = view.query;
- const listener = syncTreeCreateListenerForView_(syncTree, view);
- syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
- }
- }
-
- }
-
-
-
- if (!covered && removed.length > 0 && !cancelError) {
-
-
- if (removingDefault) {
-
- const defaultTag = null;
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
- }
- else {
- removed.forEach((queryToRemove) => {
- const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
- });
- }
- }
- }
-
- syncTreeRemoveTags_(syncTree, removed);
- }
- return cancelEvents;
- }
-
- function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
- const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey != null) {
- const r = syncTreeParseQueryKey_(queryKey);
- const queryPath = r.path, queryId = r.queryId;
- const relativePath = newRelativePath(queryPath, path);
- const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
- const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
- if (queryKey) {
- const r = syncTreeParseQueryKey_(queryKey);
- const queryPath = r.path, queryId = r.queryId;
- const relativePath = newRelativePath(queryPath, path);
- const changeTree = ImmutableTree.fromObject(changedChildren);
- const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
- return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
- }
- else {
-
- return [];
- }
- }
-
- function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
- const path = query._path;
- let serverCache = null;
- let foundAncestorDefaultView = false;
-
-
- syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
- const relativePath = newRelativePath(pathToSyncPoint, path);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(sp, relativePath);
- foundAncestorDefaultView =
- foundAncestorDefaultView || syncPointHasCompleteView(sp);
- });
- let syncPoint = syncTree.syncPointTree_.get(path);
- if (!syncPoint) {
- syncPoint = new SyncPoint();
- syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
- }
- else {
- foundAncestorDefaultView =
- foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- let serverCacheComplete;
- if (serverCache != null) {
- serverCacheComplete = true;
- }
- else {
- serverCacheComplete = false;
- serverCache = ChildrenNode.EMPTY_NODE;
- const subtree = syncTree.syncPointTree_.subtree(path);
- subtree.foreachChild((childName, childSyncPoint) => {
- const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
- if (completeCache) {
- serverCache = serverCache.updateImmediateChild(childName, completeCache);
- }
- });
- }
- const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
- if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
-
- const queryKey = syncTreeMakeQueryKey_(query);
- assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
- const tag = syncTreeGetNextQueryTag_();
- syncTree.queryToTagMap.set(queryKey, tag);
- syncTree.tagToQueryMap.set(tag, queryKey);
- }
- const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
- let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
- if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
- const view = syncPointViewForQuery(syncPoint, query);
- events = events.concat(syncTreeSetupListener_(syncTree, query, view));
- }
- return events;
- }
-
- function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
- const includeHiddenSets = true;
- const writeTree = syncTree.pendingWriteTree_;
- const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
- const relativePath = newRelativePath(pathSoFar, path);
- const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
- if (serverCache) {
- return serverCache;
- }
- });
- return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
- }
- function syncTreeGetServerValue(syncTree, query) {
- const path = query._path;
- let serverCache = null;
-
-
- syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
- const relativePath = newRelativePath(pathToSyncPoint, path);
- serverCache =
- serverCache || syncPointGetCompleteServerCache(sp, relativePath);
- });
- let syncPoint = syncTree.syncPointTree_.get(path);
- if (!syncPoint) {
- syncPoint = new SyncPoint();
- syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
- }
- else {
- serverCache =
- serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- const serverCacheComplete = serverCache != null;
- const serverCacheNode = serverCacheComplete
- ? new CacheNode(serverCache, true, false)
- : null;
- const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
- const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
- return viewGetCompleteNode(view);
- }
-
- function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
- return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
- null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
- }
-
- function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
- if (pathIsEmpty(operation.path)) {
- return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
- }
- else {
- const syncPoint = syncPointTree.get(newEmptyPath());
-
- if (serverCache == null && syncPoint != null) {
- serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- let events = [];
- const childName = pathGetFront(operation.path);
- const childOperation = operation.operationForChild(childName);
- const childTree = syncPointTree.children.get(childName);
- if (childTree && childOperation) {
- const childServerCache = serverCache
- ? serverCache.getImmediateChild(childName)
- : null;
- const childWritesCache = writeTreeRefChild(writesCache, childName);
- events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
- }
- if (syncPoint) {
- events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
- }
- return events;
- }
- }
-
- function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
- const syncPoint = syncPointTree.get(newEmptyPath());
-
- if (serverCache == null && syncPoint != null) {
- serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
- }
- let events = [];
- syncPointTree.children.inorderTraversal((childName, childTree) => {
- const childServerCache = serverCache
- ? serverCache.getImmediateChild(childName)
- : null;
- const childWritesCache = writeTreeRefChild(writesCache, childName);
- const childOperation = operation.operationForChild(childName);
- if (childOperation) {
- events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
- }
- });
- if (syncPoint) {
- events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
- }
- return events;
- }
- function syncTreeCreateListenerForView_(syncTree, view) {
- const query = view.query;
- const tag = syncTreeTagForQuery(syncTree, query);
- return {
- hashFn: () => {
- const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
- return cache.hash();
- },
- onComplete: (status) => {
- if (status === 'ok') {
- if (tag) {
- return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
- }
- else {
- return syncTreeApplyListenComplete(syncTree, query._path);
- }
- }
- else {
-
-
- const error = errorForServerCode(status, query);
- return syncTreeRemoveEventRegistration(syncTree, query,
- null, error);
- }
- }
- };
- }
-
- function syncTreeTagForQuery(syncTree, query) {
- const queryKey = syncTreeMakeQueryKey_(query);
- return syncTree.queryToTagMap.get(queryKey);
- }
-
- function syncTreeMakeQueryKey_(query) {
- return query._path.toString() + '$' + query._queryIdentifier;
- }
-
- function syncTreeQueryKeyForTag_(syncTree, tag) {
- return syncTree.tagToQueryMap.get(tag);
- }
-
- function syncTreeParseQueryKey_(queryKey) {
- const splitIndex = queryKey.indexOf('$');
- assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
- return {
- queryId: queryKey.substr(splitIndex + 1),
- path: new Path(queryKey.substr(0, splitIndex))
- };
- }
-
- function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
- const syncPoint = syncTree.syncPointTree_.get(queryPath);
- assert(syncPoint, "Missing sync point for query tag that we're tracking");
- const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
- return syncPointApplyOperation(syncPoint, operation, writesCache, null);
- }
-
- function syncTreeCollectDistinctViewsForSubTree_(subtree) {
- return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
- if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
- const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
- return [completeView];
- }
- else {
-
- let views = [];
- if (maybeChildSyncPoint) {
- views = syncPointGetQueryViews(maybeChildSyncPoint);
- }
- each(childMap, (_key, childViews) => {
- views = views.concat(childViews);
- });
- return views;
- }
- });
- }
-
- function syncTreeQueryForListening_(query) {
- if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
-
-
-
- return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
- }
- else {
- return query;
- }
- }
- function syncTreeRemoveTags_(syncTree, queries) {
- for (let j = 0; j < queries.length; ++j) {
- const removedQuery = queries[j];
- if (!removedQuery._queryParams.loadsAllData()) {
-
- const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
- const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
- syncTree.queryToTagMap.delete(removedQueryKey);
- syncTree.tagToQueryMap.delete(removedQueryTag);
- }
- }
- }
-
- function syncTreeGetNextQueryTag_() {
- return syncTreeNextQueryTag_++;
- }
-
- function syncTreeSetupListener_(syncTree, query, view) {
- const path = query._path;
- const tag = syncTreeTagForQuery(syncTree, query);
- const listener = syncTreeCreateListenerForView_(syncTree, view);
- const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
- const subtree = syncTree.syncPointTree_.subtree(path);
-
-
- if (tag) {
- assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
- }
- else {
-
- const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
- if (!pathIsEmpty(relativePath) &&
- maybeChildSyncPoint &&
- syncPointHasCompleteView(maybeChildSyncPoint)) {
- return [syncPointGetCompleteView(maybeChildSyncPoint).query];
- }
- else {
-
- let queries = [];
- if (maybeChildSyncPoint) {
- queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
- }
- each(childMap, (_key, childQueries) => {
- queries = queries.concat(childQueries);
- });
- return queries;
- }
- });
- for (let i = 0; i < queriesToStop.length; ++i) {
- const queryToStop = queriesToStop[i];
- syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
- }
- }
- return events;
- }
-
-
- class ExistingValueProvider {
- constructor(node_) {
- this.node_ = node_;
- }
- getImmediateChild(childName) {
- const child = this.node_.getImmediateChild(childName);
- return new ExistingValueProvider(child);
- }
- node() {
- return this.node_;
- }
- }
- class DeferredValueProvider {
- constructor(syncTree, path) {
- this.syncTree_ = syncTree;
- this.path_ = path;
- }
- getImmediateChild(childName) {
- const childPath = pathChild(this.path_, childName);
- return new DeferredValueProvider(this.syncTree_, childPath);
- }
- node() {
- return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
- }
- }
-
- const generateWithValues = function (values) {
- values = values || {};
- values['timestamp'] = values['timestamp'] || new Date().getTime();
- return values;
- };
-
- const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
- if (!value || typeof value !== 'object') {
- return value;
- }
- assert('.sv' in value, 'Unexpected leaf node or priority contents');
- if (typeof value['.sv'] === 'string') {
- return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
- }
- else if (typeof value['.sv'] === 'object') {
- return resolveComplexDeferredValue(value['.sv'], existingVal);
- }
- else {
- assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
- }
- };
- const resolveScalarDeferredValue = function (op, existing, serverValues) {
- switch (op) {
- case 'timestamp':
- return serverValues['timestamp'];
- default:
- assert(false, 'Unexpected server value: ' + op);
- }
- };
- const resolveComplexDeferredValue = function (op, existing, unused) {
- if (!op.hasOwnProperty('increment')) {
- assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
- }
- const delta = op['increment'];
- if (typeof delta !== 'number') {
- assert(false, 'Unexpected increment value: ' + delta);
- }
- const existingNode = existing.node();
- assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
-
- if (!existingNode.isLeafNode()) {
- return delta;
- }
- const leaf = existingNode;
- const existingVal = leaf.getValue();
- if (typeof existingVal !== 'number') {
- return delta;
- }
-
- return existingVal + delta;
- };
-
- const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
- return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
- };
-
- const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
- return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
- };
- function resolveDeferredValue(node, existingVal, serverValues) {
- const rawPri = node.getPriority().val();
- const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
- let newNode;
- if (node.isLeafNode()) {
- const leafNode = node;
- const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
- if (value !== leafNode.getValue() ||
- priority !== leafNode.getPriority().val()) {
- return new LeafNode(value, nodeFromJSON(priority));
- }
- else {
- return node;
- }
- }
- else {
- const childrenNode = node;
- newNode = childrenNode;
- if (priority !== childrenNode.getPriority().val()) {
- newNode = newNode.updatePriority(new LeafNode(priority));
- }
- childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
- const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
- if (newChildNode !== childNode) {
- newNode = newNode.updateImmediateChild(childName, newChildNode);
- }
- });
- return newNode;
- }
- }
-
-
-
- class Tree {
-
-
- constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
- this.name = name;
- this.parent = parent;
- this.node = node;
- }
- }
-
- function treeSubTree(tree, pathObj) {
-
- let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
- let child = tree, next = pathGetFront(path);
- while (next !== null) {
- const childNode = safeGet(child.node.children, next) || {
- children: {},
- childCount: 0
- };
- child = new Tree(next, child, childNode);
- path = pathPopFront(path);
- next = pathGetFront(path);
- }
- return child;
- }
-
- function treeGetValue(tree) {
- return tree.node.value;
- }
-
- function treeSetValue(tree, value) {
- tree.node.value = value;
- treeUpdateParents(tree);
- }
-
- function treeHasChildren(tree) {
- return tree.node.childCount > 0;
- }
-
- function treeIsEmpty(tree) {
- return treeGetValue(tree) === undefined && !treeHasChildren(tree);
- }
-
- function treeForEachChild(tree, action) {
- each(tree.node.children, (child, childTree) => {
- action(new Tree(child, tree, childTree));
- });
- }
-
- function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
- if (includeSelf && !childrenFirst) {
- action(tree);
- }
- treeForEachChild(tree, child => {
- treeForEachDescendant(child, action, true, childrenFirst);
- });
- if (includeSelf && childrenFirst) {
- action(tree);
- }
- }
-
- function treeForEachAncestor(tree, action, includeSelf) {
- let node = includeSelf ? tree : tree.parent;
- while (node !== null) {
- if (action(node)) {
- return true;
- }
- node = node.parent;
- }
- return false;
- }
-
- function treeGetPath(tree) {
- return new Path(tree.parent === null
- ? tree.name
- : treeGetPath(tree.parent) + '/' + tree.name);
- }
-
- function treeUpdateParents(tree) {
- if (tree.parent !== null) {
- treeUpdateChild(tree.parent, tree.name, tree);
- }
- }
-
- function treeUpdateChild(tree, childName, child) {
- const childEmpty = treeIsEmpty(child);
- const childExists = contains(tree.node.children, childName);
- if (childEmpty && childExists) {
- delete tree.node.children[childName];
- tree.node.childCount--;
- treeUpdateParents(tree);
- }
- else if (!childEmpty && !childExists) {
- tree.node.children[childName] = child.node;
- tree.node.childCount++;
- treeUpdateParents(tree);
- }
- }
-
-
-
- const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
-
- const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
-
- const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
- const isValidKey = function (key) {
- return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
- };
- const isValidPathString = function (pathString) {
- return (typeof pathString === 'string' &&
- pathString.length !== 0 &&
- !INVALID_PATH_REGEX_.test(pathString));
- };
- const isValidRootPathString = function (pathString) {
- if (pathString) {
-
- pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
- }
- return isValidPathString(pathString);
- };
- const isValidPriority = function (priority) {
- return (priority === null ||
- typeof priority === 'string' ||
- (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
- (priority &&
- typeof priority === 'object' &&
-
- contains(priority, '.sv')));
- };
-
- const validateFirebaseDataArg = function (fnName, value, path, optional) {
- if (optional && value === undefined) {
- return;
- }
- validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
- };
-
- const validateFirebaseData = function (errorPrefix, data, path_) {
- const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
- if (data === undefined) {
- throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
- }
- if (typeof data === 'function') {
- throw new Error(errorPrefix +
- 'contains a function ' +
- validationPathToErrorString(path) +
- ' with contents = ' +
- data.toString());
- }
- if (isInvalidJSONNumber(data)) {
- throw new Error(errorPrefix +
- 'contains ' +
- data.toString() +
- ' ' +
- validationPathToErrorString(path));
- }
-
- if (typeof data === 'string' &&
- data.length > MAX_LEAF_SIZE_ / 3 &&
- stringLength(data) > MAX_LEAF_SIZE_) {
- throw new Error(errorPrefix +
- 'contains a string greater than ' +
- MAX_LEAF_SIZE_ +
- ' utf8 bytes ' +
- validationPathToErrorString(path) +
- " ('" +
- data.substring(0, 50) +
- "...')");
- }
-
-
- if (data && typeof data === 'object') {
- let hasDotValue = false;
- let hasActualChild = false;
- each(data, (key, value) => {
- if (key === '.value') {
- hasDotValue = true;
- }
- else if (key !== '.priority' && key !== '.sv') {
- hasActualChild = true;
- if (!isValidKey(key)) {
- throw new Error(errorPrefix +
- ' contains an invalid key (' +
- key +
- ') ' +
- validationPathToErrorString(path) +
- '. Keys must be non-empty strings ' +
- 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
- }
- }
- validationPathPush(path, key);
- validateFirebaseData(errorPrefix, value, path);
- validationPathPop(path);
- });
- if (hasDotValue && hasActualChild) {
- throw new Error(errorPrefix +
- ' contains ".value" child ' +
- validationPathToErrorString(path) +
- ' in addition to actual children.');
- }
- }
- };
-
- const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
- let i, curPath;
- for (i = 0; i < mergePaths.length; i++) {
- curPath = mergePaths[i];
- const keys = pathSlice(curPath);
- for (let j = 0; j < keys.length; j++) {
- if (keys[j] === '.priority' && j === keys.length - 1) ;
- else if (!isValidKey(keys[j])) {
- throw new Error(errorPrefix +
- 'contains an invalid key (' +
- keys[j] +
- ') in path ' +
- curPath.toString() +
- '. Keys must be non-empty strings ' +
- 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
- }
- }
- }
-
-
-
- mergePaths.sort(pathCompare);
- let prevPath = null;
- for (i = 0; i < mergePaths.length; i++) {
- curPath = mergePaths[i];
- if (prevPath !== null && pathContains(prevPath, curPath)) {
- throw new Error(errorPrefix +
- 'contains a path ' +
- prevPath.toString() +
- ' that is ancestor of another path ' +
- curPath.toString());
- }
- prevPath = curPath;
- }
- };
-
- const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
- if (optional && data === undefined) {
- return;
- }
- const errorPrefix$1 = errorPrefix(fnName, 'values');
- if (!(data && typeof data === 'object') || Array.isArray(data)) {
- throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
- }
- const mergePaths = [];
- each(data, (key, value) => {
- const curPath = new Path(key);
- validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
- if (pathGetBack(curPath) === '.priority') {
- if (!isValidPriority(value)) {
- throw new Error(errorPrefix$1 +
- "contains an invalid value for '" +
- curPath.toString() +
- "', which must be a valid " +
- 'Firebase priority (a string, finite number, server value, or null).');
- }
- }
- mergePaths.push(curPath);
- });
- validateFirebaseMergePaths(errorPrefix$1, mergePaths);
- };
- const validatePriority = function (fnName, priority, optional) {
- if (optional && priority === undefined) {
- return;
- }
- if (isInvalidJSONNumber(priority)) {
- throw new Error(errorPrefix(fnName, 'priority') +
- 'is ' +
- priority.toString() +
- ', but must be a valid Firebase priority (a string, finite number, ' +
- 'server value, or null).');
- }
-
- if (!isValidPriority(priority)) {
- throw new Error(errorPrefix(fnName, 'priority') +
- 'must be a valid Firebase priority ' +
- '(a string, finite number, server value, or null).');
- }
- };
- const validateKey = function (fnName, argumentName, key, optional) {
- if (optional && key === undefined) {
- return;
- }
- if (!isValidKey(key)) {
- throw new Error(errorPrefix(fnName, argumentName) +
- 'was an invalid key = "' +
- key +
- '". Firebase keys must be non-empty strings and ' +
- 'can\'t contain ".", "#", "$", "/", "[", or "]").');
- }
- };
-
- const validatePathString = function (fnName, argumentName, pathString, optional) {
- if (optional && pathString === undefined) {
- return;
- }
- if (!isValidPathString(pathString)) {
- throw new Error(errorPrefix(fnName, argumentName) +
- 'was an invalid path = "' +
- pathString +
- '". Paths must be non-empty strings and ' +
- 'can\'t contain ".", "#", "$", "[", or "]"');
- }
- };
- const validateRootPathString = function (fnName, argumentName, pathString, optional) {
- if (pathString) {
-
- pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
- }
- validatePathString(fnName, argumentName, pathString, optional);
- };
-
- const validateWritablePath = function (fnName, path) {
- if (pathGetFront(path) === '.info') {
- throw new Error(fnName + " failed = Can't modify data under /.info/");
- }
- };
- const validateUrl = function (fnName, parsedUrl) {
-
- const pathString = parsedUrl.path.toString();
- if (!(typeof parsedUrl.repoInfo.host === 'string') ||
- parsedUrl.repoInfo.host.length === 0 ||
- (!isValidKey(parsedUrl.repoInfo.namespace) &&
- parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
- (pathString.length !== 0 && !isValidRootPathString(pathString))) {
- throw new Error(errorPrefix(fnName, 'url') +
- 'must be a valid firebase URL and ' +
- 'the path can\'t contain ".", "#", "$", "[", or "]".');
- }
- };
-
-
-
- class EventQueue {
- constructor() {
- this.eventLists_ = [];
-
-
- this.recursionDepth_ = 0;
- }
- }
-
- function eventQueueQueueEvents(eventQueue, eventDataList) {
-
- let currList = null;
- for (let i = 0; i < eventDataList.length; i++) {
- const data = eventDataList[i];
- const path = data.getPath();
- if (currList !== null && !pathEquals(path, currList.path)) {
- eventQueue.eventLists_.push(currList);
- currList = null;
- }
- if (currList === null) {
- currList = { events: [], path };
- }
- currList.events.push(data);
- }
- if (currList) {
- eventQueue.eventLists_.push(currList);
- }
- }
-
- function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
- eventQueueQueueEvents(eventQueue, eventDataList);
- eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
- }
-
- function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
- eventQueueQueueEvents(eventQueue, eventDataList);
- eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
- pathContains(changedPath, eventPath));
- }
- function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
- eventQueue.recursionDepth_++;
- let sentAll = true;
- for (let i = 0; i < eventQueue.eventLists_.length; i++) {
- const eventList = eventQueue.eventLists_[i];
- if (eventList) {
- const eventPath = eventList.path;
- if (predicate(eventPath)) {
- eventListRaise(eventQueue.eventLists_[i]);
- eventQueue.eventLists_[i] = null;
- }
- else {
- sentAll = false;
- }
- }
- }
- if (sentAll) {
- eventQueue.eventLists_ = [];
- }
- eventQueue.recursionDepth_--;
- }
-
- function eventListRaise(eventList) {
- for (let i = 0; i < eventList.events.length; i++) {
- const eventData = eventList.events[i];
- if (eventData !== null) {
- eventList.events[i] = null;
- const eventFn = eventData.getEventRunner();
- if (logger) {
- log('event: ' + eventData.toString());
- }
- exceptionGuard(eventFn);
- }
- }
- }
-
-
- const INTERRUPT_REASON = 'repo_interrupt';
-
- const MAX_TRANSACTION_RETRIES = 25;
-
- class Repo {
- constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
- this.repoInfo_ = repoInfo_;
- this.forceRestClient_ = forceRestClient_;
- this.authTokenProvider_ = authTokenProvider_;
- this.appCheckProvider_ = appCheckProvider_;
- this.dataUpdateCount = 0;
- this.statsListener_ = null;
- this.eventQueue_ = new EventQueue();
- this.nextWriteId_ = 1;
- this.interceptServerDataCallback_ = null;
-
- this.onDisconnect_ = newSparseSnapshotTree();
-
- this.transactionQueueTree_ = new Tree();
-
- this.persistentConnection_ = null;
-
- this.key = this.repoInfo_.toURLString();
- }
-
-
- toString() {
- return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
- }
- }
- function repoStart(repo, appId, authOverride) {
- repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
- if (repo.forceRestClient_ || beingCrawled()) {
- repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
- repoOnDataUpdate(repo, pathString, data, isMerge, tag);
- }, repo.authTokenProvider_, repo.appCheckProvider_);
-
- setTimeout(() => repoOnConnectStatus(repo, true), 0);
- }
- else {
-
- if (typeof authOverride !== 'undefined' && authOverride !== null) {
- if (typeof authOverride !== 'object') {
- throw new Error('Only objects are supported for option databaseAuthVariableOverride');
- }
- try {
- stringify(authOverride);
- }
- catch (e) {
- throw new Error('Invalid authOverride provided: ' + e);
- }
- }
- repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
- repoOnDataUpdate(repo, pathString, data, isMerge, tag);
- }, (connectStatus) => {
- repoOnConnectStatus(repo, connectStatus);
- }, (updates) => {
- repoOnServerInfoUpdate(repo, updates);
- }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
- repo.server_ = repo.persistentConnection_;
- }
- repo.authTokenProvider_.addTokenChangeListener(token => {
- repo.server_.refreshAuthToken(token);
- });
- repo.appCheckProvider_.addTokenChangeListener(result => {
- repo.server_.refreshAppCheckToken(result.token);
- });
-
-
- repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
-
- repo.infoData_ = new SnapshotHolder();
- repo.infoSyncTree_ = new SyncTree({
- startListening: (query, tag, currentHashFn, onComplete) => {
- let infoEvents = [];
- const node = repo.infoData_.getNode(query._path);
-
-
- if (!node.isEmpty()) {
- infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
- setTimeout(() => {
- onComplete('ok');
- }, 0);
- }
- return infoEvents;
- },
- stopListening: () => { }
- });
- repoUpdateInfo(repo, 'connected', false);
- repo.serverSyncTree_ = new SyncTree({
- startListening: (query, tag, currentHashFn, onComplete) => {
- repo.server_.listen(query, currentHashFn, tag, (status, data) => {
- const events = onComplete(status, data);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
- });
-
- return [];
- },
- stopListening: (query, tag) => {
- repo.server_.unlisten(query, tag);
- }
- });
- }
-
- function repoServerTime(repo) {
- const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
- const offset = offsetNode.val() || 0;
- return new Date().getTime() + offset;
- }
-
- function repoGenerateServerValues(repo) {
- return generateWithValues({
- timestamp: repoServerTime(repo)
- });
- }
-
- function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
-
- repo.dataUpdateCount++;
- const path = new Path(pathString);
- data = repo.interceptServerDataCallback_
- ? repo.interceptServerDataCallback_(pathString, data)
- : data;
- let events = [];
- if (tag) {
- if (isMerge) {
- const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
- events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
- }
- else {
- const taggedSnap = nodeFromJSON(data);
- events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
- }
- }
- else if (isMerge) {
- const changedChildren = map(data, (raw) => nodeFromJSON(raw));
- events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
- }
- else {
- const snap = nodeFromJSON(data);
- events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
- }
- let affectedPath = path;
- if (events.length > 0) {
-
-
- affectedPath = repoRerunTransactions(repo, path);
- }
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
- }
- function repoOnConnectStatus(repo, connectStatus) {
- repoUpdateInfo(repo, 'connected', connectStatus);
- if (connectStatus === false) {
- repoRunOnDisconnectEvents(repo);
- }
- }
- function repoOnServerInfoUpdate(repo, updates) {
- each(updates, (key, value) => {
- repoUpdateInfo(repo, key, value);
- });
- }
- function repoUpdateInfo(repo, pathString, value) {
- const path = new Path('/.info/' + pathString);
- const newNode = nodeFromJSON(value);
- repo.infoData_.updateSnapshot(path, newNode);
- const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- }
- function repoGetNextWriteId(repo) {
- return repo.nextWriteId_++;
- }
-
- function repoGetValue(repo, query, eventRegistration) {
-
- const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
- if (cached != null) {
- return Promise.resolve(cached);
- }
- return repo.server_.get(query).then(payload => {
- const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
-
-
- syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
- let events;
- if (query._queryParams.loadsAllData()) {
- events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
- }
- else {
- const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
- events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
- }
-
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
- syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
- return node;
- }, err => {
- repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
- return Promise.reject(new Error(err));
- });
- }
- function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
- repoLog(repo, 'set', {
- path: path.toString(),
- value: newVal,
- priority: newPriority
- });
-
-
- const serverValues = repoGenerateServerValues(repo);
- const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
- const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
- const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
- const writeId = repoGetNextWriteId(repo);
- const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
- eventQueueQueueEvents(repo.eventQueue_, events);
- repo.server_.put(path.toString(), newNodeUnresolved.val( true), (status, errorReason) => {
- const success = status === 'ok';
- if (!success) {
- warn('set at ' + path + ' failed: ' + status);
- }
- const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- const affectedPath = repoAbortTransactions(repo, path);
- repoRerunTransactions(repo, affectedPath);
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
- }
- function repoUpdate(repo, path, childrenToMerge, onComplete) {
- repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
-
- let empty = true;
- const serverValues = repoGenerateServerValues(repo);
- const changedChildren = {};
- each(childrenToMerge, (changedKey, changedValue) => {
- empty = false;
- changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
- });
- if (!empty) {
- const writeId = repoGetNextWriteId(repo);
- const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
- eventQueueQueueEvents(repo.eventQueue_, events);
- repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
- const success = status === 'ok';
- if (!success) {
- warn('update at ' + path + ' failed: ' + status);
- }
- const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
- const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- each(childrenToMerge, (changedPath) => {
- const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
- repoRerunTransactions(repo, affectedPath);
- });
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
- }
- else {
- log("update() called with empty data. Don't do anything.");
- repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
- }
- }
-
- function repoRunOnDisconnectEvents(repo) {
- repoLog(repo, 'onDisconnectEvents');
- const serverValues = repoGenerateServerValues(repo);
- const resolvedOnDisconnectTree = newSparseSnapshotTree();
- sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
- const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
- sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
- });
- let events = [];
- sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
- events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
- const affectedPath = repoAbortTransactions(repo, path);
- repoRerunTransactions(repo, affectedPath);
- });
- repo.onDisconnect_ = newSparseSnapshotTree();
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
- }
- function repoOnDisconnectCancel(repo, path, onComplete) {
- repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
- if (status === 'ok') {
- sparseSnapshotTreeForget(repo.onDisconnect_, path);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectSet(repo, path, value, onComplete) {
- const newNode = nodeFromJSON(value);
- repo.server_.onDisconnectPut(path.toString(), newNode.val( true), (status, errorReason) => {
- if (status === 'ok') {
- sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
- const newNode = nodeFromJSON(value, priority);
- repo.server_.onDisconnectPut(path.toString(), newNode.val( true), (status, errorReason) => {
- if (status === 'ok') {
- sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
- if (isEmpty(childrenToMerge)) {
- log("onDisconnect().update() called with empty data. Don't do anything.");
- repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
- return;
- }
- repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
- if (status === 'ok') {
- each(childrenToMerge, (childName, childNode) => {
- const newChildNode = nodeFromJSON(childNode);
- sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
- });
- }
- repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
- });
- }
- function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
- let events;
- if (pathGetFront(query._path) === '.info') {
- events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
- }
- else {
- events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
- }
- eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
- }
- function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
-
-
- let events;
- if (pathGetFront(query._path) === '.info') {
- events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
- }
- else {
- events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
- }
- eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
- }
- function repoInterrupt(repo) {
- if (repo.persistentConnection_) {
- repo.persistentConnection_.interrupt(INTERRUPT_REASON);
- }
- }
- function repoResume(repo) {
- if (repo.persistentConnection_) {
- repo.persistentConnection_.resume(INTERRUPT_REASON);
- }
- }
- function repoLog(repo, ...varArgs) {
- let prefix = '';
- if (repo.persistentConnection_) {
- prefix = repo.persistentConnection_.id + ':';
- }
- log(prefix, ...varArgs);
- }
- function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
- if (callback) {
- exceptionGuard(() => {
- if (status === 'ok') {
- callback(null);
- }
- else {
- const code = (status || 'error').toUpperCase();
- let message = code;
- if (errorReason) {
- message += ': ' + errorReason;
- }
- const error = new Error(message);
-
- error.code = code;
- callback(error);
- }
- });
- }
- }
-
- function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
- repoLog(repo, 'transaction on ' + path);
-
- const transaction = {
- path,
- update: transactionUpdate,
- onComplete,
-
- status: null,
-
-
- order: LUIDGenerator(),
-
- applyLocally,
-
- retryCount: 0,
-
- unwatcher,
-
- abortReason: null,
- currentWriteId: null,
- currentInputSnapshot: null,
- currentOutputSnapshotRaw: null,
- currentOutputSnapshotResolved: null
- };
-
- const currentState = repoGetLatestState(repo, path, undefined);
- transaction.currentInputSnapshot = currentState;
- const newVal = transaction.update(currentState.val());
- if (newVal === undefined) {
-
- transaction.unwatcher();
- transaction.currentOutputSnapshotRaw = null;
- transaction.currentOutputSnapshotResolved = null;
- if (transaction.onComplete) {
- transaction.onComplete(null, false, transaction.currentInputSnapshot);
- }
- }
- else {
- validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
-
- transaction.status = 0 ;
- const queueNode = treeSubTree(repo.transactionQueueTree_, path);
- const nodeQueue = treeGetValue(queueNode) || [];
- nodeQueue.push(transaction);
- treeSetValue(queueNode, nodeQueue);
-
-
-
-
- let priorityForNode;
- if (typeof newVal === 'object' &&
- newVal !== null &&
- contains(newVal, '.priority')) {
-
- priorityForNode = safeGet(newVal, '.priority');
- assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
- 'Priority must be a valid string, finite number, server value, or null.');
- }
- else {
- const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
- ChildrenNode.EMPTY_NODE;
- priorityForNode = currentNode.getPriority().val();
- }
- const serverValues = repoGenerateServerValues(repo);
- const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
- const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
- transaction.currentOutputSnapshotRaw = newNodeUnresolved;
- transaction.currentOutputSnapshotResolved = newNode;
- transaction.currentWriteId = repoGetNextWriteId(repo);
- const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- }
- }
-
- function repoGetLatestState(repo, path, excludeSets) {
- return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
- ChildrenNode.EMPTY_NODE);
- }
-
- function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
-
- if (!node) {
- repoPruneCompletedTransactionsBelowNode(repo, node);
- }
- if (treeGetValue(node)) {
- const queue = repoBuildTransactionQueue(repo, node);
- assert(queue.length > 0, 'Sending zero length transaction queue');
- const allRun = queue.every((transaction) => transaction.status === 0 );
-
- if (allRun) {
- repoSendTransactionQueue(repo, treeGetPath(node), queue);
- }
- }
- else if (treeHasChildren(node)) {
- treeForEachChild(node, childNode => {
- repoSendReadyTransactions(repo, childNode);
- });
- }
- }
-
- function repoSendTransactionQueue(repo, path, queue) {
-
- const setsToIgnore = queue.map(txn => {
- return txn.currentWriteId;
- });
- const latestState = repoGetLatestState(repo, path, setsToIgnore);
- let snapToSend = latestState;
- const latestHash = latestState.hash();
- for (let i = 0; i < queue.length; i++) {
- const txn = queue[i];
- assert(txn.status === 0 , 'tryToSendTransactionQueue_: items in queue should all be run.');
- txn.status = 1 ;
- txn.retryCount++;
- const relativePath = newRelativePath(path, txn.path);
-
- snapToSend = snapToSend.updateChild(relativePath , txn.currentOutputSnapshotRaw);
- }
- const dataToSend = snapToSend.val(true);
- const pathToSend = path;
-
- repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
- repoLog(repo, 'transaction put response', {
- path: pathToSend.toString(),
- status
- });
- let events = [];
- if (status === 'ok') {
-
-
-
- const callbacks = [];
- for (let i = 0; i < queue.length; i++) {
- queue[i].status = 2 ;
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
- if (queue[i].onComplete) {
-
-
- callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
- }
- queue[i].unwatcher();
- }
-
- repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
-
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
-
- for (let i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
- }
- else {
-
- if (status === 'datastale') {
- for (let i = 0; i < queue.length; i++) {
- if (queue[i].status === 3 ) {
- queue[i].status = 4 ;
- }
- else {
- queue[i].status = 0 ;
- }
- }
- }
- else {
- warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
- for (let i = 0; i < queue.length; i++) {
- queue[i].status = 4 ;
- queue[i].abortReason = status;
- }
- }
- repoRerunTransactions(repo, path);
- }
- }, latestHash);
- }
-
- function repoRerunTransactions(repo, changedPath) {
- const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
- const path = treeGetPath(rootMostTransactionNode);
- const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
- repoRerunTransactionQueue(repo, queue, path);
- return path;
- }
-
- function repoRerunTransactionQueue(repo, queue, path) {
- if (queue.length === 0) {
- return;
- }
-
-
-
- const callbacks = [];
- let events = [];
-
- const txnsToRerun = queue.filter(q => {
- return q.status === 0 ;
- });
- const setsToIgnore = txnsToRerun.map(q => {
- return q.currentWriteId;
- });
- for (let i = 0; i < queue.length; i++) {
- const transaction = queue[i];
- const relativePath = newRelativePath(path, transaction.path);
- let abortTransaction = false, abortReason;
- assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
- if (transaction.status === 4 ) {
- abortTransaction = true;
- abortReason = transaction.abortReason;
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- else if (transaction.status === 0 ) {
- if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
- abortTransaction = true;
- abortReason = 'maxretry';
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- else {
-
- const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
- transaction.currentInputSnapshot = currentNode;
- const newData = queue[i].update(currentNode.val());
- if (newData !== undefined) {
- validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
- let newDataNode = nodeFromJSON(newData);
- const hasExplicitPriority = typeof newData === 'object' &&
- newData != null &&
- contains(newData, '.priority');
- if (!hasExplicitPriority) {
-
- newDataNode = newDataNode.updatePriority(currentNode.getPriority());
- }
- const oldWriteId = transaction.currentWriteId;
- const serverValues = repoGenerateServerValues(repo);
- const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
- transaction.currentOutputSnapshotRaw = newDataNode;
- transaction.currentOutputSnapshotResolved = newNodeResolved;
- transaction.currentWriteId = repoGetNextWriteId(repo);
-
- setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
- events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
- }
- else {
- abortTransaction = true;
- abortReason = 'nodata';
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
- }
- }
- }
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
- events = [];
- if (abortTransaction) {
-
- queue[i].status = 2 ;
-
-
-
- (function (unwatcher) {
- setTimeout(unwatcher, Math.floor(0));
- })(queue[i].unwatcher);
- if (queue[i].onComplete) {
- if (abortReason === 'nodata') {
- callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
- }
- else {
- callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
- }
- }
- }
- }
-
- repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
-
- for (let i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
-
- repoSendReadyTransactions(repo, repo.transactionQueueTree_);
- }
-
- function repoGetAncestorTransactionNode(repo, path) {
- let front;
-
-
- let transactionNode = repo.transactionQueueTree_;
- front = pathGetFront(path);
- while (front !== null && treeGetValue(transactionNode) === undefined) {
- transactionNode = treeSubTree(transactionNode, front);
- path = pathPopFront(path);
- front = pathGetFront(path);
- }
- return transactionNode;
- }
-
- function repoBuildTransactionQueue(repo, transactionNode) {
-
- const transactionQueue = [];
- repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
-
- transactionQueue.sort((a, b) => a.order - b.order);
- return transactionQueue;
- }
- function repoAggregateTransactionQueuesForNode(repo, node, queue) {
- const nodeQueue = treeGetValue(node);
- if (nodeQueue) {
- for (let i = 0; i < nodeQueue.length; i++) {
- queue.push(nodeQueue[i]);
- }
- }
- treeForEachChild(node, child => {
- repoAggregateTransactionQueuesForNode(repo, child, queue);
- });
- }
-
- function repoPruneCompletedTransactionsBelowNode(repo, node) {
- const queue = treeGetValue(node);
- if (queue) {
- let to = 0;
- for (let from = 0; from < queue.length; from++) {
- if (queue[from].status !== 2 ) {
- queue[to] = queue[from];
- to++;
- }
- }
- queue.length = to;
- treeSetValue(node, queue.length > 0 ? queue : undefined);
- }
- treeForEachChild(node, childNode => {
- repoPruneCompletedTransactionsBelowNode(repo, childNode);
- });
- }
-
- function repoAbortTransactions(repo, path) {
- const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
- const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
- treeForEachAncestor(transactionNode, (node) => {
- repoAbortTransactionsOnNode(repo, node);
- });
- repoAbortTransactionsOnNode(repo, transactionNode);
- treeForEachDescendant(transactionNode, (node) => {
- repoAbortTransactionsOnNode(repo, node);
- });
- return affectedPath;
- }
-
- function repoAbortTransactionsOnNode(repo, node) {
- const queue = treeGetValue(node);
- if (queue) {
-
-
-
- const callbacks = [];
-
-
- let events = [];
- let lastSent = -1;
- for (let i = 0; i < queue.length; i++) {
- if (queue[i].status === 3 ) ;
- else if (queue[i].status === 1 ) {
- assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
- lastSent = i;
-
- queue[i].status = 3 ;
- queue[i].abortReason = 'set';
- }
- else {
- assert(queue[i].status === 0 , 'Unexpected transaction status in abort');
-
- queue[i].unwatcher();
- events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
- if (queue[i].onComplete) {
- callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
- }
- }
- }
- if (lastSent === -1) {
-
- treeSetValue(node, undefined);
- }
- else {
-
- queue.length = lastSent + 1;
- }
-
- eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
- for (let i = 0; i < callbacks.length; i++) {
- exceptionGuard(callbacks[i]);
- }
- }
- }
-
-
- function decodePath(pathString) {
- let pathStringDecoded = '';
- const pieces = pathString.split('/');
- for (let i = 0; i < pieces.length; i++) {
- if (pieces[i].length > 0) {
- let piece = pieces[i];
- try {
- piece = decodeURIComponent(piece.replace(/\+/g, ' '));
- }
- catch (e) { }
- pathStringDecoded += '/' + piece;
- }
- }
- return pathStringDecoded;
- }
-
- function decodeQuery(queryString) {
- const results = {};
- if (queryString.charAt(0) === '?') {
- queryString = queryString.substring(1);
- }
- for (const segment of queryString.split('&')) {
- if (segment.length === 0) {
- continue;
- }
- const kv = segment.split('=');
- if (kv.length === 2) {
- results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
- }
- else {
- warn(`Invalid query segment '${segment}' in query '${queryString}'`);
- }
- }
- return results;
- }
- const parseRepoInfo = function (dataURL, nodeAdmin) {
- const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
- if (parsedUrl.domain === 'firebase.com') {
- fatal(parsedUrl.host +
- ' is no longer supported. ' +
- 'Please use <YOUR FIREBASE>.firebaseio.com instead');
- }
-
- if ((!namespace || namespace === 'undefined') &&
- parsedUrl.domain !== 'localhost') {
- fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
- }
- if (!parsedUrl.secure) {
- warnIfPageIsSecure();
- }
- const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
- return {
- repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
- '',
- namespace !== parsedUrl.subdomain),
- path: new Path(parsedUrl.pathString)
- };
- };
- const parseDatabaseURL = function (dataURL) {
-
- let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
-
- let secure = true, scheme = 'https', port = 443;
-
- if (typeof dataURL === 'string') {
-
- let colonInd = dataURL.indexOf('//');
- if (colonInd >= 0) {
- scheme = dataURL.substring(0, colonInd - 1);
- dataURL = dataURL.substring(colonInd + 2);
- }
-
- let slashInd = dataURL.indexOf('/');
- if (slashInd === -1) {
- slashInd = dataURL.length;
- }
- let questionMarkInd = dataURL.indexOf('?');
- if (questionMarkInd === -1) {
- questionMarkInd = dataURL.length;
- }
- host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
- if (slashInd < questionMarkInd) {
-
- pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
- }
- const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
-
- colonInd = host.indexOf(':');
- if (colonInd >= 0) {
- secure = scheme === 'https' || scheme === 'wss';
- port = parseInt(host.substring(colonInd + 1), 10);
- }
- else {
- colonInd = host.length;
- }
- const hostWithoutPort = host.slice(0, colonInd);
- if (hostWithoutPort.toLowerCase() === 'localhost') {
- domain = 'localhost';
- }
- else if (hostWithoutPort.split('.').length <= 2) {
- domain = hostWithoutPort;
- }
- else {
-
- const dotInd = host.indexOf('.');
- subdomain = host.substring(0, dotInd).toLowerCase();
- domain = host.substring(dotInd + 1);
-
- namespace = subdomain;
- }
-
- if ('ns' in queryParams) {
- namespace = queryParams['ns'];
- }
- }
- return {
- host,
- port,
- domain,
- subdomain,
- secure,
- scheme,
- pathString,
- namespace
- };
- };
-
-
-
- const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
-
- const nextPushId = (function () {
-
-
- let lastPushTime = 0;
-
-
-
-
- const lastRandChars = [];
- return function (now) {
- const duplicateTime = now === lastPushTime;
- lastPushTime = now;
- let i;
- const timeStampChars = new Array(8);
- for (i = 7; i >= 0; i--) {
- timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
-
-
- now = Math.floor(now / 64);
- }
- assert(now === 0, 'Cannot push at time == 0');
- let id = timeStampChars.join('');
- if (!duplicateTime) {
- for (i = 0; i < 12; i++) {
- lastRandChars[i] = Math.floor(Math.random() * 64);
- }
- }
- else {
-
-
- for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
- lastRandChars[i] = 0;
- }
- lastRandChars[i]++;
- }
- for (i = 0; i < 12; i++) {
- id += PUSH_CHARS.charAt(lastRandChars[i]);
- }
- assert(id.length === 20, 'nextPushId: Length should be 20.');
- return id;
- };
- })();
-
-
-
- class DataEvent {
-
-
- constructor(eventType, eventRegistration, snapshot, prevName) {
- this.eventType = eventType;
- this.eventRegistration = eventRegistration;
- this.snapshot = snapshot;
- this.prevName = prevName;
- }
- getPath() {
- const ref = this.snapshot.ref;
- if (this.eventType === 'value') {
- return ref._path;
- }
- else {
- return ref.parent._path;
- }
- }
- getEventType() {
- return this.eventType;
- }
- getEventRunner() {
- return this.eventRegistration.getEventRunner(this);
- }
- toString() {
- return (this.getPath().toString() +
- ':' +
- this.eventType +
- ':' +
- stringify(this.snapshot.exportVal()));
- }
- }
- class CancelEvent {
- constructor(eventRegistration, error, path) {
- this.eventRegistration = eventRegistration;
- this.error = error;
- this.path = path;
- }
- getPath() {
- return this.path;
- }
- getEventType() {
- return 'cancel';
- }
- getEventRunner() {
- return this.eventRegistration.getEventRunner(this);
- }
- toString() {
- return this.path.toString() + ':cancel';
- }
- }
-
-
-
- class CallbackContext {
- constructor(snapshotCallback, cancelCallback) {
- this.snapshotCallback = snapshotCallback;
- this.cancelCallback = cancelCallback;
- }
- onValue(expDataSnapshot, previousChildName) {
- this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
- }
- onCancel(error) {
- assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
- return this.cancelCallback.call(null, error);
- }
- get hasCancelCallback() {
- return !!this.cancelCallback;
- }
- matches(other) {
- return (this.snapshotCallback === other.snapshotCallback ||
- (this.snapshotCallback.userCallback !== undefined &&
- this.snapshotCallback.userCallback ===
- other.snapshotCallback.userCallback &&
- this.snapshotCallback.context === other.snapshotCallback.context));
- }
- }
-
-
-
- class OnDisconnect {
-
- constructor(_repo, _path) {
- this._repo = _repo;
- this._path = _path;
- }
-
-
- cancel() {
- const deferred = new Deferred();
- repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
-
- remove() {
- validateWritablePath('OnDisconnect.remove', this._path);
- const deferred = new Deferred();
- repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
-
- set(value) {
- validateWritablePath('OnDisconnect.set', this._path);
- validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
- const deferred = new Deferred();
- repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
-
- setWithPriority(value, priority) {
- validateWritablePath('OnDisconnect.setWithPriority', this._path);
- validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
- validatePriority('OnDisconnect.setWithPriority', priority, false);
- const deferred = new Deferred();
- repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
-
- update(values) {
- validateWritablePath('OnDisconnect.update', this._path);
- validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
- const deferred = new Deferred();
- repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
- }
-
-
-
- class QueryImpl {
-
-
- constructor(_repo, _path, _queryParams, _orderByCalled) {
- this._repo = _repo;
- this._path = _path;
- this._queryParams = _queryParams;
- this._orderByCalled = _orderByCalled;
- }
- get key() {
- if (pathIsEmpty(this._path)) {
- return null;
- }
- else {
- return pathGetBack(this._path);
- }
- }
- get ref() {
- return new ReferenceImpl(this._repo, this._path);
- }
- get _queryIdentifier() {
- const obj = queryParamsGetQueryObject(this._queryParams);
- const id = ObjectToUniqueKey(obj);
- return id === '{}' ? 'default' : id;
- }
-
-
- get _queryObject() {
- return queryParamsGetQueryObject(this._queryParams);
- }
- isEqual(other) {
- other = getModularInstance(other);
- if (!(other instanceof QueryImpl)) {
- return false;
- }
- const sameRepo = this._repo === other._repo;
- const samePath = pathEquals(this._path, other._path);
- const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
- return sameRepo && samePath && sameQueryIdentifier;
- }
- toJSON() {
- return this.toString();
- }
- toString() {
- return this._repo.toString() + pathToUrlEncodedString(this._path);
- }
- }
-
- function validateNoPreviousOrderByCall(query, fnName) {
- if (query._orderByCalled === true) {
- throw new Error(fnName + ": You can't combine multiple orderBy calls.");
- }
- }
-
- function validateQueryEndpoints(params) {
- let startNode = null;
- let endNode = null;
- if (params.hasStart()) {
- startNode = params.getIndexStartValue();
- }
- if (params.hasEnd()) {
- endNode = params.getIndexEndValue();
- }
- if (params.getIndex() === KEY_INDEX) {
- const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
- 'startAt(), endAt(), or equalTo().';
- const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
- 'endAt(), endBefore(), or equalTo() must be a string.';
- if (params.hasStart()) {
- const startName = params.getIndexStartName();
- if (startName !== MIN_NAME) {
- throw new Error(tooManyArgsError);
- }
- else if (typeof startNode !== 'string') {
- throw new Error(wrongArgTypeError);
- }
- }
- if (params.hasEnd()) {
- const endName = params.getIndexEndName();
- if (endName !== MAX_NAME) {
- throw new Error(tooManyArgsError);
- }
- else if (typeof endNode !== 'string') {
- throw new Error(wrongArgTypeError);
- }
- }
- }
- else if (params.getIndex() === PRIORITY_INDEX) {
- if ((startNode != null && !isValidPriority(startNode)) ||
- (endNode != null && !isValidPriority(endNode))) {
- throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
- 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
- '(null, a number, or a string).');
- }
- }
- else {
- assert(params.getIndex() instanceof PathIndex ||
- params.getIndex() === VALUE_INDEX, 'unknown index type.');
- if ((startNode != null && typeof startNode === 'object') ||
- (endNode != null && typeof endNode === 'object')) {
- throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
- 'equalTo() cannot be an object.');
- }
- }
- }
-
- function validateLimit(params) {
- if (params.hasStart() &&
- params.hasEnd() &&
- params.hasLimit() &&
- !params.hasAnchoredLimit()) {
- throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
- 'limitToFirst() or limitToLast() instead.');
- }
- }
-
- class ReferenceImpl extends QueryImpl {
-
- constructor(repo, path) {
- super(repo, path, new QueryParams(), false);
- }
- get parent() {
- const parentPath = pathParent(this._path);
- return parentPath === null
- ? null
- : new ReferenceImpl(this._repo, parentPath);
- }
- get root() {
- let ref = this;
- while (ref.parent !== null) {
- ref = ref.parent;
- }
- return ref;
- }
- }
-
- class DataSnapshot {
-
-
- constructor(_node,
- /**
- * The location of this DataSnapshot.
- */
- ref, _index) {
- this._node = _node;
- this.ref = ref;
- this._index = _index;
- }
-
-
- get priority() {
-
- return this._node.getPriority().val();
- }
-
-
- get key() {
- return this.ref.key;
- }
-
- get size() {
- return this._node.numChildren();
- }
-
-
- child(path) {
- const childPath = new Path(path);
- const childRef = child(this.ref, path);
- return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
- }
-
-
- exists() {
- return !this._node.isEmpty();
- }
-
-
-
- exportVal() {
- return this._node.val(true);
- }
-
-
- forEach(action) {
- if (this._node.isLeafNode()) {
- return false;
- }
- const childrenNode = this._node;
-
- return !!childrenNode.forEachChild(this._index, (key, node) => {
- return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
- });
- }
-
-
- hasChild(path) {
- const childPath = new Path(path);
- return !this._node.getChild(childPath).isEmpty();
- }
-
-
- hasChildren() {
- if (this._node.isLeafNode()) {
- return false;
- }
- else {
- return !this._node.isEmpty();
- }
- }
-
-
- toJSON() {
- return this.exportVal();
- }
-
-
-
- val() {
- return this._node.val();
- }
- }
-
- function ref(db, path) {
- db = getModularInstance(db);
- db._checkNotDeleted('ref');
- return path !== undefined ? child(db._root, path) : db._root;
- }
-
- function refFromURL(db, url) {
- db = getModularInstance(db);
- db._checkNotDeleted('refFromURL');
- const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
- validateUrl('refFromURL', parsedURL);
- const repoInfo = parsedURL.repoInfo;
- if (!db._repo.repoInfo_.isCustomHost() &&
- repoInfo.host !== db._repo.repoInfo_.host) {
- fatal('refFromURL' +
- ': Host name does not match the current database: ' +
- '(found ' +
- repoInfo.host +
- ' but expected ' +
- db._repo.repoInfo_.host +
- ')');
- }
- return ref(db, parsedURL.path.toString());
- }
-
- function child(parent, path) {
- parent = getModularInstance(parent);
- if (pathGetFront(parent._path) === null) {
- validateRootPathString('child', 'path', path, false);
- }
- else {
- validatePathString('child', 'path', path, false);
- }
- return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
- }
-
- function onDisconnect(ref) {
- ref = getModularInstance(ref);
- return new OnDisconnect(ref._repo, ref._path);
- }
-
- function push(parent, value) {
- parent = getModularInstance(parent);
- validateWritablePath('push', parent._path);
- validateFirebaseDataArg('push', value, parent._path, true);
- const now = repoServerTime(parent._repo);
- const name = nextPushId(now);
-
-
-
-
-
-
- const thennablePushRef = child(parent, name);
- const pushRef = child(parent, name);
- let promise;
- if (value != null) {
- promise = set(pushRef, value).then(() => pushRef);
- }
- else {
- promise = Promise.resolve(pushRef);
- }
- thennablePushRef.then = promise.then.bind(promise);
- thennablePushRef.catch = promise.then.bind(promise, undefined);
- return thennablePushRef;
- }
-
- function remove(ref) {
- validateWritablePath('remove', ref._path);
- return set(ref, null);
- }
-
- function set(ref, value) {
- ref = getModularInstance(ref);
- validateWritablePath('set', ref._path);
- validateFirebaseDataArg('set', value, ref._path, false);
- const deferred = new Deferred();
- repoSetWithPriority(ref._repo, ref._path, value,
- null, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
- function setPriority(ref, priority) {
- ref = getModularInstance(ref);
- validateWritablePath('setPriority', ref._path);
- validatePriority('setPriority', priority, false);
- const deferred = new Deferred();
- repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
- function setWithPriority(ref, value, priority) {
- validateWritablePath('setWithPriority', ref._path);
- validateFirebaseDataArg('setWithPriority', value, ref._path, false);
- validatePriority('setWithPriority', priority, false);
- if (ref.key === '.length' || ref.key === '.keys') {
- throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
- }
- const deferred = new Deferred();
- repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
- function update(ref, values) {
- validateFirebaseMergeDataArg('update', values, ref._path, false);
- const deferred = new Deferred();
- repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
- return deferred.promise;
- }
-
- function get(query) {
- query = getModularInstance(query);
- const callbackContext = new CallbackContext(() => { });
- const container = new ValueEventRegistration(callbackContext);
- return repoGetValue(query._repo, query, container).then(node => {
- return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
- });
- }
-
- class ValueEventRegistration {
- constructor(callbackContext) {
- this.callbackContext = callbackContext;
- }
- respondsTo(eventType) {
- return eventType === 'value';
- }
- createEvent(change, query) {
- const index = query._queryParams.getIndex();
- return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
- }
- getEventRunner(eventData) {
- if (eventData.getEventType() === 'cancel') {
- return () => this.callbackContext.onCancel(eventData.error);
- }
- else {
- return () => this.callbackContext.onValue(eventData.snapshot, null);
- }
- }
- createCancelEvent(error, path) {
- if (this.callbackContext.hasCancelCallback) {
- return new CancelEvent(this, error, path);
- }
- else {
- return null;
- }
- }
- matches(other) {
- if (!(other instanceof ValueEventRegistration)) {
- return false;
- }
- else if (!other.callbackContext || !this.callbackContext) {
-
- return true;
- }
- else {
- return other.callbackContext.matches(this.callbackContext);
- }
- }
- hasAnyCallback() {
- return this.callbackContext !== null;
- }
- }
-
- class ChildEventRegistration {
- constructor(eventType, callbackContext) {
- this.eventType = eventType;
- this.callbackContext = callbackContext;
- }
- respondsTo(eventType) {
- let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
- eventToCheck =
- eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
- return this.eventType === eventToCheck;
- }
- createCancelEvent(error, path) {
- if (this.callbackContext.hasCancelCallback) {
- return new CancelEvent(this, error, path);
- }
- else {
- return null;
- }
- }
- createEvent(change, query) {
- assert(change.childName != null, 'Child events should have a childName.');
- const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
- const index = query._queryParams.getIndex();
- return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
- }
- getEventRunner(eventData) {
- if (eventData.getEventType() === 'cancel') {
- return () => this.callbackContext.onCancel(eventData.error);
- }
- else {
- return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
- }
- }
- matches(other) {
- if (other instanceof ChildEventRegistration) {
- return (this.eventType === other.eventType &&
- (!this.callbackContext ||
- !other.callbackContext ||
- this.callbackContext.matches(other.callbackContext)));
- }
- return false;
- }
- hasAnyCallback() {
- return !!this.callbackContext;
- }
- }
- function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
- let cancelCallback;
- if (typeof cancelCallbackOrListenOptions === 'object') {
- cancelCallback = undefined;
- options = cancelCallbackOrListenOptions;
- }
- if (typeof cancelCallbackOrListenOptions === 'function') {
- cancelCallback = cancelCallbackOrListenOptions;
- }
- if (options && options.onlyOnce) {
- const userCallback = callback;
- const onceCallback = (dataSnapshot, previousChildName) => {
- repoRemoveEventCallbackForQuery(query._repo, query, container);
- userCallback(dataSnapshot, previousChildName);
- };
- onceCallback.userCallback = callback.userCallback;
- onceCallback.context = callback.context;
- callback = onceCallback;
- }
- const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
- const container = eventType === 'value'
- ? new ValueEventRegistration(callbackContext)
- : new ChildEventRegistration(eventType, callbackContext);
- repoAddEventCallbackForQuery(query._repo, query, container);
- return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
- }
- function onValue(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
- }
- function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
- return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
- }
-
- function off(query, eventType, callback) {
- let container = null;
- const expCallback = callback ? new CallbackContext(callback) : null;
- if (eventType === 'value') {
- container = new ValueEventRegistration(expCallback);
- }
- else if (eventType) {
- container = new ChildEventRegistration(eventType, expCallback);
- }
- repoRemoveEventCallbackForQuery(query._repo, query, container);
- }
-
- class QueryConstraint {
- }
- class QueryEndAtConstraint extends QueryConstraint {
- constructor(_value, _key) {
- super();
- this._value = _value;
- this._key = _key;
- }
- _apply(query) {
- validateFirebaseDataArg('endAt', this._value, query._path, true);
- const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasEnd()) {
- throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
- 'endBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- }
- }
-
- function endAt(value, key) {
- validateKey('endAt', 'key', key, true);
- return new QueryEndAtConstraint(value, key);
- }
- class QueryEndBeforeConstraint extends QueryConstraint {
- constructor(_value, _key) {
- super();
- this._value = _value;
- this._key = _key;
- }
- _apply(query) {
- validateFirebaseDataArg('endBefore', this._value, query._path, false);
- const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasEnd()) {
- throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
- 'endBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- }
- }
-
- function endBefore(value, key) {
- validateKey('endBefore', 'key', key, true);
- return new QueryEndBeforeConstraint(value, key);
- }
- class QueryStartAtConstraint extends QueryConstraint {
- constructor(_value, _key) {
- super();
- this._value = _value;
- this._key = _key;
- }
- _apply(query) {
- validateFirebaseDataArg('startAt', this._value, query._path, true);
- const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasStart()) {
- throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
- 'startBefore or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- }
- }
-
- function startAt(value = null, key) {
- validateKey('startAt', 'key', key, true);
- return new QueryStartAtConstraint(value, key);
- }
- class QueryStartAfterConstraint extends QueryConstraint {
- constructor(_value, _key) {
- super();
- this._value = _value;
- this._key = _key;
- }
- _apply(query) {
- validateFirebaseDataArg('startAfter', this._value, query._path, false);
- const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
- validateLimit(newParams);
- validateQueryEndpoints(newParams);
- if (query._queryParams.hasStart()) {
- throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
- 'startAfter, or equalTo).');
- }
- return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
- }
- }
-
- function startAfter(value, key) {
- validateKey('startAfter', 'key', key, true);
- return new QueryStartAfterConstraint(value, key);
- }
- class QueryLimitToFirstConstraint extends QueryConstraint {
- constructor(_limit) {
- super();
- this._limit = _limit;
- }
- _apply(query) {
- if (query._queryParams.hasLimit()) {
- throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
- 'or limitToLast).');
- }
- return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
- }
- }
-
- function limitToFirst(limit) {
- if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
- throw new Error('limitToFirst: First argument must be a positive integer.');
- }
- return new QueryLimitToFirstConstraint(limit);
- }
- class QueryLimitToLastConstraint extends QueryConstraint {
- constructor(_limit) {
- super();
- this._limit = _limit;
- }
- _apply(query) {
- if (query._queryParams.hasLimit()) {
- throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
- 'or limitToLast).');
- }
- return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
- }
- }
-
- function limitToLast(limit) {
- if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
- throw new Error('limitToLast: First argument must be a positive integer.');
- }
- return new QueryLimitToLastConstraint(limit);
- }
- class QueryOrderByChildConstraint extends QueryConstraint {
- constructor(_path) {
- super();
- this._path = _path;
- }
- _apply(query) {
- validateNoPreviousOrderByCall(query, 'orderByChild');
- const parsedPath = new Path(this._path);
- if (pathIsEmpty(parsedPath)) {
- throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
- }
- const index = new PathIndex(parsedPath);
- const newParams = queryParamsOrderBy(query._queryParams, index);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- }
- }
-
- function orderByChild(path) {
- if (path === '$key') {
- throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
- }
- else if (path === '$priority') {
- throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
- }
- else if (path === '$value') {
- throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
- }
- validatePathString('orderByChild', 'path', path, false);
- return new QueryOrderByChildConstraint(path);
- }
- class QueryOrderByKeyConstraint extends QueryConstraint {
- _apply(query) {
- validateNoPreviousOrderByCall(query, 'orderByKey');
- const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- }
- }
-
- function orderByKey() {
- return new QueryOrderByKeyConstraint();
- }
- class QueryOrderByPriorityConstraint extends QueryConstraint {
- _apply(query) {
- validateNoPreviousOrderByCall(query, 'orderByPriority');
- const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- }
- }
-
- function orderByPriority() {
- return new QueryOrderByPriorityConstraint();
- }
- class QueryOrderByValueConstraint extends QueryConstraint {
- _apply(query) {
- validateNoPreviousOrderByCall(query, 'orderByValue');
- const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
- validateQueryEndpoints(newParams);
- return new QueryImpl(query._repo, query._path, newParams,
- true);
- }
- }
-
- function orderByValue() {
- return new QueryOrderByValueConstraint();
- }
- class QueryEqualToValueConstraint extends QueryConstraint {
- constructor(_value, _key) {
- super();
- this._value = _value;
- this._key = _key;
- }
- _apply(query) {
- validateFirebaseDataArg('equalTo', this._value, query._path, false);
- if (query._queryParams.hasStart()) {
- throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
- 'equalTo).');
- }
- if (query._queryParams.hasEnd()) {
- throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
- 'equalTo).');
- }
- return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
- }
- }
-
- function equalTo(value, key) {
- validateKey('equalTo', 'key', key, true);
- return new QueryEqualToValueConstraint(value, key);
- }
-
- function query(query, ...queryConstraints) {
- let queryImpl = getModularInstance(query);
- for (const constraint of queryConstraints) {
- queryImpl = constraint._apply(queryImpl);
- }
- return queryImpl;
- }
-
- syncPointSetReferenceConstructor(ReferenceImpl);
- syncTreeSetReferenceConstructor(ReferenceImpl);
-
-
-
- const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
-
- const repos = {};
-
- let useRestClient = false;
-
- function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
- repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
- false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
- if (tokenProvider) {
- repo.authTokenProvider_ = tokenProvider;
- }
- }
-
- function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
- let dbUrl = url || app.options.databaseURL;
- if (dbUrl === undefined) {
- if (!app.options.projectId) {
- fatal("Can't determine Firebase Database URL. Be sure to include " +
- ' a Project ID when calling firebase.initializeApp().');
- }
- log('Using default host for project ', app.options.projectId);
- dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
- }
- let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
- let repoInfo = parsedUrl.repoInfo;
- let isEmulator;
- let dbEmulatorHost = undefined;
- if (typeof process !== 'undefined' && process.env) {
- dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
- }
- if (dbEmulatorHost) {
- isEmulator = true;
- dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
- parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
- repoInfo = parsedUrl.repoInfo;
- }
- else {
- isEmulator = !parsedUrl.repoInfo.secure;
- }
- const authTokenProvider = nodeAdmin && isEmulator
- ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
- : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
- validateUrl('Invalid Firebase Database URL', parsedUrl);
- if (!pathIsEmpty(parsedUrl.path)) {
- fatal('Database URL must point to the root of a Firebase Database ' +
- '(not including a child path).');
- }
- const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
- return new Database(repo, app);
- }
-
- function repoManagerDeleteRepo(repo, appName) {
- const appRepos = repos[appName];
-
- if (!appRepos || appRepos[repo.key] !== repo) {
- fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
- }
- repoInterrupt(repo);
- delete appRepos[repo.key];
- }
-
- function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
- let appRepos = repos[app.name];
- if (!appRepos) {
- appRepos = {};
- repos[app.name] = appRepos;
- }
- let repo = appRepos[repoInfo.toURLString()];
- if (repo) {
- fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
- }
- repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
- appRepos[repoInfo.toURLString()] = repo;
- return repo;
- }
-
- function repoManagerForceRestClient(forceRestClient) {
- useRestClient = forceRestClient;
- }
-
- class Database {
-
- constructor(_repoInternal,
- /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
- app) {
- this._repoInternal = _repoInternal;
- this.app = app;
- /** Represents a `Database` instance. */
- this['type'] = 'database';
- /** Track if the instance has been used (root or repo accessed) */
- this._instanceStarted = false;
- }
- get _repo() {
- if (!this._instanceStarted) {
- repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
- this._instanceStarted = true;
- }
- return this._repoInternal;
- }
- get _root() {
- if (!this._rootInternal) {
- this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
- }
- return this._rootInternal;
- }
- _delete() {
- if (this._rootInternal !== null) {
- repoManagerDeleteRepo(this._repo, this.app.name);
- this._repoInternal = null;
- this._rootInternal = null;
- }
- return Promise.resolve();
- }
- _checkNotDeleted(apiName) {
- if (this._rootInternal === null) {
- fatal('Cannot call ' + apiName + ' on a deleted database.');
- }
- }
- }
- function checkTransportInit() {
- if (TransportManager.IS_TRANSPORT_INITIALIZED) {
- warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
- }
- }
- /**
- * Force the use of websockets instead of longPolling.
- */
- function forceWebSockets() {
- checkTransportInit();
- BrowserPollConnection.forceDisallow();
- }
- /**
- * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
- */
- function forceLongPolling() {
- checkTransportInit();
- WebSocketConnection.forceDisallow();
- BrowserPollConnection.forceAllow();
- }
- /**
- * Returns the instance of the Realtime Database SDK that is associated
- * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
- * with default settings if no instance exists or if the existing instance uses
- * a custom database URL.
- *
- * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
- * Database instance is associated with.
- * @param url - The URL of the Realtime Database instance to connect to. If not
- * provided, the SDK connects to the default instance of the Firebase App.
- * @returns The `Database` instance of the provided app.
- */
- function getDatabase(app = getApp(), url) {
- const db = _getProvider(app, 'database').getImmediate({
- identifier: url
- });
- if (!db._instanceStarted) {
- const emulator = getDefaultEmulatorHostnameAndPort('database');
- if (emulator) {
- connectDatabaseEmulator(db, ...emulator);
- }
- }
- return db;
- }
- /**
- * Modify the provided instance to communicate with the Realtime Database
- * emulator.
- *
- * <p>Note: This method must be called before performing any other operation.
- *
- * @param db - The instance to modify.
- * @param host - The emulator host (ex: localhost)
- * @param port - The emulator port (ex: 8080)
- * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
- */
- function connectDatabaseEmulator(db, host, port, options = {}) {
- db = getModularInstance(db);
- db._checkNotDeleted('useEmulator');
- if (db._instanceStarted) {
- fatal('Cannot call useEmulator() after instance has already been initialized.');
- }
- const repo = db._repoInternal;
- let tokenProvider = undefined;
- if (repo.repoInfo_.nodeAdmin) {
- if (options.mockUserToken) {
- fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
- }
- tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
- }
- else if (options.mockUserToken) {
- const token = typeof options.mockUserToken === 'string'
- ? options.mockUserToken
- : createMockUserToken(options.mockUserToken, db.app.options.projectId);
- tokenProvider = new EmulatorTokenProvider(token);
- }
- // Modify the repo to apply emulator settings
- repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
- }
- /**
- * Disconnects from the server (all Database operations will be completed
- * offline).
- *
- * The client automatically maintains a persistent connection to the Database
- * server, which will remain active indefinitely and reconnect when
- * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
- * to control the client connection in cases where a persistent connection is
- * undesirable.
- *
- * While offline, the client will no longer receive data updates from the
- * Database. However, all Database operations performed locally will continue to
- * immediately fire events, allowing your application to continue behaving
- * normally. Additionally, each operation performed locally will automatically
- * be queued and retried upon reconnection to the Database server.
- *
- * To reconnect to the Database and begin receiving remote events, see
- * `goOnline()`.
- *
- * @param db - The instance to disconnect.
- */
- function goOffline(db) {
- db = getModularInstance(db);
- db._checkNotDeleted('goOffline');
- repoInterrupt(db._repo);
- }
- /**
- * Reconnects to the server and synchronizes the offline Database state
- * with the server state.
- *
- * This method should be used after disabling the active connection with
- * `goOffline()`. Once reconnected, the client will transmit the proper data
- * and fire the appropriate events so that your client "catches up"
- * automatically.
- *
- * @param db - The instance to reconnect.
- */
- function goOnline(db) {
- db = getModularInstance(db);
- db._checkNotDeleted('goOnline');
- repoResume(db._repo);
- }
- function enableLogging(logger, persistent) {
- enableLogging$1(logger, persistent);
- }
-
- /**
- * @license
- * Copyright 2021 Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- function registerDatabase(variant) {
- setSDKVersion(SDK_VERSION$1);
- _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
- const app = container.getProvider('app').getImmediate();
- const authProvider = container.getProvider('auth-internal');
- const appCheckProvider = container.getProvider('app-check-internal');
- return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
- }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
- registerVersion(name, version, variant);
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
- registerVersion(name, version, 'esm2017');
- }
-
- /**
- * @license
- * Copyright 2020 Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- const SERVER_TIMESTAMP = {
- '.sv': 'timestamp'
- };
- /**
- * Returns a placeholder value for auto-populating the current timestamp (time
- * since the Unix epoch, in milliseconds) as determined by the Firebase
- * servers.
- */
- function serverTimestamp() {
- return SERVER_TIMESTAMP;
- }
- /**
- * Returns a placeholder value that can be used to atomically increment the
- * current database value by the provided delta.
- *
- * @param delta - the amount to modify the current value atomically.
- * @returns A placeholder value for modifying data atomically server-side.
- */
- function increment(delta) {
- return {
- '.sv': {
- 'increment': delta
- }
- };
- }
-
- /**
- * @license
- * Copyright 2020 Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- /**
- * A type for the resolve value of {@link runTransaction}.
- */
- class TransactionResult {
- /** @hideconstructor */
- constructor(
- /** Whether the transaction was successfully committed. */
- committed,
- /** The resulting data snapshot. */
- snapshot) {
- this.committed = committed;
- this.snapshot = snapshot;
- }
- /** Returns a JSON-serializable representation of this object. */
- toJSON() {
- return { committed: this.committed, snapshot: this.snapshot.toJSON() };
- }
- }
- /**
- * Atomically modifies the data at this location.
- *
- * Atomically modify the data at this location. Unlike a normal `set()`, which
- * just overwrites the data regardless of its previous value, `runTransaction()` is
- * used to modify the existing value to a new value, ensuring there are no
- * conflicts with other clients writing to the same location at the same time.
- *
- * To accomplish this, you pass `runTransaction()` an update function which is
- * used to transform the current value into a new value. If another client
- * writes to the location before your new value is successfully written, your
- * update function will be called again with the new current value, and the
- * write will be retried. This will happen repeatedly until your write succeeds
- * without conflict or you abort the transaction by not returning a value from
- * your update function.
- *
- * Note: Modifying data with `set()` will cancel any pending transactions at
- * that location, so extreme care should be taken if mixing `set()` and
- * `runTransaction()` to update the same data.
- *
- * Note: When using transactions with Security and Firebase Rules in place, be
- * aware that a client needs `.read` access in addition to `.write` access in
- * order to perform a transaction. This is because the client-side nature of
- * transactions requires the client to read the data in order to transactionally
- * update it.
- *
- * @param ref - The location to atomically modify.
- * @param transactionUpdate - A developer-supplied function which will be passed
- * the current data stored at this location (as a JavaScript object). The
- * function should return the new value it would like written (as a JavaScript
- * object). If `undefined` is returned (i.e. you return with no arguments) the
- * transaction will be aborted and the data at this location will not be
- * modified.
- * @param options - An options object to configure transactions.
- * @returns A `Promise` that can optionally be used instead of the `onComplete`
- * callback to handle success and failure.
- */
- function runTransaction(ref,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- transactionUpdate, options) {
- var _a;
- ref = getModularInstance(ref);
- validateWritablePath('Reference.transaction', ref._path);
- if (ref.key === '.length' || ref.key === '.keys') {
- throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
- }
- const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
- const deferred = new Deferred();
- const promiseComplete = (error, committed, node) => {
- let dataSnapshot = null;
- if (error) {
- deferred.reject(error);
- }
- else {
- dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
- deferred.resolve(new TransactionResult(committed, dataSnapshot));
- }
- };
- // Add a watch to make sure we get server updates.
- const unwatcher = onValue(ref, () => { });
- repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
- return deferred.promise;
- }
-
- /**
- * @license
- * Copyright 2017 Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- PersistentConnection;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
- this.sendRequest('q', { p: pathString }, onComplete);
- };
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- PersistentConnection.prototype.echo = function (data, onEcho) {
- this.sendRequest('echo', { d: data }, onEcho);
- };
- // RealTimeConnection properties that we use in tests.
- Connection;
- /**
- * @internal
- */
- const hijackHash = function (newHash) {
- const oldPut = PersistentConnection.prototype.put;
- PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
- if (hash !== undefined) {
- hash = newHash();
- }
- oldPut.call(this, pathString, data, onComplete, hash);
- };
- return function () {
- PersistentConnection.prototype.put = oldPut;
- };
- };
- RepoInfo;
- /**
- * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
- * @internal
- */
- const forceRestClient = function (forceRestClient) {
- repoManagerForceRestClient(forceRestClient);
- };
-
- /**
- * Firebase Realtime Database
- *
- * @packageDocumentation
- */
- registerDatabase();
-
- export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
- //# sourceMappingURL=index.esm2017.js.map
|