index.node.esm.js 538 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021
  1. import Websocket from 'faye-websocket';
  2. 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';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
  5. import { Component, ComponentContainer, Provider } from '@firebase/component';
  6. /**
  7. * @license
  8. * Copyright 2017 Google LLC
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. const PROTOCOL_VERSION = '5';
  23. const VERSION_PARAM = 'v';
  24. const TRANSPORT_SESSION_PARAM = 's';
  25. const REFERER_PARAM = 'r';
  26. const FORGE_REF = 'f';
  27. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  28. // firebase.corp.google.com
  29. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  30. const LAST_SESSION_PARAM = 'ls';
  31. const APPLICATION_ID_PARAM = 'p';
  32. const APP_CHECK_TOKEN_PARAM = 'ac';
  33. const WEBSOCKET = 'websocket';
  34. const LONG_POLLING = 'long_polling';
  35. /**
  36. * @license
  37. * Copyright 2017 Google LLC
  38. *
  39. * Licensed under the Apache License, Version 2.0 (the "License");
  40. * you may not use this file except in compliance with the License.
  41. * You may obtain a copy of the License at
  42. *
  43. * http://www.apache.org/licenses/LICENSE-2.0
  44. *
  45. * Unless required by applicable law or agreed to in writing, software
  46. * distributed under the License is distributed on an "AS IS" BASIS,
  47. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  48. * See the License for the specific language governing permissions and
  49. * limitations under the License.
  50. */
  51. /**
  52. * Wraps a DOM Storage object and:
  53. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  54. * - prefixes names with "firebase:" to avoid collisions with app data.
  55. *
  56. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  57. * and one for localStorage.
  58. *
  59. */
  60. class DOMStorageWrapper {
  61. /**
  62. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  63. */
  64. constructor(domStorage_) {
  65. this.domStorage_ = domStorage_;
  66. // Use a prefix to avoid collisions with other stuff saved by the app.
  67. this.prefix_ = 'firebase:';
  68. }
  69. /**
  70. * @param key - The key to save the value under
  71. * @param value - The value being stored, or null to remove the key.
  72. */
  73. set(key, value) {
  74. if (value == null) {
  75. this.domStorage_.removeItem(this.prefixedName_(key));
  76. }
  77. else {
  78. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  79. }
  80. }
  81. /**
  82. * @returns The value that was stored under this key, or null
  83. */
  84. get(key) {
  85. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  86. if (storedVal == null) {
  87. return null;
  88. }
  89. else {
  90. return jsonEval(storedVal);
  91. }
  92. }
  93. remove(key) {
  94. this.domStorage_.removeItem(this.prefixedName_(key));
  95. }
  96. prefixedName_(name) {
  97. return this.prefix_ + name;
  98. }
  99. toString() {
  100. return this.domStorage_.toString();
  101. }
  102. }
  103. /**
  104. * @license
  105. * Copyright 2017 Google LLC
  106. *
  107. * Licensed under the Apache License, Version 2.0 (the "License");
  108. * you may not use this file except in compliance with the License.
  109. * You may obtain a copy of the License at
  110. *
  111. * http://www.apache.org/licenses/LICENSE-2.0
  112. *
  113. * Unless required by applicable law or agreed to in writing, software
  114. * distributed under the License is distributed on an "AS IS" BASIS,
  115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  116. * See the License for the specific language governing permissions and
  117. * limitations under the License.
  118. */
  119. /**
  120. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  121. * (TODO: create interface for both to implement).
  122. */
  123. class MemoryStorage {
  124. constructor() {
  125. this.cache_ = {};
  126. this.isInMemoryStorage = true;
  127. }
  128. set(key, value) {
  129. if (value == null) {
  130. delete this.cache_[key];
  131. }
  132. else {
  133. this.cache_[key] = value;
  134. }
  135. }
  136. get(key) {
  137. if (contains(this.cache_, key)) {
  138. return this.cache_[key];
  139. }
  140. return null;
  141. }
  142. remove(key) {
  143. delete this.cache_[key];
  144. }
  145. }
  146. /**
  147. * @license
  148. * Copyright 2017 Google LLC
  149. *
  150. * Licensed under the Apache License, Version 2.0 (the "License");
  151. * you may not use this file except in compliance with the License.
  152. * You may obtain a copy of the License at
  153. *
  154. * http://www.apache.org/licenses/LICENSE-2.0
  155. *
  156. * Unless required by applicable law or agreed to in writing, software
  157. * distributed under the License is distributed on an "AS IS" BASIS,
  158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  159. * See the License for the specific language governing permissions and
  160. * limitations under the License.
  161. */
  162. /**
  163. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  164. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  165. * to reflect this type
  166. *
  167. * @param domStorageName - Name of the underlying storage object
  168. * (e.g. 'localStorage' or 'sessionStorage').
  169. * @returns Turning off type information until a common interface is defined.
  170. */
  171. const createStoragefor = function (domStorageName) {
  172. try {
  173. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  174. // so it must be inside the try/catch.
  175. if (typeof window !== 'undefined' &&
  176. typeof window[domStorageName] !== 'undefined') {
  177. // Need to test cache. Just because it's here doesn't mean it works
  178. const domStorage = window[domStorageName];
  179. domStorage.setItem('firebase:sentinel', 'cache');
  180. domStorage.removeItem('firebase:sentinel');
  181. return new DOMStorageWrapper(domStorage);
  182. }
  183. }
  184. catch (e) { }
  185. // Failed to create wrapper. Just return in-memory storage.
  186. // TODO: log?
  187. return new MemoryStorage();
  188. };
  189. /** A storage object that lasts across sessions */
  190. const PersistentStorage = createStoragefor('localStorage');
  191. /** A storage object that only lasts one session */
  192. const SessionStorage = createStoragefor('sessionStorage');
  193. /**
  194. * @license
  195. * Copyright 2017 Google LLC
  196. *
  197. * Licensed under the Apache License, Version 2.0 (the "License");
  198. * you may not use this file except in compliance with the License.
  199. * You may obtain a copy of the License at
  200. *
  201. * http://www.apache.org/licenses/LICENSE-2.0
  202. *
  203. * Unless required by applicable law or agreed to in writing, software
  204. * distributed under the License is distributed on an "AS IS" BASIS,
  205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. * See the License for the specific language governing permissions and
  207. * limitations under the License.
  208. */
  209. const logClient = new Logger('@firebase/database');
  210. /**
  211. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  212. */
  213. const LUIDGenerator = (function () {
  214. let id = 1;
  215. return function () {
  216. return id++;
  217. };
  218. })();
  219. /**
  220. * Sha1 hash of the input string
  221. * @param str - The string to hash
  222. * @returns {!string} The resulting hash
  223. */
  224. const sha1 = function (str) {
  225. const utf8Bytes = stringToByteArray(str);
  226. const sha1 = new Sha1();
  227. sha1.update(utf8Bytes);
  228. const sha1Bytes = sha1.digest();
  229. return base64.encodeByteArray(sha1Bytes);
  230. };
  231. const buildLogMessage_ = function (...varArgs) {
  232. let message = '';
  233. for (let i = 0; i < varArgs.length; i++) {
  234. const arg = varArgs[i];
  235. if (Array.isArray(arg) ||
  236. (arg &&
  237. typeof arg === 'object' &&
  238. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  239. typeof arg.length === 'number')) {
  240. message += buildLogMessage_.apply(null, arg);
  241. }
  242. else if (typeof arg === 'object') {
  243. message += stringify(arg);
  244. }
  245. else {
  246. message += arg;
  247. }
  248. message += ' ';
  249. }
  250. return message;
  251. };
  252. /**
  253. * Use this for all debug messages in Firebase.
  254. */
  255. let logger = null;
  256. /**
  257. * Flag to check for log availability on first log message
  258. */
  259. let firstLog_ = true;
  260. /**
  261. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  262. * @param logger_ - A flag to turn on logging, or a custom logger
  263. * @param persistent - Whether or not to persist logging settings across refreshes
  264. */
  265. const enableLogging$1 = function (logger_, persistent) {
  266. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  267. if (logger_ === true) {
  268. logClient.logLevel = LogLevel.VERBOSE;
  269. logger = logClient.log.bind(logClient);
  270. if (persistent) {
  271. SessionStorage.set('logging_enabled', true);
  272. }
  273. }
  274. else if (typeof logger_ === 'function') {
  275. logger = logger_;
  276. }
  277. else {
  278. logger = null;
  279. SessionStorage.remove('logging_enabled');
  280. }
  281. };
  282. const log = function (...varArgs) {
  283. if (firstLog_ === true) {
  284. firstLog_ = false;
  285. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  286. enableLogging$1(true);
  287. }
  288. }
  289. if (logger) {
  290. const message = buildLogMessage_.apply(null, varArgs);
  291. logger(message);
  292. }
  293. };
  294. const logWrapper = function (prefix) {
  295. return function (...varArgs) {
  296. log(prefix, ...varArgs);
  297. };
  298. };
  299. const error = function (...varArgs) {
  300. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  301. logClient.error(message);
  302. };
  303. const fatal = function (...varArgs) {
  304. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  305. logClient.error(message);
  306. throw new Error(message);
  307. };
  308. const warn = function (...varArgs) {
  309. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  310. logClient.warn(message);
  311. };
  312. /**
  313. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  314. * does not use https.
  315. */
  316. const warnIfPageIsSecure = function () {
  317. // Be very careful accessing browser globals. Who knows what may or may not exist.
  318. if (typeof window !== 'undefined' &&
  319. window.location &&
  320. window.location.protocol &&
  321. window.location.protocol.indexOf('https:') !== -1) {
  322. warn('Insecure Firebase access from a secure page. ' +
  323. 'Please use https in calls to new Firebase().');
  324. }
  325. };
  326. /**
  327. * Returns true if data is NaN, or +/- Infinity.
  328. */
  329. const isInvalidJSONNumber = function (data) {
  330. return (typeof data === 'number' &&
  331. (data !== data || // NaN
  332. data === Number.POSITIVE_INFINITY ||
  333. data === Number.NEGATIVE_INFINITY));
  334. };
  335. const executeWhenDOMReady = function (fn) {
  336. if (isNodeSdk() || document.readyState === 'complete') {
  337. fn();
  338. }
  339. else {
  340. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  341. // fire before onload), but fall back to onload.
  342. let called = false;
  343. const wrappedFn = function () {
  344. if (!document.body) {
  345. setTimeout(wrappedFn, Math.floor(10));
  346. return;
  347. }
  348. if (!called) {
  349. called = true;
  350. fn();
  351. }
  352. };
  353. if (document.addEventListener) {
  354. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  355. // fallback to onload.
  356. window.addEventListener('load', wrappedFn, false);
  357. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  358. }
  359. else if (document.attachEvent) {
  360. // IE.
  361. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  362. document.attachEvent('onreadystatechange', () => {
  363. if (document.readyState === 'complete') {
  364. wrappedFn();
  365. }
  366. });
  367. // fallback to onload.
  368. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  369. window.attachEvent('onload', wrappedFn);
  370. // jQuery has an extra hack for IE that we could employ (based on
  371. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  372. // I'm hoping we don't need it.
  373. }
  374. }
  375. };
  376. /**
  377. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  378. */
  379. const MIN_NAME = '[MIN_NAME]';
  380. /**
  381. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  382. */
  383. const MAX_NAME = '[MAX_NAME]';
  384. /**
  385. * Compares valid Firebase key names, plus min and max name
  386. */
  387. const nameCompare = function (a, b) {
  388. if (a === b) {
  389. return 0;
  390. }
  391. else if (a === MIN_NAME || b === MAX_NAME) {
  392. return -1;
  393. }
  394. else if (b === MIN_NAME || a === MAX_NAME) {
  395. return 1;
  396. }
  397. else {
  398. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  399. if (aAsInt !== null) {
  400. if (bAsInt !== null) {
  401. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  402. }
  403. else {
  404. return -1;
  405. }
  406. }
  407. else if (bAsInt !== null) {
  408. return 1;
  409. }
  410. else {
  411. return a < b ? -1 : 1;
  412. }
  413. }
  414. };
  415. /**
  416. * @returns {!number} comparison result.
  417. */
  418. const stringCompare = function (a, b) {
  419. if (a === b) {
  420. return 0;
  421. }
  422. else if (a < b) {
  423. return -1;
  424. }
  425. else {
  426. return 1;
  427. }
  428. };
  429. const requireKey = function (key, obj) {
  430. if (obj && key in obj) {
  431. return obj[key];
  432. }
  433. else {
  434. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  435. }
  436. };
  437. const ObjectToUniqueKey = function (obj) {
  438. if (typeof obj !== 'object' || obj === null) {
  439. return stringify(obj);
  440. }
  441. const keys = [];
  442. // eslint-disable-next-line guard-for-in
  443. for (const k in obj) {
  444. keys.push(k);
  445. }
  446. // Export as json, but with the keys sorted.
  447. keys.sort();
  448. let key = '{';
  449. for (let i = 0; i < keys.length; i++) {
  450. if (i !== 0) {
  451. key += ',';
  452. }
  453. key += stringify(keys[i]);
  454. key += ':';
  455. key += ObjectToUniqueKey(obj[keys[i]]);
  456. }
  457. key += '}';
  458. return key;
  459. };
  460. /**
  461. * Splits a string into a number of smaller segments of maximum size
  462. * @param str - The string
  463. * @param segsize - The maximum number of chars in the string.
  464. * @returns The string, split into appropriately-sized chunks
  465. */
  466. const splitStringBySize = function (str, segsize) {
  467. const len = str.length;
  468. if (len <= segsize) {
  469. return [str];
  470. }
  471. const dataSegs = [];
  472. for (let c = 0; c < len; c += segsize) {
  473. if (c + segsize > len) {
  474. dataSegs.push(str.substring(c, len));
  475. }
  476. else {
  477. dataSegs.push(str.substring(c, c + segsize));
  478. }
  479. }
  480. return dataSegs;
  481. };
  482. /**
  483. * Apply a function to each (key, value) pair in an object or
  484. * apply a function to each (index, value) pair in an array
  485. * @param obj - The object or array to iterate over
  486. * @param fn - The function to apply
  487. */
  488. function each(obj, fn) {
  489. for (const key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. fn(key, obj[key]);
  492. }
  493. }
  494. }
  495. /**
  496. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  497. * I made one modification at the end and removed the NaN / Infinity
  498. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  499. * @param v - A double
  500. *
  501. */
  502. const doubleToIEEE754String = function (v) {
  503. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  504. const ebits = 11, fbits = 52;
  505. const bias = (1 << (ebits - 1)) - 1;
  506. let s, e, f, ln, i;
  507. // Compute sign, exponent, fraction
  508. // Skip NaN / Infinity handling --MJL.
  509. if (v === 0) {
  510. e = 0;
  511. f = 0;
  512. s = 1 / v === -Infinity ? 1 : 0;
  513. }
  514. else {
  515. s = v < 0;
  516. v = Math.abs(v);
  517. if (v >= Math.pow(2, 1 - bias)) {
  518. // Normalized
  519. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  520. e = ln + bias;
  521. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  522. }
  523. else {
  524. // Denormalized
  525. e = 0;
  526. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  527. }
  528. }
  529. // Pack sign, exponent, fraction
  530. const bits = [];
  531. for (i = fbits; i; i -= 1) {
  532. bits.push(f % 2 ? 1 : 0);
  533. f = Math.floor(f / 2);
  534. }
  535. for (i = ebits; i; i -= 1) {
  536. bits.push(e % 2 ? 1 : 0);
  537. e = Math.floor(e / 2);
  538. }
  539. bits.push(s ? 1 : 0);
  540. bits.reverse();
  541. const str = bits.join('');
  542. // Return the data as a hex string. --MJL
  543. let hexByteString = '';
  544. for (i = 0; i < 64; i += 8) {
  545. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  546. if (hexByte.length === 1) {
  547. hexByte = '0' + hexByte;
  548. }
  549. hexByteString = hexByteString + hexByte;
  550. }
  551. return hexByteString.toLowerCase();
  552. };
  553. /**
  554. * Used to detect if we're in a Chrome content script (which executes in an
  555. * isolated environment where long-polling doesn't work).
  556. */
  557. const isChromeExtensionContentScript = function () {
  558. return !!(typeof window === 'object' &&
  559. window['chrome'] &&
  560. window['chrome']['extension'] &&
  561. !/^chrome/.test(window.location.href));
  562. };
  563. /**
  564. * Used to detect if we're in a Windows 8 Store app.
  565. */
  566. const isWindowsStoreApp = function () {
  567. // Check for the presence of a couple WinRT globals
  568. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  569. };
  570. /**
  571. * Converts a server error code to a JavaScript Error
  572. */
  573. function errorForServerCode(code, query) {
  574. let reason = 'Unknown Error';
  575. if (code === 'too_big') {
  576. reason =
  577. 'The data requested exceeds the maximum size ' +
  578. 'that can be accessed with a single request.';
  579. }
  580. else if (code === 'permission_denied') {
  581. reason = "Client doesn't have permission to access the desired data.";
  582. }
  583. else if (code === 'unavailable') {
  584. reason = 'The service is unavailable';
  585. }
  586. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  587. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  588. error.code = code.toUpperCase();
  589. return error;
  590. }
  591. /**
  592. * Used to test for integer-looking strings
  593. */
  594. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  595. /**
  596. * For use in keys, the minimum possible 32-bit integer.
  597. */
  598. const INTEGER_32_MIN = -2147483648;
  599. /**
  600. * For use in keys, the maximum possible 32-bit integer.
  601. */
  602. const INTEGER_32_MAX = 2147483647;
  603. /**
  604. * If the string contains a 32-bit integer, return it. Else return null.
  605. */
  606. const tryParseInt = function (str) {
  607. if (INTEGER_REGEXP_.test(str)) {
  608. const intVal = Number(str);
  609. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  610. return intVal;
  611. }
  612. }
  613. return null;
  614. };
  615. /**
  616. * Helper to run some code but catch any exceptions and re-throw them later.
  617. * Useful for preventing user callbacks from breaking internal code.
  618. *
  619. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  620. * convenient (we don't have to try to figure out when is a safe point to
  621. * re-throw it), and the behavior seems reasonable:
  622. *
  623. * * If you aren't pausing on exceptions, you get an error in the console with
  624. * the correct stack trace.
  625. * * If you're pausing on all exceptions, the debugger will pause on your
  626. * exception and then again when we rethrow it.
  627. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  628. * on us re-throwing it.
  629. *
  630. * @param fn - The code to guard.
  631. */
  632. const exceptionGuard = function (fn) {
  633. try {
  634. fn();
  635. }
  636. catch (e) {
  637. // Re-throw exception when it's safe.
  638. setTimeout(() => {
  639. // It used to be that "throw e" would result in a good console error with
  640. // relevant context, but as of Chrome 39, you just get the firebase.js
  641. // file/line number where we re-throw it, which is useless. So we log
  642. // e.stack explicitly.
  643. const stack = e.stack || '';
  644. warn('Exception was thrown by user callback.', stack);
  645. throw e;
  646. }, Math.floor(0));
  647. }
  648. };
  649. /**
  650. * @returns {boolean} true if we think we're currently being crawled.
  651. */
  652. const beingCrawled = function () {
  653. const userAgent = (typeof window === 'object' &&
  654. window['navigator'] &&
  655. window['navigator']['userAgent']) ||
  656. '';
  657. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  658. // believe to support JavaScript/AJAX rendering.
  659. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  660. // would have seen the page" is flaky if we don't treat it as a crawler.
  661. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  662. };
  663. /**
  664. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  665. *
  666. * It is removed with clearTimeout() as normal.
  667. *
  668. * @param fn - Function to run.
  669. * @param time - Milliseconds to wait before running.
  670. * @returns The setTimeout() return value.
  671. */
  672. const setTimeoutNonBlocking = function (fn, time) {
  673. const timeout = setTimeout(fn, time);
  674. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  675. if (typeof timeout === 'number' &&
  676. // @ts-ignore Is only defined in Deno environments.
  677. typeof Deno !== 'undefined' &&
  678. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  679. Deno['unrefTimer']) {
  680. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  681. Deno.unrefTimer(timeout);
  682. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  683. }
  684. else if (typeof timeout === 'object' && timeout['unref']) {
  685. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  686. timeout['unref']();
  687. }
  688. return timeout;
  689. };
  690. /**
  691. * @license
  692. * Copyright 2017 Google LLC
  693. *
  694. * Licensed under the Apache License, Version 2.0 (the "License");
  695. * you may not use this file except in compliance with the License.
  696. * You may obtain a copy of the License at
  697. *
  698. * http://www.apache.org/licenses/LICENSE-2.0
  699. *
  700. * Unless required by applicable law or agreed to in writing, software
  701. * distributed under the License is distributed on an "AS IS" BASIS,
  702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  703. * See the License for the specific language governing permissions and
  704. * limitations under the License.
  705. */
  706. /**
  707. * A class that holds metadata about a Repo object
  708. */
  709. class RepoInfo {
  710. /**
  711. * @param host - Hostname portion of the url for the repo
  712. * @param secure - Whether or not this repo is accessed over ssl
  713. * @param namespace - The namespace represented by the repo
  714. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  715. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  716. * @param persistenceKey - Override the default session persistence storage key
  717. */
  718. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {
  719. this.secure = secure;
  720. this.namespace = namespace;
  721. this.webSocketOnly = webSocketOnly;
  722. this.nodeAdmin = nodeAdmin;
  723. this.persistenceKey = persistenceKey;
  724. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  725. this.isUsingEmulator = isUsingEmulator;
  726. this._host = host.toLowerCase();
  727. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  728. this.internalHost =
  729. PersistentStorage.get('host:' + host) || this._host;
  730. }
  731. isCacheableHost() {
  732. return this.internalHost.substr(0, 2) === 's-';
  733. }
  734. isCustomHost() {
  735. return (this._domain !== 'firebaseio.com' &&
  736. this._domain !== 'firebaseio-demo.com');
  737. }
  738. get host() {
  739. return this._host;
  740. }
  741. set host(newHost) {
  742. if (newHost !== this.internalHost) {
  743. this.internalHost = newHost;
  744. if (this.isCacheableHost()) {
  745. PersistentStorage.set('host:' + this._host, this.internalHost);
  746. }
  747. }
  748. }
  749. toString() {
  750. let str = this.toURLString();
  751. if (this.persistenceKey) {
  752. str += '<' + this.persistenceKey + '>';
  753. }
  754. return str;
  755. }
  756. toURLString() {
  757. const protocol = this.secure ? 'https://' : 'http://';
  758. const query = this.includeNamespaceInQueryParams
  759. ? `?ns=${this.namespace}`
  760. : '';
  761. return `${protocol}${this.host}/${query}`;
  762. }
  763. }
  764. function repoInfoNeedsQueryParam(repoInfo) {
  765. return (repoInfo.host !== repoInfo.internalHost ||
  766. repoInfo.isCustomHost() ||
  767. repoInfo.includeNamespaceInQueryParams);
  768. }
  769. /**
  770. * Returns the websocket URL for this repo
  771. * @param repoInfo - RepoInfo object
  772. * @param type - of connection
  773. * @param params - list
  774. * @returns The URL for this repo
  775. */
  776. function repoInfoConnectionURL(repoInfo, type, params) {
  777. assert(typeof type === 'string', 'typeof type must == string');
  778. assert(typeof params === 'object', 'typeof params must == object');
  779. let connURL;
  780. if (type === WEBSOCKET) {
  781. connURL =
  782. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  783. }
  784. else if (type === LONG_POLLING) {
  785. connURL =
  786. (repoInfo.secure ? 'https://' : 'http://') +
  787. repoInfo.internalHost +
  788. '/.lp?';
  789. }
  790. else {
  791. throw new Error('Unknown connection type: ' + type);
  792. }
  793. if (repoInfoNeedsQueryParam(repoInfo)) {
  794. params['ns'] = repoInfo.namespace;
  795. }
  796. const pairs = [];
  797. each(params, (key, value) => {
  798. pairs.push(key + '=' + value);
  799. });
  800. return connURL + pairs.join('&');
  801. }
  802. /**
  803. * @license
  804. * Copyright 2017 Google LLC
  805. *
  806. * Licensed under the Apache License, Version 2.0 (the "License");
  807. * you may not use this file except in compliance with the License.
  808. * You may obtain a copy of the License at
  809. *
  810. * http://www.apache.org/licenses/LICENSE-2.0
  811. *
  812. * Unless required by applicable law or agreed to in writing, software
  813. * distributed under the License is distributed on an "AS IS" BASIS,
  814. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  815. * See the License for the specific language governing permissions and
  816. * limitations under the License.
  817. */
  818. /**
  819. * Tracks a collection of stats.
  820. */
  821. class StatsCollection {
  822. constructor() {
  823. this.counters_ = {};
  824. }
  825. incrementCounter(name, amount = 1) {
  826. if (!contains(this.counters_, name)) {
  827. this.counters_[name] = 0;
  828. }
  829. this.counters_[name] += amount;
  830. }
  831. get() {
  832. return deepCopy(this.counters_);
  833. }
  834. }
  835. /**
  836. * @license
  837. * Copyright 2017 Google LLC
  838. *
  839. * Licensed under the Apache License, Version 2.0 (the "License");
  840. * you may not use this file except in compliance with the License.
  841. * You may obtain a copy of the License at
  842. *
  843. * http://www.apache.org/licenses/LICENSE-2.0
  844. *
  845. * Unless required by applicable law or agreed to in writing, software
  846. * distributed under the License is distributed on an "AS IS" BASIS,
  847. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  848. * See the License for the specific language governing permissions and
  849. * limitations under the License.
  850. */
  851. const collections = {};
  852. const reporters = {};
  853. function statsManagerGetCollection(repoInfo) {
  854. const hashString = repoInfo.toString();
  855. if (!collections[hashString]) {
  856. collections[hashString] = new StatsCollection();
  857. }
  858. return collections[hashString];
  859. }
  860. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  861. const hashString = repoInfo.toString();
  862. if (!reporters[hashString]) {
  863. reporters[hashString] = creatorFunction();
  864. }
  865. return reporters[hashString];
  866. }
  867. /**
  868. * @license
  869. * Copyright 2019 Google LLC
  870. *
  871. * Licensed under the Apache License, Version 2.0 (the "License");
  872. * you may not use this file except in compliance with the License.
  873. * You may obtain a copy of the License at
  874. *
  875. * http://www.apache.org/licenses/LICENSE-2.0
  876. *
  877. * Unless required by applicable law or agreed to in writing, software
  878. * distributed under the License is distributed on an "AS IS" BASIS,
  879. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  880. * See the License for the specific language governing permissions and
  881. * limitations under the License.
  882. */
  883. /** The semver (www.semver.org) version of the SDK. */
  884. let SDK_VERSION = '';
  885. /**
  886. * SDK_VERSION should be set before any database instance is created
  887. * @internal
  888. */
  889. function setSDKVersion(version) {
  890. SDK_VERSION = version;
  891. }
  892. /**
  893. * @license
  894. * Copyright 2017 Google LLC
  895. *
  896. * Licensed under the Apache License, Version 2.0 (the "License");
  897. * you may not use this file except in compliance with the License.
  898. * You may obtain a copy of the License at
  899. *
  900. * http://www.apache.org/licenses/LICENSE-2.0
  901. *
  902. * Unless required by applicable law or agreed to in writing, software
  903. * distributed under the License is distributed on an "AS IS" BASIS,
  904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  905. * See the License for the specific language governing permissions and
  906. * limitations under the License.
  907. */
  908. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  909. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  910. let WebSocketImpl = null;
  911. if (typeof MozWebSocket !== 'undefined') {
  912. WebSocketImpl = MozWebSocket;
  913. }
  914. else if (typeof WebSocket !== 'undefined') {
  915. WebSocketImpl = WebSocket;
  916. }
  917. function setWebSocketImpl(impl) {
  918. WebSocketImpl = impl;
  919. }
  920. /**
  921. * Create a new websocket connection with the given callbacks.
  922. */
  923. class WebSocketConnection {
  924. /**
  925. * @param connId identifier for this transport
  926. * @param repoInfo The info for the websocket endpoint.
  927. * @param applicationId The Firebase App ID for this project.
  928. * @param appCheckToken The App Check Token for this client.
  929. * @param authToken The Auth Token for this client.
  930. * @param transportSessionId Optional transportSessionId if this is connecting
  931. * to an existing transport session
  932. * @param lastSessionId Optional lastSessionId if there was a previous
  933. * connection
  934. */
  935. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  936. this.connId = connId;
  937. this.applicationId = applicationId;
  938. this.appCheckToken = appCheckToken;
  939. this.authToken = authToken;
  940. this.keepaliveTimer = null;
  941. this.frames = null;
  942. this.totalFrames = 0;
  943. this.bytesSent = 0;
  944. this.bytesReceived = 0;
  945. this.log_ = logWrapper(this.connId);
  946. this.stats_ = statsManagerGetCollection(repoInfo);
  947. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  948. this.nodeAdmin = repoInfo.nodeAdmin;
  949. }
  950. /**
  951. * @param repoInfo - The info for the websocket endpoint.
  952. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  953. * session
  954. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  955. * @returns connection url
  956. */
  957. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  958. const urlParams = {};
  959. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  960. if (!isNodeSdk() &&
  961. typeof location !== 'undefined' &&
  962. location.hostname &&
  963. FORGE_DOMAIN_RE.test(location.hostname)) {
  964. urlParams[REFERER_PARAM] = FORGE_REF;
  965. }
  966. if (transportSessionId) {
  967. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  968. }
  969. if (lastSessionId) {
  970. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  971. }
  972. if (appCheckToken) {
  973. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  974. }
  975. if (applicationId) {
  976. urlParams[APPLICATION_ID_PARAM] = applicationId;
  977. }
  978. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  979. }
  980. /**
  981. * @param onMessage - Callback when messages arrive
  982. * @param onDisconnect - Callback with connection lost.
  983. */
  984. open(onMessage, onDisconnect) {
  985. this.onDisconnect = onDisconnect;
  986. this.onMessage = onMessage;
  987. this.log_('Websocket connecting to ' + this.connURL);
  988. this.everConnected_ = false;
  989. // Assume failure until proven otherwise.
  990. PersistentStorage.set('previous_websocket_failure', true);
  991. try {
  992. let options;
  993. if (isNodeSdk()) {
  994. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  995. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  996. options = {
  997. headers: {
  998. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  999. 'X-Firebase-GMPID': this.applicationId || ''
  1000. }
  1001. };
  1002. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1003. // Note that we send the credentials here even if they aren't admin credentials, which is
  1004. // not a problem.
  1005. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1006. // through the websocket connection once it is established.
  1007. if (this.authToken) {
  1008. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1009. }
  1010. if (this.appCheckToken) {
  1011. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1012. }
  1013. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1014. const env = process['env'];
  1015. const proxy = this.connURL.indexOf('wss://') === 0
  1016. ? env['HTTPS_PROXY'] || env['https_proxy']
  1017. : env['HTTP_PROXY'] || env['http_proxy'];
  1018. if (proxy) {
  1019. options['proxy'] = { origin: proxy };
  1020. }
  1021. }
  1022. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1023. }
  1024. catch (e) {
  1025. this.log_('Error instantiating WebSocket.');
  1026. const error = e.message || e.data;
  1027. if (error) {
  1028. this.log_(error);
  1029. }
  1030. this.onClosed_();
  1031. return;
  1032. }
  1033. this.mySock.onopen = () => {
  1034. this.log_('Websocket connected.');
  1035. this.everConnected_ = true;
  1036. };
  1037. this.mySock.onclose = () => {
  1038. this.log_('Websocket connection was disconnected.');
  1039. this.mySock = null;
  1040. this.onClosed_();
  1041. };
  1042. this.mySock.onmessage = m => {
  1043. this.handleIncomingFrame(m);
  1044. };
  1045. this.mySock.onerror = e => {
  1046. this.log_('WebSocket error. Closing connection.');
  1047. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1048. const error = e.message || e.data;
  1049. if (error) {
  1050. this.log_(error);
  1051. }
  1052. this.onClosed_();
  1053. };
  1054. }
  1055. /**
  1056. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1057. */
  1058. start() { }
  1059. static forceDisallow() {
  1060. WebSocketConnection.forceDisallow_ = true;
  1061. }
  1062. static isAvailable() {
  1063. let isOldAndroid = false;
  1064. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1065. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1066. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1067. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1068. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1069. isOldAndroid = true;
  1070. }
  1071. }
  1072. }
  1073. return (!isOldAndroid &&
  1074. WebSocketImpl !== null &&
  1075. !WebSocketConnection.forceDisallow_);
  1076. }
  1077. /**
  1078. * Returns true if we previously failed to connect with this transport.
  1079. */
  1080. static previouslyFailed() {
  1081. // If our persistent storage is actually only in-memory storage,
  1082. // we default to assuming that it previously failed to be safe.
  1083. return (PersistentStorage.isInMemoryStorage ||
  1084. PersistentStorage.get('previous_websocket_failure') === true);
  1085. }
  1086. markConnectionHealthy() {
  1087. PersistentStorage.remove('previous_websocket_failure');
  1088. }
  1089. appendFrame_(data) {
  1090. this.frames.push(data);
  1091. if (this.frames.length === this.totalFrames) {
  1092. const fullMess = this.frames.join('');
  1093. this.frames = null;
  1094. const jsonMess = jsonEval(fullMess);
  1095. //handle the message
  1096. this.onMessage(jsonMess);
  1097. }
  1098. }
  1099. /**
  1100. * @param frameCount - The number of frames we are expecting from the server
  1101. */
  1102. handleNewFrameCount_(frameCount) {
  1103. this.totalFrames = frameCount;
  1104. this.frames = [];
  1105. }
  1106. /**
  1107. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1108. * @returns Any remaining data to be process, or null if there is none
  1109. */
  1110. extractFrameCount_(data) {
  1111. assert(this.frames === null, 'We already have a frame buffer');
  1112. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1113. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1114. if (data.length <= 6) {
  1115. const frameCount = Number(data);
  1116. if (!isNaN(frameCount)) {
  1117. this.handleNewFrameCount_(frameCount);
  1118. return null;
  1119. }
  1120. }
  1121. this.handleNewFrameCount_(1);
  1122. return data;
  1123. }
  1124. /**
  1125. * Process a websocket frame that has arrived from the server.
  1126. * @param mess - The frame data
  1127. */
  1128. handleIncomingFrame(mess) {
  1129. if (this.mySock === null) {
  1130. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1131. }
  1132. const data = mess['data'];
  1133. this.bytesReceived += data.length;
  1134. this.stats_.incrementCounter('bytes_received', data.length);
  1135. this.resetKeepAlive();
  1136. if (this.frames !== null) {
  1137. // we're buffering
  1138. this.appendFrame_(data);
  1139. }
  1140. else {
  1141. // try to parse out a frame count, otherwise, assume 1 and process it
  1142. const remainingData = this.extractFrameCount_(data);
  1143. if (remainingData !== null) {
  1144. this.appendFrame_(remainingData);
  1145. }
  1146. }
  1147. }
  1148. /**
  1149. * Send a message to the server
  1150. * @param data - The JSON object to transmit
  1151. */
  1152. send(data) {
  1153. this.resetKeepAlive();
  1154. const dataStr = stringify(data);
  1155. this.bytesSent += dataStr.length;
  1156. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1157. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1158. //up into multiple pieces if it doesn't fit in one request.
  1159. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1160. //Send the length header
  1161. if (dataSegs.length > 1) {
  1162. this.sendString_(String(dataSegs.length));
  1163. }
  1164. //Send the actual data in segments.
  1165. for (let i = 0; i < dataSegs.length; i++) {
  1166. this.sendString_(dataSegs[i]);
  1167. }
  1168. }
  1169. shutdown_() {
  1170. this.isClosed_ = true;
  1171. if (this.keepaliveTimer) {
  1172. clearInterval(this.keepaliveTimer);
  1173. this.keepaliveTimer = null;
  1174. }
  1175. if (this.mySock) {
  1176. this.mySock.close();
  1177. this.mySock = null;
  1178. }
  1179. }
  1180. onClosed_() {
  1181. if (!this.isClosed_) {
  1182. this.log_('WebSocket is closing itself');
  1183. this.shutdown_();
  1184. // since this is an internal close, trigger the close listener
  1185. if (this.onDisconnect) {
  1186. this.onDisconnect(this.everConnected_);
  1187. this.onDisconnect = null;
  1188. }
  1189. }
  1190. }
  1191. /**
  1192. * External-facing close handler.
  1193. * Close the websocket and kill the connection.
  1194. */
  1195. close() {
  1196. if (!this.isClosed_) {
  1197. this.log_('WebSocket is being closed');
  1198. this.shutdown_();
  1199. }
  1200. }
  1201. /**
  1202. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1203. * the last activity.
  1204. */
  1205. resetKeepAlive() {
  1206. clearInterval(this.keepaliveTimer);
  1207. this.keepaliveTimer = setInterval(() => {
  1208. //If there has been no websocket activity for a while, send a no-op
  1209. if (this.mySock) {
  1210. this.sendString_('0');
  1211. }
  1212. this.resetKeepAlive();
  1213. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1214. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1215. }
  1216. /**
  1217. * Send a string over the websocket.
  1218. *
  1219. * @param str - String to send.
  1220. */
  1221. sendString_(str) {
  1222. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1223. // calls for some unknown reason. We treat these as an error and disconnect.
  1224. // See https://app.asana.com/0/58926111402292/68021340250410
  1225. try {
  1226. this.mySock.send(str);
  1227. }
  1228. catch (e) {
  1229. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1230. setTimeout(this.onClosed_.bind(this), 0);
  1231. }
  1232. }
  1233. }
  1234. /**
  1235. * Number of response before we consider the connection "healthy."
  1236. */
  1237. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1238. /**
  1239. * Time to wait for the connection te become healthy before giving up.
  1240. */
  1241. WebSocketConnection.healthyTimeout = 30000;
  1242. const name = "@firebase/database";
  1243. const version = "1.0.9";
  1244. /**
  1245. * @license
  1246. * Copyright 2021 Google LLC
  1247. *
  1248. * Licensed under the Apache License, Version 2.0 (the "License");
  1249. * you may not use this file except in compliance with the License.
  1250. * You may obtain a copy of the License at
  1251. *
  1252. * http://www.apache.org/licenses/LICENSE-2.0
  1253. *
  1254. * Unless required by applicable law or agreed to in writing, software
  1255. * distributed under the License is distributed on an "AS IS" BASIS,
  1256. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1257. * See the License for the specific language governing permissions and
  1258. * limitations under the License.
  1259. */
  1260. /**
  1261. * Abstraction around AppCheck's token fetching capabilities.
  1262. */
  1263. class AppCheckTokenProvider {
  1264. constructor(appName_, appCheckProvider) {
  1265. this.appName_ = appName_;
  1266. this.appCheckProvider = appCheckProvider;
  1267. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1268. if (!this.appCheck) {
  1269. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  1270. }
  1271. }
  1272. getToken(forceRefresh) {
  1273. if (!this.appCheck) {
  1274. return new Promise((resolve, reject) => {
  1275. // Support delayed initialization of FirebaseAppCheck. This allows our
  1276. // customers to initialize the RTDB SDK before initializing Firebase
  1277. // AppCheck and ensures that all requests are authenticated if a token
  1278. // becomes available before the timeout below expires.
  1279. setTimeout(() => {
  1280. if (this.appCheck) {
  1281. this.getToken(forceRefresh).then(resolve, reject);
  1282. }
  1283. else {
  1284. resolve(null);
  1285. }
  1286. }, 0);
  1287. });
  1288. }
  1289. return this.appCheck.getToken(forceRefresh);
  1290. }
  1291. addTokenChangeListener(listener) {
  1292. var _a;
  1293. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  1294. }
  1295. notifyForInvalidToken() {
  1296. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  1297. 'are invalid. This usually indicates your app was not initialized correctly.');
  1298. }
  1299. }
  1300. /**
  1301. * @license
  1302. * Copyright 2017 Google LLC
  1303. *
  1304. * Licensed under the Apache License, Version 2.0 (the "License");
  1305. * you may not use this file except in compliance with the License.
  1306. * You may obtain a copy of the License at
  1307. *
  1308. * http://www.apache.org/licenses/LICENSE-2.0
  1309. *
  1310. * Unless required by applicable law or agreed to in writing, software
  1311. * distributed under the License is distributed on an "AS IS" BASIS,
  1312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1313. * See the License for the specific language governing permissions and
  1314. * limitations under the License.
  1315. */
  1316. /**
  1317. * Abstraction around FirebaseApp's token fetching capabilities.
  1318. */
  1319. class FirebaseAuthTokenProvider {
  1320. constructor(appName_, firebaseOptions_, authProvider_) {
  1321. this.appName_ = appName_;
  1322. this.firebaseOptions_ = firebaseOptions_;
  1323. this.authProvider_ = authProvider_;
  1324. this.auth_ = null;
  1325. this.auth_ = authProvider_.getImmediate({ optional: true });
  1326. if (!this.auth_) {
  1327. authProvider_.onInit(auth => (this.auth_ = auth));
  1328. }
  1329. }
  1330. getToken(forceRefresh) {
  1331. if (!this.auth_) {
  1332. return new Promise((resolve, reject) => {
  1333. // Support delayed initialization of FirebaseAuth. This allows our
  1334. // customers to initialize the RTDB SDK before initializing Firebase
  1335. // Auth and ensures that all requests are authenticated if a token
  1336. // becomes available before the timeout below expires.
  1337. setTimeout(() => {
  1338. if (this.auth_) {
  1339. this.getToken(forceRefresh).then(resolve, reject);
  1340. }
  1341. else {
  1342. resolve(null);
  1343. }
  1344. }, 0);
  1345. });
  1346. }
  1347. return this.auth_.getToken(forceRefresh).catch(error => {
  1348. // TODO: Need to figure out all the cases this is raised and whether
  1349. // this makes sense.
  1350. if (error && error.code === 'auth/token-not-initialized') {
  1351. log('Got auth/token-not-initialized error. Treating as null token.');
  1352. return null;
  1353. }
  1354. else {
  1355. return Promise.reject(error);
  1356. }
  1357. });
  1358. }
  1359. addTokenChangeListener(listener) {
  1360. // TODO: We might want to wrap the listener and call it with no args to
  1361. // avoid a leaky abstraction, but that makes removing the listener harder.
  1362. if (this.auth_) {
  1363. this.auth_.addAuthTokenListener(listener);
  1364. }
  1365. else {
  1366. this.authProvider_
  1367. .get()
  1368. .then(auth => auth.addAuthTokenListener(listener));
  1369. }
  1370. }
  1371. removeTokenChangeListener(listener) {
  1372. this.authProvider_
  1373. .get()
  1374. .then(auth => auth.removeAuthTokenListener(listener));
  1375. }
  1376. notifyForInvalidToken() {
  1377. let errorMessage = 'Provided authentication credentials for the app named "' +
  1378. this.appName_ +
  1379. '" are invalid. This usually indicates your app was not ' +
  1380. 'initialized correctly. ';
  1381. if ('credential' in this.firebaseOptions_) {
  1382. errorMessage +=
  1383. 'Make sure the "credential" property provided to initializeApp() ' +
  1384. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1385. 'project.';
  1386. }
  1387. else if ('serviceAccount' in this.firebaseOptions_) {
  1388. errorMessage +=
  1389. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1390. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1391. 'project.';
  1392. }
  1393. else {
  1394. errorMessage +=
  1395. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1396. 'initializeApp() match the values provided for your app at ' +
  1397. 'https://console.firebase.google.com/.';
  1398. }
  1399. warn(errorMessage);
  1400. }
  1401. }
  1402. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1403. class EmulatorTokenProvider {
  1404. constructor(accessToken) {
  1405. this.accessToken = accessToken;
  1406. }
  1407. getToken(forceRefresh) {
  1408. return Promise.resolve({
  1409. accessToken: this.accessToken
  1410. });
  1411. }
  1412. addTokenChangeListener(listener) {
  1413. // Invoke the listener immediately to match the behavior in Firebase Auth
  1414. // (see packages/auth/src/auth.js#L1807)
  1415. listener(this.accessToken);
  1416. }
  1417. removeTokenChangeListener(listener) { }
  1418. notifyForInvalidToken() { }
  1419. }
  1420. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1421. EmulatorTokenProvider.OWNER = 'owner';
  1422. /**
  1423. * @license
  1424. * Copyright 2017 Google LLC
  1425. *
  1426. * Licensed under the Apache License, Version 2.0 (the "License");
  1427. * you may not use this file except in compliance with the License.
  1428. * You may obtain a copy of the License at
  1429. *
  1430. * http://www.apache.org/licenses/LICENSE-2.0
  1431. *
  1432. * Unless required by applicable law or agreed to in writing, software
  1433. * distributed under the License is distributed on an "AS IS" BASIS,
  1434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1435. * See the License for the specific language governing permissions and
  1436. * limitations under the License.
  1437. */
  1438. /**
  1439. * This class ensures the packets from the server arrive in order
  1440. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1441. */
  1442. class PacketReceiver {
  1443. /**
  1444. * @param onMessage_
  1445. */
  1446. constructor(onMessage_) {
  1447. this.onMessage_ = onMessage_;
  1448. this.pendingResponses = [];
  1449. this.currentResponseNum = 0;
  1450. this.closeAfterResponse = -1;
  1451. this.onClose = null;
  1452. }
  1453. closeAfter(responseNum, callback) {
  1454. this.closeAfterResponse = responseNum;
  1455. this.onClose = callback;
  1456. if (this.closeAfterResponse < this.currentResponseNum) {
  1457. this.onClose();
  1458. this.onClose = null;
  1459. }
  1460. }
  1461. /**
  1462. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1463. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1464. * browsers will respond in the same order as the requests we sent
  1465. */
  1466. handleResponse(requestNum, data) {
  1467. this.pendingResponses[requestNum] = data;
  1468. while (this.pendingResponses[this.currentResponseNum]) {
  1469. const toProcess = this.pendingResponses[this.currentResponseNum];
  1470. delete this.pendingResponses[this.currentResponseNum];
  1471. for (let i = 0; i < toProcess.length; ++i) {
  1472. if (toProcess[i]) {
  1473. exceptionGuard(() => {
  1474. this.onMessage_(toProcess[i]);
  1475. });
  1476. }
  1477. }
  1478. if (this.currentResponseNum === this.closeAfterResponse) {
  1479. if (this.onClose) {
  1480. this.onClose();
  1481. this.onClose = null;
  1482. }
  1483. break;
  1484. }
  1485. this.currentResponseNum++;
  1486. }
  1487. }
  1488. }
  1489. /**
  1490. * @license
  1491. * Copyright 2017 Google LLC
  1492. *
  1493. * Licensed under the Apache License, Version 2.0 (the "License");
  1494. * you may not use this file except in compliance with the License.
  1495. * You may obtain a copy of the License at
  1496. *
  1497. * http://www.apache.org/licenses/LICENSE-2.0
  1498. *
  1499. * Unless required by applicable law or agreed to in writing, software
  1500. * distributed under the License is distributed on an "AS IS" BASIS,
  1501. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1502. * See the License for the specific language governing permissions and
  1503. * limitations under the License.
  1504. */
  1505. // URL query parameters associated with longpolling
  1506. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1507. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1508. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1509. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1510. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1511. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1512. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1513. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1514. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1515. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1516. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1517. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1518. //Data size constants.
  1519. //TODO: Perf: the maximum length actually differs from browser to browser.
  1520. // We should check what browser we're on and set accordingly.
  1521. const MAX_URL_DATA_SIZE = 1870;
  1522. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1523. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1524. /**
  1525. * Keepalive period
  1526. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1527. * length of 30 seconds that we can't exceed.
  1528. */
  1529. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1530. /**
  1531. * How long to wait before aborting a long-polling connection attempt.
  1532. */
  1533. const LP_CONNECT_TIMEOUT = 30000;
  1534. /**
  1535. * This class manages a single long-polling connection.
  1536. */
  1537. class BrowserPollConnection {
  1538. /**
  1539. * @param connId An identifier for this connection, used for logging
  1540. * @param repoInfo The info for the endpoint to send data to.
  1541. * @param applicationId The Firebase App ID for this project.
  1542. * @param appCheckToken The AppCheck token for this client.
  1543. * @param authToken The AuthToken to use for this connection.
  1544. * @param transportSessionId Optional transportSessionid if we are
  1545. * reconnecting for an existing transport session
  1546. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1547. * already created a connection previously
  1548. */
  1549. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1550. this.connId = connId;
  1551. this.repoInfo = repoInfo;
  1552. this.applicationId = applicationId;
  1553. this.appCheckToken = appCheckToken;
  1554. this.authToken = authToken;
  1555. this.transportSessionId = transportSessionId;
  1556. this.lastSessionId = lastSessionId;
  1557. this.bytesSent = 0;
  1558. this.bytesReceived = 0;
  1559. this.everConnected_ = false;
  1560. this.log_ = logWrapper(connId);
  1561. this.stats_ = statsManagerGetCollection(repoInfo);
  1562. this.urlFn = (params) => {
  1563. // Always add the token if we have one.
  1564. if (this.appCheckToken) {
  1565. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1566. }
  1567. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1568. };
  1569. }
  1570. /**
  1571. * @param onMessage - Callback when messages arrive
  1572. * @param onDisconnect - Callback with connection lost.
  1573. */
  1574. open(onMessage, onDisconnect) {
  1575. this.curSegmentNum = 0;
  1576. this.onDisconnect_ = onDisconnect;
  1577. this.myPacketOrderer = new PacketReceiver(onMessage);
  1578. this.isClosed_ = false;
  1579. this.connectTimeoutTimer_ = setTimeout(() => {
  1580. this.log_('Timed out trying to connect.');
  1581. // Make sure we clear the host cache
  1582. this.onClosed_();
  1583. this.connectTimeoutTimer_ = null;
  1584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1585. }, Math.floor(LP_CONNECT_TIMEOUT));
  1586. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1587. executeWhenDOMReady(() => {
  1588. if (this.isClosed_) {
  1589. return;
  1590. }
  1591. //Set up a callback that gets triggered once a connection is set up.
  1592. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1593. const [command, arg1, arg2, arg3, arg4] = args;
  1594. this.incrementIncomingBytes_(args);
  1595. if (!this.scriptTagHolder) {
  1596. return; // we closed the connection.
  1597. }
  1598. if (this.connectTimeoutTimer_) {
  1599. clearTimeout(this.connectTimeoutTimer_);
  1600. this.connectTimeoutTimer_ = null;
  1601. }
  1602. this.everConnected_ = true;
  1603. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1604. this.id = arg1;
  1605. this.password = arg2;
  1606. }
  1607. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1608. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1609. if (arg1) {
  1610. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1611. // through our already open polls), so don't send any more.
  1612. this.scriptTagHolder.sendNewPolls = false;
  1613. // arg1 in this case is the last response number sent by the server. We should try to receive
  1614. // all of the responses up to this one before closing
  1615. this.myPacketOrderer.closeAfter(arg1, () => {
  1616. this.onClosed_();
  1617. });
  1618. }
  1619. else {
  1620. this.onClosed_();
  1621. }
  1622. }
  1623. else {
  1624. throw new Error('Unrecognized command received: ' + command);
  1625. }
  1626. }, (...args) => {
  1627. const [pN, data] = args;
  1628. this.incrementIncomingBytes_(args);
  1629. this.myPacketOrderer.handleResponse(pN, data);
  1630. }, () => {
  1631. this.onClosed_();
  1632. }, this.urlFn);
  1633. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1634. //from cache.
  1635. const urlParams = {};
  1636. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1637. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1638. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1639. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1640. this.scriptTagHolder.uniqueCallbackIdentifier;
  1641. }
  1642. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1643. if (this.transportSessionId) {
  1644. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1645. }
  1646. if (this.lastSessionId) {
  1647. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1648. }
  1649. if (this.applicationId) {
  1650. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1651. }
  1652. if (this.appCheckToken) {
  1653. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1654. }
  1655. if (typeof location !== 'undefined' &&
  1656. location.hostname &&
  1657. FORGE_DOMAIN_RE.test(location.hostname)) {
  1658. urlParams[REFERER_PARAM] = FORGE_REF;
  1659. }
  1660. const connectURL = this.urlFn(urlParams);
  1661. this.log_('Connecting via long-poll to ' + connectURL);
  1662. this.scriptTagHolder.addTag(connectURL, () => {
  1663. /* do nothing */
  1664. });
  1665. });
  1666. }
  1667. /**
  1668. * Call this when a handshake has completed successfully and we want to consider the connection established
  1669. */
  1670. start() {
  1671. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1672. this.addDisconnectPingFrame(this.id, this.password);
  1673. }
  1674. /**
  1675. * Forces long polling to be considered as a potential transport
  1676. */
  1677. static forceAllow() {
  1678. BrowserPollConnection.forceAllow_ = true;
  1679. }
  1680. /**
  1681. * Forces longpolling to not be considered as a potential transport
  1682. */
  1683. static forceDisallow() {
  1684. BrowserPollConnection.forceDisallow_ = true;
  1685. }
  1686. // Static method, use string literal so it can be accessed in a generic way
  1687. static isAvailable() {
  1688. if (isNodeSdk()) {
  1689. return false;
  1690. }
  1691. else if (BrowserPollConnection.forceAllow_) {
  1692. return true;
  1693. }
  1694. else {
  1695. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1696. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1697. return (!BrowserPollConnection.forceDisallow_ &&
  1698. typeof document !== 'undefined' &&
  1699. document.createElement != null &&
  1700. !isChromeExtensionContentScript() &&
  1701. !isWindowsStoreApp());
  1702. }
  1703. }
  1704. /**
  1705. * No-op for polling
  1706. */
  1707. markConnectionHealthy() { }
  1708. /**
  1709. * Stops polling and cleans up the iframe
  1710. */
  1711. shutdown_() {
  1712. this.isClosed_ = true;
  1713. if (this.scriptTagHolder) {
  1714. this.scriptTagHolder.close();
  1715. this.scriptTagHolder = null;
  1716. }
  1717. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1718. if (this.myDisconnFrame) {
  1719. document.body.removeChild(this.myDisconnFrame);
  1720. this.myDisconnFrame = null;
  1721. }
  1722. if (this.connectTimeoutTimer_) {
  1723. clearTimeout(this.connectTimeoutTimer_);
  1724. this.connectTimeoutTimer_ = null;
  1725. }
  1726. }
  1727. /**
  1728. * Triggered when this transport is closed
  1729. */
  1730. onClosed_() {
  1731. if (!this.isClosed_) {
  1732. this.log_('Longpoll is closing itself');
  1733. this.shutdown_();
  1734. if (this.onDisconnect_) {
  1735. this.onDisconnect_(this.everConnected_);
  1736. this.onDisconnect_ = null;
  1737. }
  1738. }
  1739. }
  1740. /**
  1741. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1742. * that we've left.
  1743. */
  1744. close() {
  1745. if (!this.isClosed_) {
  1746. this.log_('Longpoll is being closed.');
  1747. this.shutdown_();
  1748. }
  1749. }
  1750. /**
  1751. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1752. * broken into chunks (since URLs have a small maximum length).
  1753. * @param data - The JSON data to transmit.
  1754. */
  1755. send(data) {
  1756. const dataStr = stringify(data);
  1757. this.bytesSent += dataStr.length;
  1758. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1759. //first, lets get the base64-encoded data
  1760. const base64data = base64Encode(dataStr);
  1761. //We can only fit a certain amount in each URL, so we need to split this request
  1762. //up into multiple pieces if it doesn't fit in one request.
  1763. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1764. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1765. //of segments so that we can reassemble the packet on the server.
  1766. for (let i = 0; i < dataSegs.length; i++) {
  1767. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1768. this.curSegmentNum++;
  1769. }
  1770. }
  1771. /**
  1772. * This is how we notify the server that we're leaving.
  1773. * We aren't able to send requests with DHTML on a window close event, but we can
  1774. * trigger XHR requests in some browsers (everything but Opera basically).
  1775. */
  1776. addDisconnectPingFrame(id, pw) {
  1777. if (isNodeSdk()) {
  1778. return;
  1779. }
  1780. this.myDisconnFrame = document.createElement('iframe');
  1781. const urlParams = {};
  1782. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1783. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1784. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1785. this.myDisconnFrame.src = this.urlFn(urlParams);
  1786. this.myDisconnFrame.style.display = 'none';
  1787. document.body.appendChild(this.myDisconnFrame);
  1788. }
  1789. /**
  1790. * Used to track the bytes received by this client
  1791. */
  1792. incrementIncomingBytes_(args) {
  1793. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1794. const bytesReceived = stringify(args).length;
  1795. this.bytesReceived += bytesReceived;
  1796. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1797. }
  1798. }
  1799. /*********************************************************************************************
  1800. * A wrapper around an iframe that is used as a long-polling script holder.
  1801. *********************************************************************************************/
  1802. class FirebaseIFrameScriptHolder {
  1803. /**
  1804. * @param commandCB - The callback to be called when control commands are received from the server.
  1805. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1806. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1807. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1808. */
  1809. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1810. this.onDisconnect = onDisconnect;
  1811. this.urlFn = urlFn;
  1812. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1813. //problems in some browsers.
  1814. this.outstandingRequests = new Set();
  1815. //A queue of the pending segments waiting for transmission to the server.
  1816. this.pendingSegs = [];
  1817. //A serial number. We use this for two things:
  1818. // 1) A way to ensure the browser doesn't cache responses to polls
  1819. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1820. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1821. // JSONP code in the order it was added to the iframe.
  1822. this.currentSerial = Math.floor(Math.random() * 100000000);
  1823. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1824. // incoming data from the server that we're waiting for).
  1825. this.sendNewPolls = true;
  1826. if (!isNodeSdk()) {
  1827. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1828. //iframes where we put the long-polling script tags. We have two callbacks:
  1829. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1830. // 2) Message Callback - Triggered when new data arrives.
  1831. this.uniqueCallbackIdentifier = LUIDGenerator();
  1832. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1833. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1834. onMessageCB;
  1835. //Create an iframe for us to add script tags to.
  1836. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1837. // Set the iframe's contents.
  1838. let script = '';
  1839. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1840. // for ie9, but ie8 needs to do it again in the document itself.
  1841. if (this.myIFrame.src &&
  1842. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1843. const currentDomain = document.domain;
  1844. script = '<script>document.domain="' + currentDomain + '";</script>';
  1845. }
  1846. const iframeContents = '<html><body>' + script + '</body></html>';
  1847. try {
  1848. this.myIFrame.doc.open();
  1849. this.myIFrame.doc.write(iframeContents);
  1850. this.myIFrame.doc.close();
  1851. }
  1852. catch (e) {
  1853. log('frame writing exception');
  1854. if (e.stack) {
  1855. log(e.stack);
  1856. }
  1857. log(e);
  1858. }
  1859. }
  1860. else {
  1861. this.commandCB = commandCB;
  1862. this.onMessageCB = onMessageCB;
  1863. }
  1864. }
  1865. /**
  1866. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1867. * actually use.
  1868. */
  1869. static createIFrame_() {
  1870. const iframe = document.createElement('iframe');
  1871. iframe.style.display = 'none';
  1872. // This is necessary in order to initialize the document inside the iframe
  1873. if (document.body) {
  1874. document.body.appendChild(iframe);
  1875. try {
  1876. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1877. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1878. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1879. const a = iframe.contentWindow.document;
  1880. if (!a) {
  1881. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1882. log('No IE domain setting required');
  1883. }
  1884. }
  1885. catch (e) {
  1886. const domain = document.domain;
  1887. iframe.src =
  1888. "javascript:void((function(){document.open();document.domain='" +
  1889. domain +
  1890. "';document.close();})())";
  1891. }
  1892. }
  1893. else {
  1894. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1895. // never gets hit.
  1896. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1897. }
  1898. // Get the document of the iframe in a browser-specific way.
  1899. if (iframe.contentDocument) {
  1900. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1901. }
  1902. else if (iframe.contentWindow) {
  1903. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1904. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1905. }
  1906. else if (iframe.document) {
  1907. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1908. iframe.doc = iframe.document; //others?
  1909. }
  1910. return iframe;
  1911. }
  1912. /**
  1913. * Cancel all outstanding queries and remove the frame.
  1914. */
  1915. close() {
  1916. //Mark this iframe as dead, so no new requests are sent.
  1917. this.alive = false;
  1918. if (this.myIFrame) {
  1919. //We have to actually remove all of the html inside this iframe before removing it from the
  1920. //window, or IE will continue loading and executing the script tags we've already added, which
  1921. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1922. this.myIFrame.doc.body.textContent = '';
  1923. setTimeout(() => {
  1924. if (this.myIFrame !== null) {
  1925. document.body.removeChild(this.myIFrame);
  1926. this.myIFrame = null;
  1927. }
  1928. }, Math.floor(0));
  1929. }
  1930. // Protect from being called recursively.
  1931. const onDisconnect = this.onDisconnect;
  1932. if (onDisconnect) {
  1933. this.onDisconnect = null;
  1934. onDisconnect();
  1935. }
  1936. }
  1937. /**
  1938. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1939. * @param id - The ID of this connection
  1940. * @param pw - The password for this connection
  1941. */
  1942. startLongPoll(id, pw) {
  1943. this.myID = id;
  1944. this.myPW = pw;
  1945. this.alive = true;
  1946. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1947. while (this.newRequest_()) { }
  1948. }
  1949. /**
  1950. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1951. * too many outstanding requests and we are still alive.
  1952. *
  1953. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1954. * needed.
  1955. */
  1956. newRequest_() {
  1957. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1958. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1959. // close the old request.
  1960. if (this.alive &&
  1961. this.sendNewPolls &&
  1962. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1963. //construct our url
  1964. this.currentSerial++;
  1965. const urlParams = {};
  1966. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1967. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1968. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1969. let theURL = this.urlFn(urlParams);
  1970. //Now add as much data as we can.
  1971. let curDataString = '';
  1972. let i = 0;
  1973. while (this.pendingSegs.length > 0) {
  1974. //first, lets see if the next segment will fit.
  1975. const nextSeg = this.pendingSegs[0];
  1976. if (nextSeg.d.length +
  1977. SEG_HEADER_SIZE +
  1978. curDataString.length <=
  1979. MAX_URL_DATA_SIZE) {
  1980. //great, the segment will fit. Lets append it.
  1981. const theSeg = this.pendingSegs.shift();
  1982. curDataString =
  1983. curDataString +
  1984. '&' +
  1985. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1986. i +
  1987. '=' +
  1988. theSeg.seg +
  1989. '&' +
  1990. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1991. i +
  1992. '=' +
  1993. theSeg.ts +
  1994. '&' +
  1995. FIREBASE_LONGPOLL_DATA_PARAM +
  1996. i +
  1997. '=' +
  1998. theSeg.d;
  1999. i++;
  2000. }
  2001. else {
  2002. break;
  2003. }
  2004. }
  2005. theURL = theURL + curDataString;
  2006. this.addLongPollTag_(theURL, this.currentSerial);
  2007. return true;
  2008. }
  2009. else {
  2010. return false;
  2011. }
  2012. }
  2013. /**
  2014. * Queue a packet for transmission to the server.
  2015. * @param segnum - A sequential id for this packet segment used for reassembly
  2016. * @param totalsegs - The total number of segments in this packet
  2017. * @param data - The data for this segment.
  2018. */
  2019. enqueueSegment(segnum, totalsegs, data) {
  2020. //add this to the queue of segments to send.
  2021. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2022. //send the data immediately if there isn't already data being transmitted, unless
  2023. //startLongPoll hasn't been called yet.
  2024. if (this.alive) {
  2025. this.newRequest_();
  2026. }
  2027. }
  2028. /**
  2029. * Add a script tag for a regular long-poll request.
  2030. * @param url - The URL of the script tag.
  2031. * @param serial - The serial number of the request.
  2032. */
  2033. addLongPollTag_(url, serial) {
  2034. //remember that we sent this request.
  2035. this.outstandingRequests.add(serial);
  2036. const doNewRequest = () => {
  2037. this.outstandingRequests.delete(serial);
  2038. this.newRequest_();
  2039. };
  2040. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2041. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2042. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2043. const readyStateCB = () => {
  2044. // Request completed. Cancel the keepalive.
  2045. clearTimeout(keepaliveTimeout);
  2046. // Trigger a new request so we can continue receiving data.
  2047. doNewRequest();
  2048. };
  2049. this.addTag(url, readyStateCB);
  2050. }
  2051. /**
  2052. * Add an arbitrary script tag to the iframe.
  2053. * @param url - The URL for the script tag source.
  2054. * @param loadCB - A callback to be triggered once the script has loaded.
  2055. */
  2056. addTag(url, loadCB) {
  2057. if (isNodeSdk()) {
  2058. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2059. this.doNodeLongPoll(url, loadCB);
  2060. }
  2061. else {
  2062. setTimeout(() => {
  2063. try {
  2064. // if we're already closed, don't add this poll
  2065. if (!this.sendNewPolls) {
  2066. return;
  2067. }
  2068. const newScript = this.myIFrame.doc.createElement('script');
  2069. newScript.type = 'text/javascript';
  2070. newScript.async = true;
  2071. newScript.src = url;
  2072. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2073. newScript.onload = newScript.onreadystatechange =
  2074. function () {
  2075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2076. const rstate = newScript.readyState;
  2077. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2078. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2079. newScript.onload = newScript.onreadystatechange = null;
  2080. if (newScript.parentNode) {
  2081. newScript.parentNode.removeChild(newScript);
  2082. }
  2083. loadCB();
  2084. }
  2085. };
  2086. newScript.onerror = () => {
  2087. log('Long-poll script failed to load: ' + url);
  2088. this.sendNewPolls = false;
  2089. this.close();
  2090. };
  2091. this.myIFrame.doc.body.appendChild(newScript);
  2092. }
  2093. catch (e) {
  2094. // TODO: we should make this error visible somehow
  2095. }
  2096. }, Math.floor(1));
  2097. }
  2098. }
  2099. }
  2100. /**
  2101. * @license
  2102. * Copyright 2017 Google LLC
  2103. *
  2104. * Licensed under the Apache License, Version 2.0 (the "License");
  2105. * you may not use this file except in compliance with the License.
  2106. * You may obtain a copy of the License at
  2107. *
  2108. * http://www.apache.org/licenses/LICENSE-2.0
  2109. *
  2110. * Unless required by applicable law or agreed to in writing, software
  2111. * distributed under the License is distributed on an "AS IS" BASIS,
  2112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2113. * See the License for the specific language governing permissions and
  2114. * limitations under the License.
  2115. */
  2116. /**
  2117. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2118. * lifecycle.
  2119. *
  2120. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2121. * they are available.
  2122. */
  2123. class TransportManager {
  2124. /**
  2125. * @param repoInfo - Metadata around the namespace we're connecting to
  2126. */
  2127. constructor(repoInfo) {
  2128. this.initTransports_(repoInfo);
  2129. }
  2130. static get ALL_TRANSPORTS() {
  2131. return [BrowserPollConnection, WebSocketConnection];
  2132. }
  2133. /**
  2134. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2135. * TransportManager has already set up transports_
  2136. */
  2137. static get IS_TRANSPORT_INITIALIZED() {
  2138. return this.globalTransportInitialized_;
  2139. }
  2140. initTransports_(repoInfo) {
  2141. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2142. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2143. if (repoInfo.webSocketOnly) {
  2144. if (!isWebSocketsAvailable) {
  2145. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2146. }
  2147. isSkipPollConnection = true;
  2148. }
  2149. if (isSkipPollConnection) {
  2150. this.transports_ = [WebSocketConnection];
  2151. }
  2152. else {
  2153. const transports = (this.transports_ = []);
  2154. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2155. if (transport && transport['isAvailable']()) {
  2156. transports.push(transport);
  2157. }
  2158. }
  2159. TransportManager.globalTransportInitialized_ = true;
  2160. }
  2161. }
  2162. /**
  2163. * @returns The constructor for the initial transport to use
  2164. */
  2165. initialTransport() {
  2166. if (this.transports_.length > 0) {
  2167. return this.transports_[0];
  2168. }
  2169. else {
  2170. throw new Error('No transports available');
  2171. }
  2172. }
  2173. /**
  2174. * @returns The constructor for the next transport, or null
  2175. */
  2176. upgradeTransport() {
  2177. if (this.transports_.length > 1) {
  2178. return this.transports_[1];
  2179. }
  2180. else {
  2181. return null;
  2182. }
  2183. }
  2184. }
  2185. // Keeps track of whether the TransportManager has already chosen a transport to use
  2186. TransportManager.globalTransportInitialized_ = false;
  2187. /**
  2188. * @license
  2189. * Copyright 2017 Google LLC
  2190. *
  2191. * Licensed under the Apache License, Version 2.0 (the "License");
  2192. * you may not use this file except in compliance with the License.
  2193. * You may obtain a copy of the License at
  2194. *
  2195. * http://www.apache.org/licenses/LICENSE-2.0
  2196. *
  2197. * Unless required by applicable law or agreed to in writing, software
  2198. * distributed under the License is distributed on an "AS IS" BASIS,
  2199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2200. * See the License for the specific language governing permissions and
  2201. * limitations under the License.
  2202. */
  2203. // Abort upgrade attempt if it takes longer than 60s.
  2204. const UPGRADE_TIMEOUT = 60000;
  2205. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2206. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2207. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2208. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  2209. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2210. // but we've sent/received enough bytes, we don't cancel the connection.
  2211. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2212. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2213. const MESSAGE_TYPE = 't';
  2214. const MESSAGE_DATA = 'd';
  2215. const CONTROL_SHUTDOWN = 's';
  2216. const CONTROL_RESET = 'r';
  2217. const CONTROL_ERROR = 'e';
  2218. const CONTROL_PONG = 'o';
  2219. const SWITCH_ACK = 'a';
  2220. const END_TRANSMISSION = 'n';
  2221. const PING = 'p';
  2222. const SERVER_HELLO = 'h';
  2223. /**
  2224. * Creates a new real-time connection to the server using whichever method works
  2225. * best in the current browser.
  2226. */
  2227. class Connection {
  2228. /**
  2229. * @param id - an id for this connection
  2230. * @param repoInfo_ - the info for the endpoint to connect to
  2231. * @param applicationId_ - the Firebase App ID for this project
  2232. * @param appCheckToken_ - The App Check Token for this device.
  2233. * @param authToken_ - The auth token for this session.
  2234. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2235. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2236. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2237. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2238. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2239. */
  2240. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2241. this.id = id;
  2242. this.repoInfo_ = repoInfo_;
  2243. this.applicationId_ = applicationId_;
  2244. this.appCheckToken_ = appCheckToken_;
  2245. this.authToken_ = authToken_;
  2246. this.onMessage_ = onMessage_;
  2247. this.onReady_ = onReady_;
  2248. this.onDisconnect_ = onDisconnect_;
  2249. this.onKill_ = onKill_;
  2250. this.lastSessionId = lastSessionId;
  2251. this.connectionCount = 0;
  2252. this.pendingDataMessages = [];
  2253. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2254. this.log_ = logWrapper('c:' + this.id + ':');
  2255. this.transportManager_ = new TransportManager(repoInfo_);
  2256. this.log_('Connection created');
  2257. this.start_();
  2258. }
  2259. /**
  2260. * Starts a connection attempt
  2261. */
  2262. start_() {
  2263. const conn = this.transportManager_.initialTransport();
  2264. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2265. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2266. // can consider the transport healthy.
  2267. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2268. const onMessageReceived = this.connReceiver_(this.conn_);
  2269. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2270. this.tx_ = this.conn_;
  2271. this.rx_ = this.conn_;
  2272. this.secondaryConn_ = null;
  2273. this.isHealthy_ = false;
  2274. /*
  2275. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2276. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2277. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2278. * still have the context of your originating frame.
  2279. */
  2280. setTimeout(() => {
  2281. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2282. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2283. }, Math.floor(0));
  2284. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2285. if (healthyTimeoutMS > 0) {
  2286. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2287. this.healthyTimeout_ = null;
  2288. if (!this.isHealthy_) {
  2289. if (this.conn_ &&
  2290. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2291. this.log_('Connection exceeded healthy timeout but has received ' +
  2292. this.conn_.bytesReceived +
  2293. ' bytes. Marking connection healthy.');
  2294. this.isHealthy_ = true;
  2295. this.conn_.markConnectionHealthy();
  2296. }
  2297. else if (this.conn_ &&
  2298. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2299. this.log_('Connection exceeded healthy timeout but has sent ' +
  2300. this.conn_.bytesSent +
  2301. ' bytes. Leaving connection alive.');
  2302. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2303. // the server.
  2304. }
  2305. else {
  2306. this.log_('Closing unhealthy connection after timeout.');
  2307. this.close();
  2308. }
  2309. }
  2310. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2311. }, Math.floor(healthyTimeoutMS));
  2312. }
  2313. }
  2314. nextTransportId_() {
  2315. return 'c:' + this.id + ':' + this.connectionCount++;
  2316. }
  2317. disconnReceiver_(conn) {
  2318. return everConnected => {
  2319. if (conn === this.conn_) {
  2320. this.onConnectionLost_(everConnected);
  2321. }
  2322. else if (conn === this.secondaryConn_) {
  2323. this.log_('Secondary connection lost.');
  2324. this.onSecondaryConnectionLost_();
  2325. }
  2326. else {
  2327. this.log_('closing an old connection');
  2328. }
  2329. };
  2330. }
  2331. connReceiver_(conn) {
  2332. return (message) => {
  2333. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2334. if (conn === this.rx_) {
  2335. this.onPrimaryMessageReceived_(message);
  2336. }
  2337. else if (conn === this.secondaryConn_) {
  2338. this.onSecondaryMessageReceived_(message);
  2339. }
  2340. else {
  2341. this.log_('message on old connection');
  2342. }
  2343. }
  2344. };
  2345. }
  2346. /**
  2347. * @param dataMsg - An arbitrary data message to be sent to the server
  2348. */
  2349. sendRequest(dataMsg) {
  2350. // wrap in a data message envelope and send it on
  2351. const msg = { t: 'd', d: dataMsg };
  2352. this.sendData_(msg);
  2353. }
  2354. tryCleanupConnection() {
  2355. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2356. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2357. this.conn_ = this.secondaryConn_;
  2358. this.secondaryConn_ = null;
  2359. // the server will shutdown the old connection
  2360. }
  2361. }
  2362. onSecondaryControl_(controlData) {
  2363. if (MESSAGE_TYPE in controlData) {
  2364. const cmd = controlData[MESSAGE_TYPE];
  2365. if (cmd === SWITCH_ACK) {
  2366. this.upgradeIfSecondaryHealthy_();
  2367. }
  2368. else if (cmd === CONTROL_RESET) {
  2369. // Most likely the session wasn't valid. Abandon the switch attempt
  2370. this.log_('Got a reset on secondary, closing it');
  2371. this.secondaryConn_.close();
  2372. // If we were already using this connection for something, than we need to fully close
  2373. if (this.tx_ === this.secondaryConn_ ||
  2374. this.rx_ === this.secondaryConn_) {
  2375. this.close();
  2376. }
  2377. }
  2378. else if (cmd === CONTROL_PONG) {
  2379. this.log_('got pong on secondary.');
  2380. this.secondaryResponsesRequired_--;
  2381. this.upgradeIfSecondaryHealthy_();
  2382. }
  2383. }
  2384. }
  2385. onSecondaryMessageReceived_(parsedData) {
  2386. const layer = requireKey('t', parsedData);
  2387. const data = requireKey('d', parsedData);
  2388. if (layer === 'c') {
  2389. this.onSecondaryControl_(data);
  2390. }
  2391. else if (layer === 'd') {
  2392. // got a data message, but we're still second connection. Need to buffer it up
  2393. this.pendingDataMessages.push(data);
  2394. }
  2395. else {
  2396. throw new Error('Unknown protocol layer: ' + layer);
  2397. }
  2398. }
  2399. upgradeIfSecondaryHealthy_() {
  2400. if (this.secondaryResponsesRequired_ <= 0) {
  2401. this.log_('Secondary connection is healthy.');
  2402. this.isHealthy_ = true;
  2403. this.secondaryConn_.markConnectionHealthy();
  2404. this.proceedWithUpgrade_();
  2405. }
  2406. else {
  2407. // Send a ping to make sure the connection is healthy.
  2408. this.log_('sending ping on secondary.');
  2409. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2410. }
  2411. }
  2412. proceedWithUpgrade_() {
  2413. // tell this connection to consider itself open
  2414. this.secondaryConn_.start();
  2415. // send ack
  2416. this.log_('sending client ack on secondary');
  2417. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2418. // send end packet on primary transport, switch to sending on this one
  2419. // can receive on this one, buffer responses until end received on primary transport
  2420. this.log_('Ending transmission on primary');
  2421. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2422. this.tx_ = this.secondaryConn_;
  2423. this.tryCleanupConnection();
  2424. }
  2425. onPrimaryMessageReceived_(parsedData) {
  2426. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2427. const layer = requireKey('t', parsedData);
  2428. const data = requireKey('d', parsedData);
  2429. if (layer === 'c') {
  2430. this.onControl_(data);
  2431. }
  2432. else if (layer === 'd') {
  2433. this.onDataMessage_(data);
  2434. }
  2435. }
  2436. onDataMessage_(message) {
  2437. this.onPrimaryResponse_();
  2438. // We don't do anything with data messages, just kick them up a level
  2439. this.onMessage_(message);
  2440. }
  2441. onPrimaryResponse_() {
  2442. if (!this.isHealthy_) {
  2443. this.primaryResponsesRequired_--;
  2444. if (this.primaryResponsesRequired_ <= 0) {
  2445. this.log_('Primary connection is healthy.');
  2446. this.isHealthy_ = true;
  2447. this.conn_.markConnectionHealthy();
  2448. }
  2449. }
  2450. }
  2451. onControl_(controlData) {
  2452. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2453. if (MESSAGE_DATA in controlData) {
  2454. const payload = controlData[MESSAGE_DATA];
  2455. if (cmd === SERVER_HELLO) {
  2456. const handshakePayload = Object.assign({}, payload);
  2457. if (this.repoInfo_.isUsingEmulator) {
  2458. // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.
  2459. handshakePayload.h = this.repoInfo_.host;
  2460. }
  2461. this.onHandshake_(handshakePayload);
  2462. }
  2463. else if (cmd === END_TRANSMISSION) {
  2464. this.log_('recvd end transmission on primary');
  2465. this.rx_ = this.secondaryConn_;
  2466. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2467. this.onDataMessage_(this.pendingDataMessages[i]);
  2468. }
  2469. this.pendingDataMessages = [];
  2470. this.tryCleanupConnection();
  2471. }
  2472. else if (cmd === CONTROL_SHUTDOWN) {
  2473. // This was previously the 'onKill' callback passed to the lower-level connection
  2474. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2475. this.onConnectionShutdown_(payload);
  2476. }
  2477. else if (cmd === CONTROL_RESET) {
  2478. // payload in this case is the host we should contact
  2479. this.onReset_(payload);
  2480. }
  2481. else if (cmd === CONTROL_ERROR) {
  2482. error('Server Error: ' + payload);
  2483. }
  2484. else if (cmd === CONTROL_PONG) {
  2485. this.log_('got pong on primary.');
  2486. this.onPrimaryResponse_();
  2487. this.sendPingOnPrimaryIfNecessary_();
  2488. }
  2489. else {
  2490. error('Unknown control packet command: ' + cmd);
  2491. }
  2492. }
  2493. }
  2494. /**
  2495. * @param handshake - The handshake data returned from the server
  2496. */
  2497. onHandshake_(handshake) {
  2498. const timestamp = handshake.ts;
  2499. const version = handshake.v;
  2500. const host = handshake.h;
  2501. this.sessionId = handshake.s;
  2502. this.repoInfo_.host = host;
  2503. // if we've already closed the connection, then don't bother trying to progress further
  2504. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2505. this.conn_.start();
  2506. this.onConnectionEstablished_(this.conn_, timestamp);
  2507. if (PROTOCOL_VERSION !== version) {
  2508. warn('Protocol version mismatch detected');
  2509. }
  2510. // TODO: do we want to upgrade? when? maybe a delay?
  2511. this.tryStartUpgrade_();
  2512. }
  2513. }
  2514. tryStartUpgrade_() {
  2515. const conn = this.transportManager_.upgradeTransport();
  2516. if (conn) {
  2517. this.startUpgrade_(conn);
  2518. }
  2519. }
  2520. startUpgrade_(conn) {
  2521. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2522. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2523. // can consider the transport healthy.
  2524. this.secondaryResponsesRequired_ =
  2525. conn['responsesRequiredToBeHealthy'] || 0;
  2526. const onMessage = this.connReceiver_(this.secondaryConn_);
  2527. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2528. this.secondaryConn_.open(onMessage, onDisconnect);
  2529. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2530. setTimeoutNonBlocking(() => {
  2531. if (this.secondaryConn_) {
  2532. this.log_('Timed out trying to upgrade.');
  2533. this.secondaryConn_.close();
  2534. }
  2535. }, Math.floor(UPGRADE_TIMEOUT));
  2536. }
  2537. onReset_(host) {
  2538. this.log_('Reset packet received. New host: ' + host);
  2539. this.repoInfo_.host = host;
  2540. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2541. // We don't currently support resets after the connection has already been established
  2542. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2543. this.close();
  2544. }
  2545. else {
  2546. // Close whatever connections we have open and start again.
  2547. this.closeConnections_();
  2548. this.start_();
  2549. }
  2550. }
  2551. onConnectionEstablished_(conn, timestamp) {
  2552. this.log_('Realtime connection established.');
  2553. this.conn_ = conn;
  2554. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2555. if (this.onReady_) {
  2556. this.onReady_(timestamp, this.sessionId);
  2557. this.onReady_ = null;
  2558. }
  2559. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2560. // send some pings.
  2561. if (this.primaryResponsesRequired_ === 0) {
  2562. this.log_('Primary connection is healthy.');
  2563. this.isHealthy_ = true;
  2564. }
  2565. else {
  2566. setTimeoutNonBlocking(() => {
  2567. this.sendPingOnPrimaryIfNecessary_();
  2568. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2569. }
  2570. }
  2571. sendPingOnPrimaryIfNecessary_() {
  2572. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2573. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2574. this.log_('sending ping on primary.');
  2575. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2576. }
  2577. }
  2578. onSecondaryConnectionLost_() {
  2579. const conn = this.secondaryConn_;
  2580. this.secondaryConn_ = null;
  2581. if (this.tx_ === conn || this.rx_ === conn) {
  2582. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2583. this.close();
  2584. }
  2585. }
  2586. /**
  2587. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2588. * we should flush the host cache
  2589. */
  2590. onConnectionLost_(everConnected) {
  2591. this.conn_ = null;
  2592. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2593. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2594. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2595. this.log_('Realtime connection failed.');
  2596. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2597. if (this.repoInfo_.isCacheableHost()) {
  2598. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2599. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2600. this.repoInfo_.internalHost = this.repoInfo_.host;
  2601. }
  2602. }
  2603. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2604. this.log_('Realtime connection lost.');
  2605. }
  2606. this.close();
  2607. }
  2608. onConnectionShutdown_(reason) {
  2609. this.log_('Connection shutdown command received. Shutting down...');
  2610. if (this.onKill_) {
  2611. this.onKill_(reason);
  2612. this.onKill_ = null;
  2613. }
  2614. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2615. // so clear the callback.
  2616. this.onDisconnect_ = null;
  2617. this.close();
  2618. }
  2619. sendData_(data) {
  2620. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2621. throw 'Connection is not connected';
  2622. }
  2623. else {
  2624. this.tx_.send(data);
  2625. }
  2626. }
  2627. /**
  2628. * Cleans up this connection, calling the appropriate callbacks
  2629. */
  2630. close() {
  2631. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2632. this.log_('Closing realtime connection.');
  2633. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2634. this.closeConnections_();
  2635. if (this.onDisconnect_) {
  2636. this.onDisconnect_();
  2637. this.onDisconnect_ = null;
  2638. }
  2639. }
  2640. }
  2641. closeConnections_() {
  2642. this.log_('Shutting down all connections');
  2643. if (this.conn_) {
  2644. this.conn_.close();
  2645. this.conn_ = null;
  2646. }
  2647. if (this.secondaryConn_) {
  2648. this.secondaryConn_.close();
  2649. this.secondaryConn_ = null;
  2650. }
  2651. if (this.healthyTimeout_) {
  2652. clearTimeout(this.healthyTimeout_);
  2653. this.healthyTimeout_ = null;
  2654. }
  2655. }
  2656. }
  2657. /**
  2658. * @license
  2659. * Copyright 2017 Google LLC
  2660. *
  2661. * Licensed under the Apache License, Version 2.0 (the "License");
  2662. * you may not use this file except in compliance with the License.
  2663. * You may obtain a copy of the License at
  2664. *
  2665. * http://www.apache.org/licenses/LICENSE-2.0
  2666. *
  2667. * Unless required by applicable law or agreed to in writing, software
  2668. * distributed under the License is distributed on an "AS IS" BASIS,
  2669. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2670. * See the License for the specific language governing permissions and
  2671. * limitations under the License.
  2672. */
  2673. /**
  2674. * Interface defining the set of actions that can be performed against the Firebase server
  2675. * (basically corresponds to our wire protocol).
  2676. *
  2677. * @interface
  2678. */
  2679. class ServerActions {
  2680. put(pathString, data, onComplete, hash) { }
  2681. merge(pathString, data, onComplete, hash) { }
  2682. /**
  2683. * Refreshes the auth token for the current connection.
  2684. * @param token - The authentication token
  2685. */
  2686. refreshAuthToken(token) { }
  2687. /**
  2688. * Refreshes the app check token for the current connection.
  2689. * @param token The app check token
  2690. */
  2691. refreshAppCheckToken(token) { }
  2692. onDisconnectPut(pathString, data, onComplete) { }
  2693. onDisconnectMerge(pathString, data, onComplete) { }
  2694. onDisconnectCancel(pathString, onComplete) { }
  2695. reportStats(stats) { }
  2696. }
  2697. /**
  2698. * @license
  2699. * Copyright 2017 Google LLC
  2700. *
  2701. * Licensed under the Apache License, Version 2.0 (the "License");
  2702. * you may not use this file except in compliance with the License.
  2703. * You may obtain a copy of the License at
  2704. *
  2705. * http://www.apache.org/licenses/LICENSE-2.0
  2706. *
  2707. * Unless required by applicable law or agreed to in writing, software
  2708. * distributed under the License is distributed on an "AS IS" BASIS,
  2709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2710. * See the License for the specific language governing permissions and
  2711. * limitations under the License.
  2712. */
  2713. /**
  2714. * Base class to be used if you want to emit events. Call the constructor with
  2715. * the set of allowed event names.
  2716. */
  2717. class EventEmitter {
  2718. constructor(allowedEvents_) {
  2719. this.allowedEvents_ = allowedEvents_;
  2720. this.listeners_ = {};
  2721. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2722. }
  2723. /**
  2724. * To be called by derived classes to trigger events.
  2725. */
  2726. trigger(eventType, ...varArgs) {
  2727. if (Array.isArray(this.listeners_[eventType])) {
  2728. // Clone the list, since callbacks could add/remove listeners.
  2729. const listeners = [...this.listeners_[eventType]];
  2730. for (let i = 0; i < listeners.length; i++) {
  2731. listeners[i].callback.apply(listeners[i].context, varArgs);
  2732. }
  2733. }
  2734. }
  2735. on(eventType, callback, context) {
  2736. this.validateEventType_(eventType);
  2737. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2738. this.listeners_[eventType].push({ callback, context });
  2739. const eventData = this.getInitialEvent(eventType);
  2740. if (eventData) {
  2741. callback.apply(context, eventData);
  2742. }
  2743. }
  2744. off(eventType, callback, context) {
  2745. this.validateEventType_(eventType);
  2746. const listeners = this.listeners_[eventType] || [];
  2747. for (let i = 0; i < listeners.length; i++) {
  2748. if (listeners[i].callback === callback &&
  2749. (!context || context === listeners[i].context)) {
  2750. listeners.splice(i, 1);
  2751. return;
  2752. }
  2753. }
  2754. }
  2755. validateEventType_(eventType) {
  2756. assert(this.allowedEvents_.find(et => {
  2757. return et === eventType;
  2758. }), 'Unknown event: ' + eventType);
  2759. }
  2760. }
  2761. /**
  2762. * @license
  2763. * Copyright 2017 Google LLC
  2764. *
  2765. * Licensed under the Apache License, Version 2.0 (the "License");
  2766. * you may not use this file except in compliance with the License.
  2767. * You may obtain a copy of the License at
  2768. *
  2769. * http://www.apache.org/licenses/LICENSE-2.0
  2770. *
  2771. * Unless required by applicable law or agreed to in writing, software
  2772. * distributed under the License is distributed on an "AS IS" BASIS,
  2773. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2774. * See the License for the specific language governing permissions and
  2775. * limitations under the License.
  2776. */
  2777. /**
  2778. * Monitors online state (as reported by window.online/offline events).
  2779. *
  2780. * The expectation is that this could have many false positives (thinks we are online
  2781. * when we're not), but no false negatives. So we can safely use it to determine when
  2782. * we definitely cannot reach the internet.
  2783. */
  2784. class OnlineMonitor extends EventEmitter {
  2785. constructor() {
  2786. super(['online']);
  2787. this.online_ = true;
  2788. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2789. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2790. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2791. // for Cordova.
  2792. if (typeof window !== 'undefined' &&
  2793. typeof window.addEventListener !== 'undefined' &&
  2794. !isMobileCordova()) {
  2795. window.addEventListener('online', () => {
  2796. if (!this.online_) {
  2797. this.online_ = true;
  2798. this.trigger('online', true);
  2799. }
  2800. }, false);
  2801. window.addEventListener('offline', () => {
  2802. if (this.online_) {
  2803. this.online_ = false;
  2804. this.trigger('online', false);
  2805. }
  2806. }, false);
  2807. }
  2808. }
  2809. static getInstance() {
  2810. return new OnlineMonitor();
  2811. }
  2812. getInitialEvent(eventType) {
  2813. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2814. return [this.online_];
  2815. }
  2816. currentlyOnline() {
  2817. return this.online_;
  2818. }
  2819. }
  2820. /**
  2821. * @license
  2822. * Copyright 2017 Google LLC
  2823. *
  2824. * Licensed under the Apache License, Version 2.0 (the "License");
  2825. * you may not use this file except in compliance with the License.
  2826. * You may obtain a copy of the License at
  2827. *
  2828. * http://www.apache.org/licenses/LICENSE-2.0
  2829. *
  2830. * Unless required by applicable law or agreed to in writing, software
  2831. * distributed under the License is distributed on an "AS IS" BASIS,
  2832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2833. * See the License for the specific language governing permissions and
  2834. * limitations under the License.
  2835. */
  2836. /** Maximum key depth. */
  2837. const MAX_PATH_DEPTH = 32;
  2838. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2839. const MAX_PATH_LENGTH_BYTES = 768;
  2840. /**
  2841. * An immutable object representing a parsed path. It's immutable so that you
  2842. * can pass them around to other functions without worrying about them changing
  2843. * it.
  2844. */
  2845. class Path {
  2846. /**
  2847. * @param pathOrString - Path string to parse, or another path, or the raw
  2848. * tokens array
  2849. */
  2850. constructor(pathOrString, pieceNum) {
  2851. if (pieceNum === void 0) {
  2852. this.pieces_ = pathOrString.split('/');
  2853. // Remove empty pieces.
  2854. let copyTo = 0;
  2855. for (let i = 0; i < this.pieces_.length; i++) {
  2856. if (this.pieces_[i].length > 0) {
  2857. this.pieces_[copyTo] = this.pieces_[i];
  2858. copyTo++;
  2859. }
  2860. }
  2861. this.pieces_.length = copyTo;
  2862. this.pieceNum_ = 0;
  2863. }
  2864. else {
  2865. this.pieces_ = pathOrString;
  2866. this.pieceNum_ = pieceNum;
  2867. }
  2868. }
  2869. toString() {
  2870. let pathString = '';
  2871. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2872. if (this.pieces_[i] !== '') {
  2873. pathString += '/' + this.pieces_[i];
  2874. }
  2875. }
  2876. return pathString || '/';
  2877. }
  2878. }
  2879. function newEmptyPath() {
  2880. return new Path('');
  2881. }
  2882. function pathGetFront(path) {
  2883. if (path.pieceNum_ >= path.pieces_.length) {
  2884. return null;
  2885. }
  2886. return path.pieces_[path.pieceNum_];
  2887. }
  2888. /**
  2889. * @returns The number of segments in this path
  2890. */
  2891. function pathGetLength(path) {
  2892. return path.pieces_.length - path.pieceNum_;
  2893. }
  2894. function pathPopFront(path) {
  2895. let pieceNum = path.pieceNum_;
  2896. if (pieceNum < path.pieces_.length) {
  2897. pieceNum++;
  2898. }
  2899. return new Path(path.pieces_, pieceNum);
  2900. }
  2901. function pathGetBack(path) {
  2902. if (path.pieceNum_ < path.pieces_.length) {
  2903. return path.pieces_[path.pieces_.length - 1];
  2904. }
  2905. return null;
  2906. }
  2907. function pathToUrlEncodedString(path) {
  2908. let pathString = '';
  2909. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2910. if (path.pieces_[i] !== '') {
  2911. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2912. }
  2913. }
  2914. return pathString || '/';
  2915. }
  2916. /**
  2917. * Shallow copy of the parts of the path.
  2918. *
  2919. */
  2920. function pathSlice(path, begin = 0) {
  2921. return path.pieces_.slice(path.pieceNum_ + begin);
  2922. }
  2923. function pathParent(path) {
  2924. if (path.pieceNum_ >= path.pieces_.length) {
  2925. return null;
  2926. }
  2927. const pieces = [];
  2928. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2929. pieces.push(path.pieces_[i]);
  2930. }
  2931. return new Path(pieces, 0);
  2932. }
  2933. function pathChild(path, childPathObj) {
  2934. const pieces = [];
  2935. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2936. pieces.push(path.pieces_[i]);
  2937. }
  2938. if (childPathObj instanceof Path) {
  2939. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2940. pieces.push(childPathObj.pieces_[i]);
  2941. }
  2942. }
  2943. else {
  2944. const childPieces = childPathObj.split('/');
  2945. for (let i = 0; i < childPieces.length; i++) {
  2946. if (childPieces[i].length > 0) {
  2947. pieces.push(childPieces[i]);
  2948. }
  2949. }
  2950. }
  2951. return new Path(pieces, 0);
  2952. }
  2953. /**
  2954. * @returns True if there are no segments in this path
  2955. */
  2956. function pathIsEmpty(path) {
  2957. return path.pieceNum_ >= path.pieces_.length;
  2958. }
  2959. /**
  2960. * @returns The path from outerPath to innerPath
  2961. */
  2962. function newRelativePath(outerPath, innerPath) {
  2963. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2964. if (outer === null) {
  2965. return innerPath;
  2966. }
  2967. else if (outer === inner) {
  2968. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2969. }
  2970. else {
  2971. throw new Error('INTERNAL ERROR: innerPath (' +
  2972. innerPath +
  2973. ') is not within ' +
  2974. 'outerPath (' +
  2975. outerPath +
  2976. ')');
  2977. }
  2978. }
  2979. /**
  2980. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2981. */
  2982. function pathCompare(left, right) {
  2983. const leftKeys = pathSlice(left, 0);
  2984. const rightKeys = pathSlice(right, 0);
  2985. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2986. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2987. if (cmp !== 0) {
  2988. return cmp;
  2989. }
  2990. }
  2991. if (leftKeys.length === rightKeys.length) {
  2992. return 0;
  2993. }
  2994. return leftKeys.length < rightKeys.length ? -1 : 1;
  2995. }
  2996. /**
  2997. * @returns true if paths are the same.
  2998. */
  2999. function pathEquals(path, other) {
  3000. if (pathGetLength(path) !== pathGetLength(other)) {
  3001. return false;
  3002. }
  3003. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3004. if (path.pieces_[i] !== other.pieces_[j]) {
  3005. return false;
  3006. }
  3007. }
  3008. return true;
  3009. }
  3010. /**
  3011. * @returns True if this path is a parent of (or the same as) other
  3012. */
  3013. function pathContains(path, other) {
  3014. let i = path.pieceNum_;
  3015. let j = other.pieceNum_;
  3016. if (pathGetLength(path) > pathGetLength(other)) {
  3017. return false;
  3018. }
  3019. while (i < path.pieces_.length) {
  3020. if (path.pieces_[i] !== other.pieces_[j]) {
  3021. return false;
  3022. }
  3023. ++i;
  3024. ++j;
  3025. }
  3026. return true;
  3027. }
  3028. /**
  3029. * Dynamic (mutable) path used to count path lengths.
  3030. *
  3031. * This class is used to efficiently check paths for valid
  3032. * length (in UTF8 bytes) and depth (used in path validation).
  3033. *
  3034. * Throws Error exception if path is ever invalid.
  3035. *
  3036. * The definition of a path always begins with '/'.
  3037. */
  3038. class ValidationPath {
  3039. /**
  3040. * @param path - Initial Path.
  3041. * @param errorPrefix_ - Prefix for any error messages.
  3042. */
  3043. constructor(path, errorPrefix_) {
  3044. this.errorPrefix_ = errorPrefix_;
  3045. this.parts_ = pathSlice(path, 0);
  3046. /** Initialize to number of '/' chars needed in path. */
  3047. this.byteLength_ = Math.max(1, this.parts_.length);
  3048. for (let i = 0; i < this.parts_.length; i++) {
  3049. this.byteLength_ += stringLength(this.parts_[i]);
  3050. }
  3051. validationPathCheckValid(this);
  3052. }
  3053. }
  3054. function validationPathPush(validationPath, child) {
  3055. // Count the needed '/'
  3056. if (validationPath.parts_.length > 0) {
  3057. validationPath.byteLength_ += 1;
  3058. }
  3059. validationPath.parts_.push(child);
  3060. validationPath.byteLength_ += stringLength(child);
  3061. validationPathCheckValid(validationPath);
  3062. }
  3063. function validationPathPop(validationPath) {
  3064. const last = validationPath.parts_.pop();
  3065. validationPath.byteLength_ -= stringLength(last);
  3066. // Un-count the previous '/'
  3067. if (validationPath.parts_.length > 0) {
  3068. validationPath.byteLength_ -= 1;
  3069. }
  3070. }
  3071. function validationPathCheckValid(validationPath) {
  3072. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3073. throw new Error(validationPath.errorPrefix_ +
  3074. 'has a key path longer than ' +
  3075. MAX_PATH_LENGTH_BYTES +
  3076. ' bytes (' +
  3077. validationPath.byteLength_ +
  3078. ').');
  3079. }
  3080. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3081. throw new Error(validationPath.errorPrefix_ +
  3082. 'path specified exceeds the maximum depth that can be written (' +
  3083. MAX_PATH_DEPTH +
  3084. ') or object contains a cycle ' +
  3085. validationPathToErrorString(validationPath));
  3086. }
  3087. }
  3088. /**
  3089. * String for use in error messages - uses '.' notation for path.
  3090. */
  3091. function validationPathToErrorString(validationPath) {
  3092. if (validationPath.parts_.length === 0) {
  3093. return '';
  3094. }
  3095. return "in property '" + validationPath.parts_.join('.') + "'";
  3096. }
  3097. /**
  3098. * @license
  3099. * Copyright 2017 Google LLC
  3100. *
  3101. * Licensed under the Apache License, Version 2.0 (the "License");
  3102. * you may not use this file except in compliance with the License.
  3103. * You may obtain a copy of the License at
  3104. *
  3105. * http://www.apache.org/licenses/LICENSE-2.0
  3106. *
  3107. * Unless required by applicable law or agreed to in writing, software
  3108. * distributed under the License is distributed on an "AS IS" BASIS,
  3109. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3110. * See the License for the specific language governing permissions and
  3111. * limitations under the License.
  3112. */
  3113. class VisibilityMonitor extends EventEmitter {
  3114. constructor() {
  3115. super(['visible']);
  3116. let hidden;
  3117. let visibilityChange;
  3118. if (typeof document !== 'undefined' &&
  3119. typeof document.addEventListener !== 'undefined') {
  3120. if (typeof document['hidden'] !== 'undefined') {
  3121. // Opera 12.10 and Firefox 18 and later support
  3122. visibilityChange = 'visibilitychange';
  3123. hidden = 'hidden';
  3124. }
  3125. else if (typeof document['mozHidden'] !== 'undefined') {
  3126. visibilityChange = 'mozvisibilitychange';
  3127. hidden = 'mozHidden';
  3128. }
  3129. else if (typeof document['msHidden'] !== 'undefined') {
  3130. visibilityChange = 'msvisibilitychange';
  3131. hidden = 'msHidden';
  3132. }
  3133. else if (typeof document['webkitHidden'] !== 'undefined') {
  3134. visibilityChange = 'webkitvisibilitychange';
  3135. hidden = 'webkitHidden';
  3136. }
  3137. }
  3138. // Initially, we always assume we are visible. This ensures that in browsers
  3139. // without page visibility support or in cases where we are never visible
  3140. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3141. // reconnects
  3142. this.visible_ = true;
  3143. if (visibilityChange) {
  3144. document.addEventListener(visibilityChange, () => {
  3145. const visible = !document[hidden];
  3146. if (visible !== this.visible_) {
  3147. this.visible_ = visible;
  3148. this.trigger('visible', visible);
  3149. }
  3150. }, false);
  3151. }
  3152. }
  3153. static getInstance() {
  3154. return new VisibilityMonitor();
  3155. }
  3156. getInitialEvent(eventType) {
  3157. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3158. return [this.visible_];
  3159. }
  3160. }
  3161. /**
  3162. * @license
  3163. * Copyright 2017 Google LLC
  3164. *
  3165. * Licensed under the Apache License, Version 2.0 (the "License");
  3166. * you may not use this file except in compliance with the License.
  3167. * You may obtain a copy of the License at
  3168. *
  3169. * http://www.apache.org/licenses/LICENSE-2.0
  3170. *
  3171. * Unless required by applicable law or agreed to in writing, software
  3172. * distributed under the License is distributed on an "AS IS" BASIS,
  3173. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3174. * See the License for the specific language governing permissions and
  3175. * limitations under the License.
  3176. */
  3177. const RECONNECT_MIN_DELAY = 1000;
  3178. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3179. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3180. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3181. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3182. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3183. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3184. const INVALID_TOKEN_THRESHOLD = 3;
  3185. /**
  3186. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3187. *
  3188. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3189. * in quotes to make sure the closure compiler does not minify them.
  3190. */
  3191. class PersistentConnection extends ServerActions {
  3192. /**
  3193. * @param repoInfo_ - Data about the namespace we are connecting to
  3194. * @param applicationId_ - The Firebase App ID for this project
  3195. * @param onDataUpdate_ - A callback for new data from the server
  3196. */
  3197. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3198. super();
  3199. this.repoInfo_ = repoInfo_;
  3200. this.applicationId_ = applicationId_;
  3201. this.onDataUpdate_ = onDataUpdate_;
  3202. this.onConnectStatus_ = onConnectStatus_;
  3203. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3204. this.authTokenProvider_ = authTokenProvider_;
  3205. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3206. this.authOverride_ = authOverride_;
  3207. // Used for diagnostic logging.
  3208. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3209. this.log_ = logWrapper('p:' + this.id + ':');
  3210. this.interruptReasons_ = {};
  3211. this.listens = new Map();
  3212. this.outstandingPuts_ = [];
  3213. this.outstandingGets_ = [];
  3214. this.outstandingPutCount_ = 0;
  3215. this.outstandingGetCount_ = 0;
  3216. this.onDisconnectRequestQueue_ = [];
  3217. this.connected_ = false;
  3218. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3219. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3220. this.securityDebugCallback_ = null;
  3221. this.lastSessionId = null;
  3222. this.establishConnectionTimer_ = null;
  3223. this.visible_ = false;
  3224. // Before we get connected, we keep a queue of pending messages to send.
  3225. this.requestCBHash_ = {};
  3226. this.requestNumber_ = 0;
  3227. this.realtime_ = null;
  3228. this.authToken_ = null;
  3229. this.appCheckToken_ = null;
  3230. this.forceTokenRefresh_ = false;
  3231. this.invalidAuthTokenCount_ = 0;
  3232. this.invalidAppCheckTokenCount_ = 0;
  3233. this.firstConnection_ = true;
  3234. this.lastConnectionAttemptTime_ = null;
  3235. this.lastConnectionEstablishedTime_ = null;
  3236. if (authOverride_ && !isNodeSdk()) {
  3237. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3238. }
  3239. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3240. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3241. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3242. }
  3243. }
  3244. sendRequest(action, body, onResponse) {
  3245. const curReqNum = ++this.requestNumber_;
  3246. const msg = { r: curReqNum, a: action, b: body };
  3247. this.log_(stringify(msg));
  3248. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3249. this.realtime_.sendRequest(msg);
  3250. if (onResponse) {
  3251. this.requestCBHash_[curReqNum] = onResponse;
  3252. }
  3253. }
  3254. get(query) {
  3255. this.initConnection_();
  3256. const deferred = new Deferred();
  3257. const request = {
  3258. p: query._path.toString(),
  3259. q: query._queryObject
  3260. };
  3261. const outstandingGet = {
  3262. action: 'g',
  3263. request,
  3264. onComplete: (message) => {
  3265. const payload = message['d'];
  3266. if (message['s'] === 'ok') {
  3267. deferred.resolve(payload);
  3268. }
  3269. else {
  3270. deferred.reject(payload);
  3271. }
  3272. }
  3273. };
  3274. this.outstandingGets_.push(outstandingGet);
  3275. this.outstandingGetCount_++;
  3276. const index = this.outstandingGets_.length - 1;
  3277. if (this.connected_) {
  3278. this.sendGet_(index);
  3279. }
  3280. return deferred.promise;
  3281. }
  3282. listen(query, currentHashFn, tag, onComplete) {
  3283. this.initConnection_();
  3284. const queryId = query._queryIdentifier;
  3285. const pathString = query._path.toString();
  3286. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3287. if (!this.listens.has(pathString)) {
  3288. this.listens.set(pathString, new Map());
  3289. }
  3290. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3291. assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3292. const listenSpec = {
  3293. onComplete,
  3294. hashFn: currentHashFn,
  3295. query,
  3296. tag
  3297. };
  3298. this.listens.get(pathString).set(queryId, listenSpec);
  3299. if (this.connected_) {
  3300. this.sendListen_(listenSpec);
  3301. }
  3302. }
  3303. sendGet_(index) {
  3304. const get = this.outstandingGets_[index];
  3305. this.sendRequest('g', get.request, (message) => {
  3306. delete this.outstandingGets_[index];
  3307. this.outstandingGetCount_--;
  3308. if (this.outstandingGetCount_ === 0) {
  3309. this.outstandingGets_ = [];
  3310. }
  3311. if (get.onComplete) {
  3312. get.onComplete(message);
  3313. }
  3314. });
  3315. }
  3316. sendListen_(listenSpec) {
  3317. const query = listenSpec.query;
  3318. const pathString = query._path.toString();
  3319. const queryId = query._queryIdentifier;
  3320. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3321. const req = { /*path*/ p: pathString };
  3322. const action = 'q';
  3323. // Only bother to send query if it's non-default.
  3324. if (listenSpec.tag) {
  3325. req['q'] = query._queryObject;
  3326. req['t'] = listenSpec.tag;
  3327. }
  3328. req[ /*hash*/'h'] = listenSpec.hashFn();
  3329. this.sendRequest(action, req, (message) => {
  3330. const payload = message[ /*data*/'d'];
  3331. const status = message[ /*status*/'s'];
  3332. // print warnings in any case...
  3333. PersistentConnection.warnOnListenWarnings_(payload, query);
  3334. const currentListenSpec = this.listens.get(pathString) &&
  3335. this.listens.get(pathString).get(queryId);
  3336. // only trigger actions if the listen hasn't been removed and readded
  3337. if (currentListenSpec === listenSpec) {
  3338. this.log_('listen response', message);
  3339. if (status !== 'ok') {
  3340. this.removeListen_(pathString, queryId);
  3341. }
  3342. if (listenSpec.onComplete) {
  3343. listenSpec.onComplete(status, payload);
  3344. }
  3345. }
  3346. });
  3347. }
  3348. static warnOnListenWarnings_(payload, query) {
  3349. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3350. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3351. const warnings = safeGet(payload, 'w');
  3352. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3353. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3354. const indexPath = query._path.toString();
  3355. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3356. `filtered on the client. Consider adding ${indexSpec} at ` +
  3357. `${indexPath} to your security rules for better performance.`);
  3358. }
  3359. }
  3360. }
  3361. refreshAuthToken(token) {
  3362. this.authToken_ = token;
  3363. this.log_('Auth token refreshed');
  3364. if (this.authToken_) {
  3365. this.tryAuth();
  3366. }
  3367. else {
  3368. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3369. //the credential so we dont become authenticated next time we connect.
  3370. if (this.connected_) {
  3371. this.sendRequest('unauth', {}, () => { });
  3372. }
  3373. }
  3374. this.reduceReconnectDelayIfAdminCredential_(token);
  3375. }
  3376. reduceReconnectDelayIfAdminCredential_(credential) {
  3377. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3378. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3379. const isFirebaseSecret = credential && credential.length === 40;
  3380. if (isFirebaseSecret || isAdmin(credential)) {
  3381. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3382. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3383. }
  3384. }
  3385. refreshAppCheckToken(token) {
  3386. this.appCheckToken_ = token;
  3387. this.log_('App check token refreshed');
  3388. if (this.appCheckToken_) {
  3389. this.tryAppCheck();
  3390. }
  3391. else {
  3392. //If we're connected we want to let the server know to unauthenticate us.
  3393. //If we're not connected, simply delete the credential so we dont become
  3394. // authenticated next time we connect.
  3395. if (this.connected_) {
  3396. this.sendRequest('unappeck', {}, () => { });
  3397. }
  3398. }
  3399. }
  3400. /**
  3401. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3402. * a auth revoked (the connection is closed).
  3403. */
  3404. tryAuth() {
  3405. if (this.connected_ && this.authToken_) {
  3406. const token = this.authToken_;
  3407. const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
  3408. const requestData = { cred: token };
  3409. if (this.authOverride_ === null) {
  3410. requestData['noauth'] = true;
  3411. }
  3412. else if (typeof this.authOverride_ === 'object') {
  3413. requestData['authvar'] = this.authOverride_;
  3414. }
  3415. this.sendRequest(authMethod, requestData, (res) => {
  3416. const status = res[ /*status*/'s'];
  3417. const data = res[ /*data*/'d'] || 'error';
  3418. if (this.authToken_ === token) {
  3419. if (status === 'ok') {
  3420. this.invalidAuthTokenCount_ = 0;
  3421. }
  3422. else {
  3423. // Triggers reconnect and force refresh for auth token
  3424. this.onAuthRevoked_(status, data);
  3425. }
  3426. }
  3427. });
  3428. }
  3429. }
  3430. /**
  3431. * Attempts to authenticate with the given token. If the authentication
  3432. * attempt fails, it's triggered like the token was revoked (the connection is
  3433. * closed).
  3434. */
  3435. tryAppCheck() {
  3436. if (this.connected_ && this.appCheckToken_) {
  3437. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3438. const status = res[ /*status*/'s'];
  3439. const data = res[ /*data*/'d'] || 'error';
  3440. if (status === 'ok') {
  3441. this.invalidAppCheckTokenCount_ = 0;
  3442. }
  3443. else {
  3444. this.onAppCheckRevoked_(status, data);
  3445. }
  3446. });
  3447. }
  3448. }
  3449. /**
  3450. * @inheritDoc
  3451. */
  3452. unlisten(query, tag) {
  3453. const pathString = query._path.toString();
  3454. const queryId = query._queryIdentifier;
  3455. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3456. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3457. const listen = this.removeListen_(pathString, queryId);
  3458. if (listen && this.connected_) {
  3459. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3460. }
  3461. }
  3462. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3463. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3464. const req = { /*path*/ p: pathString };
  3465. const action = 'n';
  3466. // Only bother sending queryId if it's non-default.
  3467. if (tag) {
  3468. req['q'] = queryObj;
  3469. req['t'] = tag;
  3470. }
  3471. this.sendRequest(action, req);
  3472. }
  3473. onDisconnectPut(pathString, data, onComplete) {
  3474. this.initConnection_();
  3475. if (this.connected_) {
  3476. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3477. }
  3478. else {
  3479. this.onDisconnectRequestQueue_.push({
  3480. pathString,
  3481. action: 'o',
  3482. data,
  3483. onComplete
  3484. });
  3485. }
  3486. }
  3487. onDisconnectMerge(pathString, data, onComplete) {
  3488. this.initConnection_();
  3489. if (this.connected_) {
  3490. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3491. }
  3492. else {
  3493. this.onDisconnectRequestQueue_.push({
  3494. pathString,
  3495. action: 'om',
  3496. data,
  3497. onComplete
  3498. });
  3499. }
  3500. }
  3501. onDisconnectCancel(pathString, onComplete) {
  3502. this.initConnection_();
  3503. if (this.connected_) {
  3504. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3505. }
  3506. else {
  3507. this.onDisconnectRequestQueue_.push({
  3508. pathString,
  3509. action: 'oc',
  3510. data: null,
  3511. onComplete
  3512. });
  3513. }
  3514. }
  3515. sendOnDisconnect_(action, pathString, data, onComplete) {
  3516. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3517. this.log_('onDisconnect ' + action, request);
  3518. this.sendRequest(action, request, (response) => {
  3519. if (onComplete) {
  3520. setTimeout(() => {
  3521. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3522. }, Math.floor(0));
  3523. }
  3524. });
  3525. }
  3526. put(pathString, data, onComplete, hash) {
  3527. this.putInternal('p', pathString, data, onComplete, hash);
  3528. }
  3529. merge(pathString, data, onComplete, hash) {
  3530. this.putInternal('m', pathString, data, onComplete, hash);
  3531. }
  3532. putInternal(action, pathString, data, onComplete, hash) {
  3533. this.initConnection_();
  3534. const request = {
  3535. /*path*/ p: pathString,
  3536. /*data*/ d: data
  3537. };
  3538. if (hash !== undefined) {
  3539. request[ /*hash*/'h'] = hash;
  3540. }
  3541. // TODO: Only keep track of the most recent put for a given path?
  3542. this.outstandingPuts_.push({
  3543. action,
  3544. request,
  3545. onComplete
  3546. });
  3547. this.outstandingPutCount_++;
  3548. const index = this.outstandingPuts_.length - 1;
  3549. if (this.connected_) {
  3550. this.sendPut_(index);
  3551. }
  3552. else {
  3553. this.log_('Buffering put: ' + pathString);
  3554. }
  3555. }
  3556. sendPut_(index) {
  3557. const action = this.outstandingPuts_[index].action;
  3558. const request = this.outstandingPuts_[index].request;
  3559. const onComplete = this.outstandingPuts_[index].onComplete;
  3560. this.outstandingPuts_[index].queued = this.connected_;
  3561. this.sendRequest(action, request, (message) => {
  3562. this.log_(action + ' response', message);
  3563. delete this.outstandingPuts_[index];
  3564. this.outstandingPutCount_--;
  3565. // Clean up array occasionally.
  3566. if (this.outstandingPutCount_ === 0) {
  3567. this.outstandingPuts_ = [];
  3568. }
  3569. if (onComplete) {
  3570. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3571. }
  3572. });
  3573. }
  3574. reportStats(stats) {
  3575. // If we're not connected, we just drop the stats.
  3576. if (this.connected_) {
  3577. const request = { /*counters*/ c: stats };
  3578. this.log_('reportStats', request);
  3579. this.sendRequest(/*stats*/ 's', request, result => {
  3580. const status = result[ /*status*/'s'];
  3581. if (status !== 'ok') {
  3582. const errorReason = result[ /* data */'d'];
  3583. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3584. }
  3585. });
  3586. }
  3587. }
  3588. onDataMessage_(message) {
  3589. if ('r' in message) {
  3590. // this is a response
  3591. this.log_('from server: ' + stringify(message));
  3592. const reqNum = message['r'];
  3593. const onResponse = this.requestCBHash_[reqNum];
  3594. if (onResponse) {
  3595. delete this.requestCBHash_[reqNum];
  3596. onResponse(message[ /*body*/'b']);
  3597. }
  3598. }
  3599. else if ('error' in message) {
  3600. throw 'A server-side error has occurred: ' + message['error'];
  3601. }
  3602. else if ('a' in message) {
  3603. // a and b are action and body, respectively
  3604. this.onDataPush_(message['a'], message['b']);
  3605. }
  3606. }
  3607. onDataPush_(action, body) {
  3608. this.log_('handleServerMessage', action, body);
  3609. if (action === 'd') {
  3610. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3611. /*isMerge*/ false, body['t']);
  3612. }
  3613. else if (action === 'm') {
  3614. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3615. /*isMerge=*/ true, body['t']);
  3616. }
  3617. else if (action === 'c') {
  3618. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3619. }
  3620. else if (action === 'ac') {
  3621. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3622. }
  3623. else if (action === 'apc') {
  3624. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3625. }
  3626. else if (action === 'sd') {
  3627. this.onSecurityDebugPacket_(body);
  3628. }
  3629. else {
  3630. error('Unrecognized action received from server: ' +
  3631. stringify(action) +
  3632. '\nAre you using the latest client?');
  3633. }
  3634. }
  3635. onReady_(timestamp, sessionId) {
  3636. this.log_('connection ready');
  3637. this.connected_ = true;
  3638. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3639. this.handleTimestamp_(timestamp);
  3640. this.lastSessionId = sessionId;
  3641. if (this.firstConnection_) {
  3642. this.sendConnectStats_();
  3643. }
  3644. this.restoreState_();
  3645. this.firstConnection_ = false;
  3646. this.onConnectStatus_(true);
  3647. }
  3648. scheduleConnect_(timeout) {
  3649. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3650. if (this.establishConnectionTimer_) {
  3651. clearTimeout(this.establishConnectionTimer_);
  3652. }
  3653. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3654. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3655. this.establishConnectionTimer_ = setTimeout(() => {
  3656. this.establishConnectionTimer_ = null;
  3657. this.establishConnection_();
  3658. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3659. }, Math.floor(timeout));
  3660. }
  3661. initConnection_() {
  3662. if (!this.realtime_ && this.firstConnection_) {
  3663. this.scheduleConnect_(0);
  3664. }
  3665. }
  3666. onVisible_(visible) {
  3667. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3668. if (visible &&
  3669. !this.visible_ &&
  3670. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3671. this.log_('Window became visible. Reducing delay.');
  3672. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3673. if (!this.realtime_) {
  3674. this.scheduleConnect_(0);
  3675. }
  3676. }
  3677. this.visible_ = visible;
  3678. }
  3679. onOnline_(online) {
  3680. if (online) {
  3681. this.log_('Browser went online.');
  3682. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3683. if (!this.realtime_) {
  3684. this.scheduleConnect_(0);
  3685. }
  3686. }
  3687. else {
  3688. this.log_('Browser went offline. Killing connection.');
  3689. if (this.realtime_) {
  3690. this.realtime_.close();
  3691. }
  3692. }
  3693. }
  3694. onRealtimeDisconnect_() {
  3695. this.log_('data client disconnected');
  3696. this.connected_ = false;
  3697. this.realtime_ = null;
  3698. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3699. this.cancelSentTransactions_();
  3700. // Clear out the pending requests.
  3701. this.requestCBHash_ = {};
  3702. if (this.shouldReconnect_()) {
  3703. if (!this.visible_) {
  3704. this.log_("Window isn't visible. Delaying reconnect.");
  3705. this.reconnectDelay_ = this.maxReconnectDelay_;
  3706. this.lastConnectionAttemptTime_ = new Date().getTime();
  3707. }
  3708. else if (this.lastConnectionEstablishedTime_) {
  3709. // If we've been connected long enough, reset reconnect delay to minimum.
  3710. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3711. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3712. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3713. }
  3714. this.lastConnectionEstablishedTime_ = null;
  3715. }
  3716. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3717. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3718. reconnectDelay = Math.random() * reconnectDelay;
  3719. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3720. this.scheduleConnect_(reconnectDelay);
  3721. // Adjust reconnect delay for next time.
  3722. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3723. }
  3724. this.onConnectStatus_(false);
  3725. }
  3726. async establishConnection_() {
  3727. if (this.shouldReconnect_()) {
  3728. this.log_('Making a connection attempt');
  3729. this.lastConnectionAttemptTime_ = new Date().getTime();
  3730. this.lastConnectionEstablishedTime_ = null;
  3731. const onDataMessage = this.onDataMessage_.bind(this);
  3732. const onReady = this.onReady_.bind(this);
  3733. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3734. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3735. const lastSessionId = this.lastSessionId;
  3736. let canceled = false;
  3737. let connection = null;
  3738. const closeFn = function () {
  3739. if (connection) {
  3740. connection.close();
  3741. }
  3742. else {
  3743. canceled = true;
  3744. onDisconnect();
  3745. }
  3746. };
  3747. const sendRequestFn = function (msg) {
  3748. assert(connection, "sendRequest call when we're not connected not allowed.");
  3749. connection.sendRequest(msg);
  3750. };
  3751. this.realtime_ = {
  3752. close: closeFn,
  3753. sendRequest: sendRequestFn
  3754. };
  3755. const forceRefresh = this.forceTokenRefresh_;
  3756. this.forceTokenRefresh_ = false;
  3757. try {
  3758. // First fetch auth and app check token, and establish connection after
  3759. // fetching the token was successful
  3760. const [authToken, appCheckToken] = await Promise.all([
  3761. this.authTokenProvider_.getToken(forceRefresh),
  3762. this.appCheckTokenProvider_.getToken(forceRefresh)
  3763. ]);
  3764. if (!canceled) {
  3765. log('getToken() completed. Creating connection.');
  3766. this.authToken_ = authToken && authToken.accessToken;
  3767. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3768. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3769. /* onKill= */ reason => {
  3770. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3771. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3772. }, lastSessionId);
  3773. }
  3774. else {
  3775. log('getToken() completed but was canceled');
  3776. }
  3777. }
  3778. catch (error) {
  3779. this.log_('Failed to get token: ' + error);
  3780. if (!canceled) {
  3781. if (this.repoInfo_.nodeAdmin) {
  3782. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3783. // But getToken() may also just have temporarily failed, so we still want to
  3784. // continue retrying.
  3785. warn(error);
  3786. }
  3787. closeFn();
  3788. }
  3789. }
  3790. }
  3791. }
  3792. interrupt(reason) {
  3793. log('Interrupting connection for reason: ' + reason);
  3794. this.interruptReasons_[reason] = true;
  3795. if (this.realtime_) {
  3796. this.realtime_.close();
  3797. }
  3798. else {
  3799. if (this.establishConnectionTimer_) {
  3800. clearTimeout(this.establishConnectionTimer_);
  3801. this.establishConnectionTimer_ = null;
  3802. }
  3803. if (this.connected_) {
  3804. this.onRealtimeDisconnect_();
  3805. }
  3806. }
  3807. }
  3808. resume(reason) {
  3809. log('Resuming connection for reason: ' + reason);
  3810. delete this.interruptReasons_[reason];
  3811. if (isEmpty(this.interruptReasons_)) {
  3812. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3813. if (!this.realtime_) {
  3814. this.scheduleConnect_(0);
  3815. }
  3816. }
  3817. }
  3818. handleTimestamp_(timestamp) {
  3819. const delta = timestamp - new Date().getTime();
  3820. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3821. }
  3822. cancelSentTransactions_() {
  3823. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3824. const put = this.outstandingPuts_[i];
  3825. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3826. if (put.onComplete) {
  3827. put.onComplete('disconnect');
  3828. }
  3829. delete this.outstandingPuts_[i];
  3830. this.outstandingPutCount_--;
  3831. }
  3832. }
  3833. // Clean up array occasionally.
  3834. if (this.outstandingPutCount_ === 0) {
  3835. this.outstandingPuts_ = [];
  3836. }
  3837. }
  3838. onListenRevoked_(pathString, query) {
  3839. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3840. let queryId;
  3841. if (!query) {
  3842. queryId = 'default';
  3843. }
  3844. else {
  3845. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3846. }
  3847. const listen = this.removeListen_(pathString, queryId);
  3848. if (listen && listen.onComplete) {
  3849. listen.onComplete('permission_denied');
  3850. }
  3851. }
  3852. removeListen_(pathString, queryId) {
  3853. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3854. let listen;
  3855. if (this.listens.has(normalizedPathString)) {
  3856. const map = this.listens.get(normalizedPathString);
  3857. listen = map.get(queryId);
  3858. map.delete(queryId);
  3859. if (map.size === 0) {
  3860. this.listens.delete(normalizedPathString);
  3861. }
  3862. }
  3863. else {
  3864. // all listens for this path has already been removed
  3865. listen = undefined;
  3866. }
  3867. return listen;
  3868. }
  3869. onAuthRevoked_(statusCode, explanation) {
  3870. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3871. this.authToken_ = null;
  3872. this.forceTokenRefresh_ = true;
  3873. this.realtime_.close();
  3874. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3875. // We'll wait a couple times before logging the warning / increasing the
  3876. // retry period since oauth tokens will report as "invalid" if they're
  3877. // just expired. Plus there may be transient issues that resolve themselves.
  3878. this.invalidAuthTokenCount_++;
  3879. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3880. // Set a long reconnect delay because recovery is unlikely
  3881. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3882. // Notify the auth token provider that the token is invalid, which will log
  3883. // a warning
  3884. this.authTokenProvider_.notifyForInvalidToken();
  3885. }
  3886. }
  3887. }
  3888. onAppCheckRevoked_(statusCode, explanation) {
  3889. log('App check token revoked: ' + statusCode + '/' + explanation);
  3890. this.appCheckToken_ = null;
  3891. this.forceTokenRefresh_ = true;
  3892. // Note: We don't close the connection as the developer may not have
  3893. // enforcement enabled. The backend closes connections with enforcements.
  3894. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3895. // We'll wait a couple times before logging the warning / increasing the
  3896. // retry period since oauth tokens will report as "invalid" if they're
  3897. // just expired. Plus there may be transient issues that resolve themselves.
  3898. this.invalidAppCheckTokenCount_++;
  3899. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3900. this.appCheckTokenProvider_.notifyForInvalidToken();
  3901. }
  3902. }
  3903. }
  3904. onSecurityDebugPacket_(body) {
  3905. if (this.securityDebugCallback_) {
  3906. this.securityDebugCallback_(body);
  3907. }
  3908. else {
  3909. if ('msg' in body) {
  3910. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3911. }
  3912. }
  3913. }
  3914. restoreState_() {
  3915. //Re-authenticate ourselves if we have a credential stored.
  3916. this.tryAuth();
  3917. this.tryAppCheck();
  3918. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3919. // make sure to send listens before puts.
  3920. for (const queries of this.listens.values()) {
  3921. for (const listenSpec of queries.values()) {
  3922. this.sendListen_(listenSpec);
  3923. }
  3924. }
  3925. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3926. if (this.outstandingPuts_[i]) {
  3927. this.sendPut_(i);
  3928. }
  3929. }
  3930. while (this.onDisconnectRequestQueue_.length) {
  3931. const request = this.onDisconnectRequestQueue_.shift();
  3932. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3933. }
  3934. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3935. if (this.outstandingGets_[i]) {
  3936. this.sendGet_(i);
  3937. }
  3938. }
  3939. }
  3940. /**
  3941. * Sends client stats for first connection
  3942. */
  3943. sendConnectStats_() {
  3944. const stats = {};
  3945. let clientName = 'js';
  3946. if (isNodeSdk()) {
  3947. if (this.repoInfo_.nodeAdmin) {
  3948. clientName = 'admin_node';
  3949. }
  3950. else {
  3951. clientName = 'node';
  3952. }
  3953. }
  3954. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3955. if (isMobileCordova()) {
  3956. stats['framework.cordova'] = 1;
  3957. }
  3958. else if (isReactNative()) {
  3959. stats['framework.reactnative'] = 1;
  3960. }
  3961. this.reportStats(stats);
  3962. }
  3963. shouldReconnect_() {
  3964. const online = OnlineMonitor.getInstance().currentlyOnline();
  3965. return isEmpty(this.interruptReasons_) && online;
  3966. }
  3967. }
  3968. PersistentConnection.nextPersistentConnectionId_ = 0;
  3969. /**
  3970. * Counter for number of connections created. Mainly used for tagging in the logs
  3971. */
  3972. PersistentConnection.nextConnectionId_ = 0;
  3973. /**
  3974. * @license
  3975. * Copyright 2017 Google LLC
  3976. *
  3977. * Licensed under the Apache License, Version 2.0 (the "License");
  3978. * you may not use this file except in compliance with the License.
  3979. * You may obtain a copy of the License at
  3980. *
  3981. * http://www.apache.org/licenses/LICENSE-2.0
  3982. *
  3983. * Unless required by applicable law or agreed to in writing, software
  3984. * distributed under the License is distributed on an "AS IS" BASIS,
  3985. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3986. * See the License for the specific language governing permissions and
  3987. * limitations under the License.
  3988. */
  3989. class NamedNode {
  3990. constructor(name, node) {
  3991. this.name = name;
  3992. this.node = node;
  3993. }
  3994. static Wrap(name, node) {
  3995. return new NamedNode(name, node);
  3996. }
  3997. }
  3998. /**
  3999. * @license
  4000. * Copyright 2017 Google LLC
  4001. *
  4002. * Licensed under the Apache License, Version 2.0 (the "License");
  4003. * you may not use this file except in compliance with the License.
  4004. * You may obtain a copy of the License at
  4005. *
  4006. * http://www.apache.org/licenses/LICENSE-2.0
  4007. *
  4008. * Unless required by applicable law or agreed to in writing, software
  4009. * distributed under the License is distributed on an "AS IS" BASIS,
  4010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4011. * See the License for the specific language governing permissions and
  4012. * limitations under the License.
  4013. */
  4014. class Index {
  4015. /**
  4016. * @returns A standalone comparison function for
  4017. * this index
  4018. */
  4019. getCompare() {
  4020. return this.compare.bind(this);
  4021. }
  4022. /**
  4023. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4024. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4025. *
  4026. *
  4027. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4028. */
  4029. indexedValueChanged(oldNode, newNode) {
  4030. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4031. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4032. return this.compare(oldWrapped, newWrapped) !== 0;
  4033. }
  4034. /**
  4035. * @returns a node wrapper that will sort equal to or less than
  4036. * any other node wrapper, using this index
  4037. */
  4038. minPost() {
  4039. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4040. return NamedNode.MIN;
  4041. }
  4042. }
  4043. /**
  4044. * @license
  4045. * Copyright 2017 Google LLC
  4046. *
  4047. * Licensed under the Apache License, Version 2.0 (the "License");
  4048. * you may not use this file except in compliance with the License.
  4049. * You may obtain a copy of the License at
  4050. *
  4051. * http://www.apache.org/licenses/LICENSE-2.0
  4052. *
  4053. * Unless required by applicable law or agreed to in writing, software
  4054. * distributed under the License is distributed on an "AS IS" BASIS,
  4055. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4056. * See the License for the specific language governing permissions and
  4057. * limitations under the License.
  4058. */
  4059. let __EMPTY_NODE;
  4060. class KeyIndex extends Index {
  4061. static get __EMPTY_NODE() {
  4062. return __EMPTY_NODE;
  4063. }
  4064. static set __EMPTY_NODE(val) {
  4065. __EMPTY_NODE = val;
  4066. }
  4067. compare(a, b) {
  4068. return nameCompare(a.name, b.name);
  4069. }
  4070. isDefinedOn(node) {
  4071. // We could probably return true here (since every node has a key), but it's never called
  4072. // so just leaving unimplemented for now.
  4073. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4074. }
  4075. indexedValueChanged(oldNode, newNode) {
  4076. return false; // The key for a node never changes.
  4077. }
  4078. minPost() {
  4079. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4080. return NamedNode.MIN;
  4081. }
  4082. maxPost() {
  4083. // TODO: This should really be created once and cached in a static property, but
  4084. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4085. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4086. }
  4087. makePost(indexValue, name) {
  4088. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4089. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4090. return new NamedNode(indexValue, __EMPTY_NODE);
  4091. }
  4092. /**
  4093. * @returns String representation for inclusion in a query spec
  4094. */
  4095. toString() {
  4096. return '.key';
  4097. }
  4098. }
  4099. const KEY_INDEX = new KeyIndex();
  4100. /**
  4101. * @license
  4102. * Copyright 2017 Google LLC
  4103. *
  4104. * Licensed under the Apache License, Version 2.0 (the "License");
  4105. * you may not use this file except in compliance with the License.
  4106. * You may obtain a copy of the License at
  4107. *
  4108. * http://www.apache.org/licenses/LICENSE-2.0
  4109. *
  4110. * Unless required by applicable law or agreed to in writing, software
  4111. * distributed under the License is distributed on an "AS IS" BASIS,
  4112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4113. * See the License for the specific language governing permissions and
  4114. * limitations under the License.
  4115. */
  4116. /**
  4117. * An iterator over an LLRBNode.
  4118. */
  4119. class SortedMapIterator {
  4120. /**
  4121. * @param node - Node to iterate.
  4122. * @param isReverse_ - Whether or not to iterate in reverse
  4123. */
  4124. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4125. this.isReverse_ = isReverse_;
  4126. this.resultGenerator_ = resultGenerator_;
  4127. this.nodeStack_ = [];
  4128. let cmp = 1;
  4129. while (!node.isEmpty()) {
  4130. node = node;
  4131. cmp = startKey ? comparator(node.key, startKey) : 1;
  4132. // flip the comparison if we're going in reverse
  4133. if (isReverse_) {
  4134. cmp *= -1;
  4135. }
  4136. if (cmp < 0) {
  4137. // This node is less than our start key. ignore it
  4138. if (this.isReverse_) {
  4139. node = node.left;
  4140. }
  4141. else {
  4142. node = node.right;
  4143. }
  4144. }
  4145. else if (cmp === 0) {
  4146. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4147. this.nodeStack_.push(node);
  4148. break;
  4149. }
  4150. else {
  4151. // This node is greater than our start key, add it to the stack and move to the next one
  4152. this.nodeStack_.push(node);
  4153. if (this.isReverse_) {
  4154. node = node.right;
  4155. }
  4156. else {
  4157. node = node.left;
  4158. }
  4159. }
  4160. }
  4161. }
  4162. getNext() {
  4163. if (this.nodeStack_.length === 0) {
  4164. return null;
  4165. }
  4166. let node = this.nodeStack_.pop();
  4167. let result;
  4168. if (this.resultGenerator_) {
  4169. result = this.resultGenerator_(node.key, node.value);
  4170. }
  4171. else {
  4172. result = { key: node.key, value: node.value };
  4173. }
  4174. if (this.isReverse_) {
  4175. node = node.left;
  4176. while (!node.isEmpty()) {
  4177. this.nodeStack_.push(node);
  4178. node = node.right;
  4179. }
  4180. }
  4181. else {
  4182. node = node.right;
  4183. while (!node.isEmpty()) {
  4184. this.nodeStack_.push(node);
  4185. node = node.left;
  4186. }
  4187. }
  4188. return result;
  4189. }
  4190. hasNext() {
  4191. return this.nodeStack_.length > 0;
  4192. }
  4193. peek() {
  4194. if (this.nodeStack_.length === 0) {
  4195. return null;
  4196. }
  4197. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4198. if (this.resultGenerator_) {
  4199. return this.resultGenerator_(node.key, node.value);
  4200. }
  4201. else {
  4202. return { key: node.key, value: node.value };
  4203. }
  4204. }
  4205. }
  4206. /**
  4207. * Represents a node in a Left-leaning Red-Black tree.
  4208. */
  4209. class LLRBNode {
  4210. /**
  4211. * @param key - Key associated with this node.
  4212. * @param value - Value associated with this node.
  4213. * @param color - Whether this node is red.
  4214. * @param left - Left child.
  4215. * @param right - Right child.
  4216. */
  4217. constructor(key, value, color, left, right) {
  4218. this.key = key;
  4219. this.value = value;
  4220. this.color = color != null ? color : LLRBNode.RED;
  4221. this.left =
  4222. left != null ? left : SortedMap.EMPTY_NODE;
  4223. this.right =
  4224. right != null ? right : SortedMap.EMPTY_NODE;
  4225. }
  4226. /**
  4227. * Returns a copy of the current node, optionally replacing pieces of it.
  4228. *
  4229. * @param key - New key for the node, or null.
  4230. * @param value - New value for the node, or null.
  4231. * @param color - New color for the node, or null.
  4232. * @param left - New left child for the node, or null.
  4233. * @param right - New right child for the node, or null.
  4234. * @returns The node copy.
  4235. */
  4236. copy(key, value, color, left, right) {
  4237. 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);
  4238. }
  4239. /**
  4240. * @returns The total number of nodes in the tree.
  4241. */
  4242. count() {
  4243. return this.left.count() + 1 + this.right.count();
  4244. }
  4245. /**
  4246. * @returns True if the tree is empty.
  4247. */
  4248. isEmpty() {
  4249. return false;
  4250. }
  4251. /**
  4252. * Traverses the tree in key order and calls the specified action function
  4253. * for each node.
  4254. *
  4255. * @param action - Callback function to be called for each
  4256. * node. If it returns true, traversal is aborted.
  4257. * @returns The first truthy value returned by action, or the last falsey
  4258. * value returned by action
  4259. */
  4260. inorderTraversal(action) {
  4261. return (this.left.inorderTraversal(action) ||
  4262. !!action(this.key, this.value) ||
  4263. this.right.inorderTraversal(action));
  4264. }
  4265. /**
  4266. * Traverses the tree in reverse key order and calls the specified action function
  4267. * for each node.
  4268. *
  4269. * @param action - Callback function to be called for each
  4270. * node. If it returns true, traversal is aborted.
  4271. * @returns True if traversal was aborted.
  4272. */
  4273. reverseTraversal(action) {
  4274. return (this.right.reverseTraversal(action) ||
  4275. action(this.key, this.value) ||
  4276. this.left.reverseTraversal(action));
  4277. }
  4278. /**
  4279. * @returns The minimum node in the tree.
  4280. */
  4281. min_() {
  4282. if (this.left.isEmpty()) {
  4283. return this;
  4284. }
  4285. else {
  4286. return this.left.min_();
  4287. }
  4288. }
  4289. /**
  4290. * @returns The maximum key in the tree.
  4291. */
  4292. minKey() {
  4293. return this.min_().key;
  4294. }
  4295. /**
  4296. * @returns The maximum key in the tree.
  4297. */
  4298. maxKey() {
  4299. if (this.right.isEmpty()) {
  4300. return this.key;
  4301. }
  4302. else {
  4303. return this.right.maxKey();
  4304. }
  4305. }
  4306. /**
  4307. * @param key - Key to insert.
  4308. * @param value - Value to insert.
  4309. * @param comparator - Comparator.
  4310. * @returns New tree, with the key/value added.
  4311. */
  4312. insert(key, value, comparator) {
  4313. let n = this;
  4314. const cmp = comparator(key, n.key);
  4315. if (cmp < 0) {
  4316. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4317. }
  4318. else if (cmp === 0) {
  4319. n = n.copy(null, value, null, null, null);
  4320. }
  4321. else {
  4322. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4323. }
  4324. return n.fixUp_();
  4325. }
  4326. /**
  4327. * @returns New tree, with the minimum key removed.
  4328. */
  4329. removeMin_() {
  4330. if (this.left.isEmpty()) {
  4331. return SortedMap.EMPTY_NODE;
  4332. }
  4333. let n = this;
  4334. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4335. n = n.moveRedLeft_();
  4336. }
  4337. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4338. return n.fixUp_();
  4339. }
  4340. /**
  4341. * @param key - The key of the item to remove.
  4342. * @param comparator - Comparator.
  4343. * @returns New tree, with the specified item removed.
  4344. */
  4345. remove(key, comparator) {
  4346. let n, smallest;
  4347. n = this;
  4348. if (comparator(key, n.key) < 0) {
  4349. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4350. n = n.moveRedLeft_();
  4351. }
  4352. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4353. }
  4354. else {
  4355. if (n.left.isRed_()) {
  4356. n = n.rotateRight_();
  4357. }
  4358. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4359. n = n.moveRedRight_();
  4360. }
  4361. if (comparator(key, n.key) === 0) {
  4362. if (n.right.isEmpty()) {
  4363. return SortedMap.EMPTY_NODE;
  4364. }
  4365. else {
  4366. smallest = n.right.min_();
  4367. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4368. }
  4369. }
  4370. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4371. }
  4372. return n.fixUp_();
  4373. }
  4374. /**
  4375. * @returns Whether this is a RED node.
  4376. */
  4377. isRed_() {
  4378. return this.color;
  4379. }
  4380. /**
  4381. * @returns New tree after performing any needed rotations.
  4382. */
  4383. fixUp_() {
  4384. let n = this;
  4385. if (n.right.isRed_() && !n.left.isRed_()) {
  4386. n = n.rotateLeft_();
  4387. }
  4388. if (n.left.isRed_() && n.left.left.isRed_()) {
  4389. n = n.rotateRight_();
  4390. }
  4391. if (n.left.isRed_() && n.right.isRed_()) {
  4392. n = n.colorFlip_();
  4393. }
  4394. return n;
  4395. }
  4396. /**
  4397. * @returns New tree, after moveRedLeft.
  4398. */
  4399. moveRedLeft_() {
  4400. let n = this.colorFlip_();
  4401. if (n.right.left.isRed_()) {
  4402. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4403. n = n.rotateLeft_();
  4404. n = n.colorFlip_();
  4405. }
  4406. return n;
  4407. }
  4408. /**
  4409. * @returns New tree, after moveRedRight.
  4410. */
  4411. moveRedRight_() {
  4412. let n = this.colorFlip_();
  4413. if (n.left.left.isRed_()) {
  4414. n = n.rotateRight_();
  4415. n = n.colorFlip_();
  4416. }
  4417. return n;
  4418. }
  4419. /**
  4420. * @returns New tree, after rotateLeft.
  4421. */
  4422. rotateLeft_() {
  4423. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4424. return this.right.copy(null, null, this.color, nl, null);
  4425. }
  4426. /**
  4427. * @returns New tree, after rotateRight.
  4428. */
  4429. rotateRight_() {
  4430. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4431. return this.left.copy(null, null, this.color, null, nr);
  4432. }
  4433. /**
  4434. * @returns Newt ree, after colorFlip.
  4435. */
  4436. colorFlip_() {
  4437. const left = this.left.copy(null, null, !this.left.color, null, null);
  4438. const right = this.right.copy(null, null, !this.right.color, null, null);
  4439. return this.copy(null, null, !this.color, left, right);
  4440. }
  4441. /**
  4442. * For testing.
  4443. *
  4444. * @returns True if all is well.
  4445. */
  4446. checkMaxDepth_() {
  4447. const blackDepth = this.check_();
  4448. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4449. }
  4450. check_() {
  4451. if (this.isRed_() && this.left.isRed_()) {
  4452. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4453. }
  4454. if (this.right.isRed_()) {
  4455. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4456. }
  4457. const blackDepth = this.left.check_();
  4458. if (blackDepth !== this.right.check_()) {
  4459. throw new Error('Black depths differ');
  4460. }
  4461. else {
  4462. return blackDepth + (this.isRed_() ? 0 : 1);
  4463. }
  4464. }
  4465. }
  4466. LLRBNode.RED = true;
  4467. LLRBNode.BLACK = false;
  4468. /**
  4469. * Represents an empty node (a leaf node in the Red-Black Tree).
  4470. */
  4471. class LLRBEmptyNode {
  4472. /**
  4473. * Returns a copy of the current node.
  4474. *
  4475. * @returns The node copy.
  4476. */
  4477. copy(key, value, color, left, right) {
  4478. return this;
  4479. }
  4480. /**
  4481. * Returns a copy of the tree, with the specified key/value added.
  4482. *
  4483. * @param key - Key to be added.
  4484. * @param value - Value to be added.
  4485. * @param comparator - Comparator.
  4486. * @returns New tree, with item added.
  4487. */
  4488. insert(key, value, comparator) {
  4489. return new LLRBNode(key, value, null);
  4490. }
  4491. /**
  4492. * Returns a copy of the tree, with the specified key removed.
  4493. *
  4494. * @param key - The key to remove.
  4495. * @param comparator - Comparator.
  4496. * @returns New tree, with item removed.
  4497. */
  4498. remove(key, comparator) {
  4499. return this;
  4500. }
  4501. /**
  4502. * @returns The total number of nodes in the tree.
  4503. */
  4504. count() {
  4505. return 0;
  4506. }
  4507. /**
  4508. * @returns True if the tree is empty.
  4509. */
  4510. isEmpty() {
  4511. return true;
  4512. }
  4513. /**
  4514. * Traverses the tree in key order and calls the specified action function
  4515. * for each node.
  4516. *
  4517. * @param action - Callback function to be called for each
  4518. * node. If it returns true, traversal is aborted.
  4519. * @returns True if traversal was aborted.
  4520. */
  4521. inorderTraversal(action) {
  4522. return false;
  4523. }
  4524. /**
  4525. * Traverses the tree in reverse key order and calls the specified action function
  4526. * for each node.
  4527. *
  4528. * @param action - Callback function to be called for each
  4529. * node. If it returns true, traversal is aborted.
  4530. * @returns True if traversal was aborted.
  4531. */
  4532. reverseTraversal(action) {
  4533. return false;
  4534. }
  4535. minKey() {
  4536. return null;
  4537. }
  4538. maxKey() {
  4539. return null;
  4540. }
  4541. check_() {
  4542. return 0;
  4543. }
  4544. /**
  4545. * @returns Whether this node is red.
  4546. */
  4547. isRed_() {
  4548. return false;
  4549. }
  4550. }
  4551. /**
  4552. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4553. * tree.
  4554. */
  4555. class SortedMap {
  4556. /**
  4557. * @param comparator_ - Key comparator.
  4558. * @param root_ - Optional root node for the map.
  4559. */
  4560. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4561. this.comparator_ = comparator_;
  4562. this.root_ = root_;
  4563. }
  4564. /**
  4565. * Returns a copy of the map, with the specified key/value added or replaced.
  4566. * (TODO: We should perhaps rename this method to 'put')
  4567. *
  4568. * @param key - Key to be added.
  4569. * @param value - Value to be added.
  4570. * @returns New map, with item added.
  4571. */
  4572. insert(key, value) {
  4573. return new SortedMap(this.comparator_, this.root_
  4574. .insert(key, value, this.comparator_)
  4575. .copy(null, null, LLRBNode.BLACK, null, null));
  4576. }
  4577. /**
  4578. * Returns a copy of the map, with the specified key removed.
  4579. *
  4580. * @param key - The key to remove.
  4581. * @returns New map, with item removed.
  4582. */
  4583. remove(key) {
  4584. return new SortedMap(this.comparator_, this.root_
  4585. .remove(key, this.comparator_)
  4586. .copy(null, null, LLRBNode.BLACK, null, null));
  4587. }
  4588. /**
  4589. * Returns the value of the node with the given key, or null.
  4590. *
  4591. * @param key - The key to look up.
  4592. * @returns The value of the node with the given key, or null if the
  4593. * key doesn't exist.
  4594. */
  4595. get(key) {
  4596. let cmp;
  4597. let node = this.root_;
  4598. while (!node.isEmpty()) {
  4599. cmp = this.comparator_(key, node.key);
  4600. if (cmp === 0) {
  4601. return node.value;
  4602. }
  4603. else if (cmp < 0) {
  4604. node = node.left;
  4605. }
  4606. else if (cmp > 0) {
  4607. node = node.right;
  4608. }
  4609. }
  4610. return null;
  4611. }
  4612. /**
  4613. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4614. * @param key - The key to find the predecessor of
  4615. * @returns The predecessor key.
  4616. */
  4617. getPredecessorKey(key) {
  4618. let cmp, node = this.root_, rightParent = null;
  4619. while (!node.isEmpty()) {
  4620. cmp = this.comparator_(key, node.key);
  4621. if (cmp === 0) {
  4622. if (!node.left.isEmpty()) {
  4623. node = node.left;
  4624. while (!node.right.isEmpty()) {
  4625. node = node.right;
  4626. }
  4627. return node.key;
  4628. }
  4629. else if (rightParent) {
  4630. return rightParent.key;
  4631. }
  4632. else {
  4633. return null; // first item.
  4634. }
  4635. }
  4636. else if (cmp < 0) {
  4637. node = node.left;
  4638. }
  4639. else if (cmp > 0) {
  4640. rightParent = node;
  4641. node = node.right;
  4642. }
  4643. }
  4644. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4645. }
  4646. /**
  4647. * @returns True if the map is empty.
  4648. */
  4649. isEmpty() {
  4650. return this.root_.isEmpty();
  4651. }
  4652. /**
  4653. * @returns The total number of nodes in the map.
  4654. */
  4655. count() {
  4656. return this.root_.count();
  4657. }
  4658. /**
  4659. * @returns The minimum key in the map.
  4660. */
  4661. minKey() {
  4662. return this.root_.minKey();
  4663. }
  4664. /**
  4665. * @returns The maximum key in the map.
  4666. */
  4667. maxKey() {
  4668. return this.root_.maxKey();
  4669. }
  4670. /**
  4671. * Traverses the map in key order and calls the specified action function
  4672. * for each key/value pair.
  4673. *
  4674. * @param action - Callback function to be called
  4675. * for each key/value pair. If action returns true, traversal is aborted.
  4676. * @returns The first truthy value returned by action, or the last falsey
  4677. * value returned by action
  4678. */
  4679. inorderTraversal(action) {
  4680. return this.root_.inorderTraversal(action);
  4681. }
  4682. /**
  4683. * Traverses the map in reverse key order and calls the specified action function
  4684. * for each key/value pair.
  4685. *
  4686. * @param action - Callback function to be called
  4687. * for each key/value pair. If action returns true, traversal is aborted.
  4688. * @returns True if the traversal was aborted.
  4689. */
  4690. reverseTraversal(action) {
  4691. return this.root_.reverseTraversal(action);
  4692. }
  4693. /**
  4694. * Returns an iterator over the SortedMap.
  4695. * @returns The iterator.
  4696. */
  4697. getIterator(resultGenerator) {
  4698. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4699. }
  4700. getIteratorFrom(key, resultGenerator) {
  4701. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4702. }
  4703. getReverseIteratorFrom(key, resultGenerator) {
  4704. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4705. }
  4706. getReverseIterator(resultGenerator) {
  4707. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4708. }
  4709. }
  4710. /**
  4711. * Always use the same empty node, to reduce memory.
  4712. */
  4713. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4714. /**
  4715. * @license
  4716. * Copyright 2017 Google LLC
  4717. *
  4718. * Licensed under the Apache License, Version 2.0 (the "License");
  4719. * you may not use this file except in compliance with the License.
  4720. * You may obtain a copy of the License at
  4721. *
  4722. * http://www.apache.org/licenses/LICENSE-2.0
  4723. *
  4724. * Unless required by applicable law or agreed to in writing, software
  4725. * distributed under the License is distributed on an "AS IS" BASIS,
  4726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4727. * See the License for the specific language governing permissions and
  4728. * limitations under the License.
  4729. */
  4730. function NAME_ONLY_COMPARATOR(left, right) {
  4731. return nameCompare(left.name, right.name);
  4732. }
  4733. function NAME_COMPARATOR(left, right) {
  4734. return nameCompare(left, right);
  4735. }
  4736. /**
  4737. * @license
  4738. * Copyright 2017 Google LLC
  4739. *
  4740. * Licensed under the Apache License, Version 2.0 (the "License");
  4741. * you may not use this file except in compliance with the License.
  4742. * You may obtain a copy of the License at
  4743. *
  4744. * http://www.apache.org/licenses/LICENSE-2.0
  4745. *
  4746. * Unless required by applicable law or agreed to in writing, software
  4747. * distributed under the License is distributed on an "AS IS" BASIS,
  4748. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4749. * See the License for the specific language governing permissions and
  4750. * limitations under the License.
  4751. */
  4752. let MAX_NODE$2;
  4753. function setMaxNode$1(val) {
  4754. MAX_NODE$2 = val;
  4755. }
  4756. const priorityHashText = function (priority) {
  4757. if (typeof priority === 'number') {
  4758. return 'number:' + doubleToIEEE754String(priority);
  4759. }
  4760. else {
  4761. return 'string:' + priority;
  4762. }
  4763. };
  4764. /**
  4765. * Validates that a priority snapshot Node is valid.
  4766. */
  4767. const validatePriorityNode = function (priorityNode) {
  4768. if (priorityNode.isLeafNode()) {
  4769. const val = priorityNode.val();
  4770. assert(typeof val === 'string' ||
  4771. typeof val === 'number' ||
  4772. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4773. }
  4774. else {
  4775. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4776. }
  4777. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4778. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4779. };
  4780. /**
  4781. * @license
  4782. * Copyright 2017 Google LLC
  4783. *
  4784. * Licensed under the Apache License, Version 2.0 (the "License");
  4785. * you may not use this file except in compliance with the License.
  4786. * You may obtain a copy of the License at
  4787. *
  4788. * http://www.apache.org/licenses/LICENSE-2.0
  4789. *
  4790. * Unless required by applicable law or agreed to in writing, software
  4791. * distributed under the License is distributed on an "AS IS" BASIS,
  4792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4793. * See the License for the specific language governing permissions and
  4794. * limitations under the License.
  4795. */
  4796. let __childrenNodeConstructor;
  4797. /**
  4798. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4799. * implements Node and stores the value of the node (a string,
  4800. * number, or boolean) accessible via getValue().
  4801. */
  4802. class LeafNode {
  4803. /**
  4804. * @param value_ - The value to store in this leaf node. The object type is
  4805. * possible in the event of a deferred value
  4806. * @param priorityNode_ - The priority of this node.
  4807. */
  4808. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4809. this.value_ = value_;
  4810. this.priorityNode_ = priorityNode_;
  4811. this.lazyHash_ = null;
  4812. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4813. validatePriorityNode(this.priorityNode_);
  4814. }
  4815. static set __childrenNodeConstructor(val) {
  4816. __childrenNodeConstructor = val;
  4817. }
  4818. static get __childrenNodeConstructor() {
  4819. return __childrenNodeConstructor;
  4820. }
  4821. /** @inheritDoc */
  4822. isLeafNode() {
  4823. return true;
  4824. }
  4825. /** @inheritDoc */
  4826. getPriority() {
  4827. return this.priorityNode_;
  4828. }
  4829. /** @inheritDoc */
  4830. updatePriority(newPriorityNode) {
  4831. return new LeafNode(this.value_, newPriorityNode);
  4832. }
  4833. /** @inheritDoc */
  4834. getImmediateChild(childName) {
  4835. // Hack to treat priority as a regular child
  4836. if (childName === '.priority') {
  4837. return this.priorityNode_;
  4838. }
  4839. else {
  4840. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4841. }
  4842. }
  4843. /** @inheritDoc */
  4844. getChild(path) {
  4845. if (pathIsEmpty(path)) {
  4846. return this;
  4847. }
  4848. else if (pathGetFront(path) === '.priority') {
  4849. return this.priorityNode_;
  4850. }
  4851. else {
  4852. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4853. }
  4854. }
  4855. hasChild() {
  4856. return false;
  4857. }
  4858. /** @inheritDoc */
  4859. getPredecessorChildName(childName, childNode) {
  4860. return null;
  4861. }
  4862. /** @inheritDoc */
  4863. updateImmediateChild(childName, newChildNode) {
  4864. if (childName === '.priority') {
  4865. return this.updatePriority(newChildNode);
  4866. }
  4867. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4868. return this;
  4869. }
  4870. else {
  4871. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4872. }
  4873. }
  4874. /** @inheritDoc */
  4875. updateChild(path, newChildNode) {
  4876. const front = pathGetFront(path);
  4877. if (front === null) {
  4878. return newChildNode;
  4879. }
  4880. else if (newChildNode.isEmpty() && front !== '.priority') {
  4881. return this;
  4882. }
  4883. else {
  4884. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4885. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4886. }
  4887. }
  4888. /** @inheritDoc */
  4889. isEmpty() {
  4890. return false;
  4891. }
  4892. /** @inheritDoc */
  4893. numChildren() {
  4894. return 0;
  4895. }
  4896. /** @inheritDoc */
  4897. forEachChild(index, action) {
  4898. return false;
  4899. }
  4900. val(exportFormat) {
  4901. if (exportFormat && !this.getPriority().isEmpty()) {
  4902. return {
  4903. '.value': this.getValue(),
  4904. '.priority': this.getPriority().val()
  4905. };
  4906. }
  4907. else {
  4908. return this.getValue();
  4909. }
  4910. }
  4911. /** @inheritDoc */
  4912. hash() {
  4913. if (this.lazyHash_ === null) {
  4914. let toHash = '';
  4915. if (!this.priorityNode_.isEmpty()) {
  4916. toHash +=
  4917. 'priority:' +
  4918. priorityHashText(this.priorityNode_.val()) +
  4919. ':';
  4920. }
  4921. const type = typeof this.value_;
  4922. toHash += type + ':';
  4923. if (type === 'number') {
  4924. toHash += doubleToIEEE754String(this.value_);
  4925. }
  4926. else {
  4927. toHash += this.value_;
  4928. }
  4929. this.lazyHash_ = sha1(toHash);
  4930. }
  4931. return this.lazyHash_;
  4932. }
  4933. /**
  4934. * Returns the value of the leaf node.
  4935. * @returns The value of the node.
  4936. */
  4937. getValue() {
  4938. return this.value_;
  4939. }
  4940. compareTo(other) {
  4941. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4942. return 1;
  4943. }
  4944. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4945. return -1;
  4946. }
  4947. else {
  4948. assert(other.isLeafNode(), 'Unknown node type');
  4949. return this.compareToLeafNode_(other);
  4950. }
  4951. }
  4952. /**
  4953. * Comparison specifically for two leaf nodes
  4954. */
  4955. compareToLeafNode_(otherLeaf) {
  4956. const otherLeafType = typeof otherLeaf.value_;
  4957. const thisLeafType = typeof this.value_;
  4958. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4959. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4960. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4961. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4962. if (otherIndex === thisIndex) {
  4963. // Same type, compare values
  4964. if (thisLeafType === 'object') {
  4965. // Deferred value nodes are all equal, but we should also never get to this point...
  4966. return 0;
  4967. }
  4968. else {
  4969. // Note that this works because true > false, all others are number or string comparisons
  4970. if (this.value_ < otherLeaf.value_) {
  4971. return -1;
  4972. }
  4973. else if (this.value_ === otherLeaf.value_) {
  4974. return 0;
  4975. }
  4976. else {
  4977. return 1;
  4978. }
  4979. }
  4980. }
  4981. else {
  4982. return thisIndex - otherIndex;
  4983. }
  4984. }
  4985. withIndex() {
  4986. return this;
  4987. }
  4988. isIndexed() {
  4989. return true;
  4990. }
  4991. equals(other) {
  4992. if (other === this) {
  4993. return true;
  4994. }
  4995. else if (other.isLeafNode()) {
  4996. const otherLeaf = other;
  4997. return (this.value_ === otherLeaf.value_ &&
  4998. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4999. }
  5000. else {
  5001. return false;
  5002. }
  5003. }
  5004. }
  5005. /**
  5006. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5007. * the same type, the comparison falls back to their value
  5008. */
  5009. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5010. /**
  5011. * @license
  5012. * Copyright 2017 Google LLC
  5013. *
  5014. * Licensed under the Apache License, Version 2.0 (the "License");
  5015. * you may not use this file except in compliance with the License.
  5016. * You may obtain a copy of the License at
  5017. *
  5018. * http://www.apache.org/licenses/LICENSE-2.0
  5019. *
  5020. * Unless required by applicable law or agreed to in writing, software
  5021. * distributed under the License is distributed on an "AS IS" BASIS,
  5022. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5023. * See the License for the specific language governing permissions and
  5024. * limitations under the License.
  5025. */
  5026. let nodeFromJSON$1;
  5027. let MAX_NODE$1;
  5028. function setNodeFromJSON(val) {
  5029. nodeFromJSON$1 = val;
  5030. }
  5031. function setMaxNode(val) {
  5032. MAX_NODE$1 = val;
  5033. }
  5034. class PriorityIndex extends Index {
  5035. compare(a, b) {
  5036. const aPriority = a.node.getPriority();
  5037. const bPriority = b.node.getPriority();
  5038. const indexCmp = aPriority.compareTo(bPriority);
  5039. if (indexCmp === 0) {
  5040. return nameCompare(a.name, b.name);
  5041. }
  5042. else {
  5043. return indexCmp;
  5044. }
  5045. }
  5046. isDefinedOn(node) {
  5047. return !node.getPriority().isEmpty();
  5048. }
  5049. indexedValueChanged(oldNode, newNode) {
  5050. return !oldNode.getPriority().equals(newNode.getPriority());
  5051. }
  5052. minPost() {
  5053. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5054. return NamedNode.MIN;
  5055. }
  5056. maxPost() {
  5057. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5058. }
  5059. makePost(indexValue, name) {
  5060. const priorityNode = nodeFromJSON$1(indexValue);
  5061. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5062. }
  5063. /**
  5064. * @returns String representation for inclusion in a query spec
  5065. */
  5066. toString() {
  5067. return '.priority';
  5068. }
  5069. }
  5070. const PRIORITY_INDEX = new PriorityIndex();
  5071. /**
  5072. * @license
  5073. * Copyright 2017 Google LLC
  5074. *
  5075. * Licensed under the Apache License, Version 2.0 (the "License");
  5076. * you may not use this file except in compliance with the License.
  5077. * You may obtain a copy of the License at
  5078. *
  5079. * http://www.apache.org/licenses/LICENSE-2.0
  5080. *
  5081. * Unless required by applicable law or agreed to in writing, software
  5082. * distributed under the License is distributed on an "AS IS" BASIS,
  5083. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5084. * See the License for the specific language governing permissions and
  5085. * limitations under the License.
  5086. */
  5087. const LOG_2 = Math.log(2);
  5088. class Base12Num {
  5089. constructor(length) {
  5090. const logBase2 = (num) =>
  5091. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5092. parseInt((Math.log(num) / LOG_2), 10);
  5093. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5094. this.count = logBase2(length + 1);
  5095. this.current_ = this.count - 1;
  5096. const mask = bitMask(this.count);
  5097. this.bits_ = (length + 1) & mask;
  5098. }
  5099. nextBitIsOne() {
  5100. //noinspection JSBitwiseOperatorUsage
  5101. const result = !(this.bits_ & (0x1 << this.current_));
  5102. this.current_--;
  5103. return result;
  5104. }
  5105. }
  5106. /**
  5107. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5108. * function
  5109. *
  5110. * Uses the algorithm described in the paper linked here:
  5111. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5112. *
  5113. * @param childList - Unsorted list of children
  5114. * @param cmp - The comparison method to be used
  5115. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5116. * type is not NamedNode
  5117. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5118. */
  5119. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5120. childList.sort(cmp);
  5121. const buildBalancedTree = function (low, high) {
  5122. const length = high - low;
  5123. let namedNode;
  5124. let key;
  5125. if (length === 0) {
  5126. return null;
  5127. }
  5128. else if (length === 1) {
  5129. namedNode = childList[low];
  5130. key = keyFn ? keyFn(namedNode) : namedNode;
  5131. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5132. }
  5133. else {
  5134. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5135. const middle = parseInt((length / 2), 10) + low;
  5136. const left = buildBalancedTree(low, middle);
  5137. const right = buildBalancedTree(middle + 1, high);
  5138. namedNode = childList[middle];
  5139. key = keyFn ? keyFn(namedNode) : namedNode;
  5140. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5141. }
  5142. };
  5143. const buildFrom12Array = function (base12) {
  5144. let node = null;
  5145. let root = null;
  5146. let index = childList.length;
  5147. const buildPennant = function (chunkSize, color) {
  5148. const low = index - chunkSize;
  5149. const high = index;
  5150. index -= chunkSize;
  5151. const childTree = buildBalancedTree(low + 1, high);
  5152. const namedNode = childList[low];
  5153. const key = keyFn ? keyFn(namedNode) : namedNode;
  5154. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5155. };
  5156. const attachPennant = function (pennant) {
  5157. if (node) {
  5158. node.left = pennant;
  5159. node = pennant;
  5160. }
  5161. else {
  5162. root = pennant;
  5163. node = pennant;
  5164. }
  5165. };
  5166. for (let i = 0; i < base12.count; ++i) {
  5167. const isOne = base12.nextBitIsOne();
  5168. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5169. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5170. if (isOne) {
  5171. buildPennant(chunkSize, LLRBNode.BLACK);
  5172. }
  5173. else {
  5174. // current == 2
  5175. buildPennant(chunkSize, LLRBNode.BLACK);
  5176. buildPennant(chunkSize, LLRBNode.RED);
  5177. }
  5178. }
  5179. return root;
  5180. };
  5181. const base12 = new Base12Num(childList.length);
  5182. const root = buildFrom12Array(base12);
  5183. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5184. return new SortedMap(mapSortFn || cmp, root);
  5185. };
  5186. /**
  5187. * @license
  5188. * Copyright 2017 Google LLC
  5189. *
  5190. * Licensed under the Apache License, Version 2.0 (the "License");
  5191. * you may not use this file except in compliance with the License.
  5192. * You may obtain a copy of the License at
  5193. *
  5194. * http://www.apache.org/licenses/LICENSE-2.0
  5195. *
  5196. * Unless required by applicable law or agreed to in writing, software
  5197. * distributed under the License is distributed on an "AS IS" BASIS,
  5198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5199. * See the License for the specific language governing permissions and
  5200. * limitations under the License.
  5201. */
  5202. let _defaultIndexMap;
  5203. const fallbackObject = {};
  5204. class IndexMap {
  5205. constructor(indexes_, indexSet_) {
  5206. this.indexes_ = indexes_;
  5207. this.indexSet_ = indexSet_;
  5208. }
  5209. /**
  5210. * The default IndexMap for nodes without a priority
  5211. */
  5212. static get Default() {
  5213. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5214. _defaultIndexMap =
  5215. _defaultIndexMap ||
  5216. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5217. return _defaultIndexMap;
  5218. }
  5219. get(indexKey) {
  5220. const sortedMap = safeGet(this.indexes_, indexKey);
  5221. if (!sortedMap) {
  5222. throw new Error('No index defined for ' + indexKey);
  5223. }
  5224. if (sortedMap instanceof SortedMap) {
  5225. return sortedMap;
  5226. }
  5227. else {
  5228. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5229. // regular child map
  5230. return null;
  5231. }
  5232. }
  5233. hasIndex(indexDefinition) {
  5234. return contains(this.indexSet_, indexDefinition.toString());
  5235. }
  5236. addIndex(indexDefinition, existingChildren) {
  5237. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5238. const childList = [];
  5239. let sawIndexedValue = false;
  5240. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5241. let next = iter.getNext();
  5242. while (next) {
  5243. sawIndexedValue =
  5244. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5245. childList.push(next);
  5246. next = iter.getNext();
  5247. }
  5248. let newIndex;
  5249. if (sawIndexedValue) {
  5250. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5251. }
  5252. else {
  5253. newIndex = fallbackObject;
  5254. }
  5255. const indexName = indexDefinition.toString();
  5256. const newIndexSet = Object.assign({}, this.indexSet_);
  5257. newIndexSet[indexName] = indexDefinition;
  5258. const newIndexes = Object.assign({}, this.indexes_);
  5259. newIndexes[indexName] = newIndex;
  5260. return new IndexMap(newIndexes, newIndexSet);
  5261. }
  5262. /**
  5263. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5264. */
  5265. addToIndexes(namedNode, existingChildren) {
  5266. const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
  5267. const index = safeGet(this.indexSet_, indexName);
  5268. assert(index, 'Missing index implementation for ' + indexName);
  5269. if (indexedChildren === fallbackObject) {
  5270. // Check to see if we need to index everything
  5271. if (index.isDefinedOn(namedNode.node)) {
  5272. // We need to build this index
  5273. const childList = [];
  5274. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5275. let next = iter.getNext();
  5276. while (next) {
  5277. if (next.name !== namedNode.name) {
  5278. childList.push(next);
  5279. }
  5280. next = iter.getNext();
  5281. }
  5282. childList.push(namedNode);
  5283. return buildChildSet(childList, index.getCompare());
  5284. }
  5285. else {
  5286. // No change, this remains a fallback
  5287. return fallbackObject;
  5288. }
  5289. }
  5290. else {
  5291. const existingSnap = existingChildren.get(namedNode.name);
  5292. let newChildren = indexedChildren;
  5293. if (existingSnap) {
  5294. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5295. }
  5296. return newChildren.insert(namedNode, namedNode.node);
  5297. }
  5298. });
  5299. return new IndexMap(newIndexes, this.indexSet_);
  5300. }
  5301. /**
  5302. * Create a new IndexMap instance with the given value removed
  5303. */
  5304. removeFromIndexes(namedNode, existingChildren) {
  5305. const newIndexes = map(this.indexes_, (indexedChildren) => {
  5306. if (indexedChildren === fallbackObject) {
  5307. // This is the fallback. Just return it, nothing to do in this case
  5308. return indexedChildren;
  5309. }
  5310. else {
  5311. const existingSnap = existingChildren.get(namedNode.name);
  5312. if (existingSnap) {
  5313. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5314. }
  5315. else {
  5316. // No record of this child
  5317. return indexedChildren;
  5318. }
  5319. }
  5320. });
  5321. return new IndexMap(newIndexes, this.indexSet_);
  5322. }
  5323. }
  5324. /**
  5325. * @license
  5326. * Copyright 2017 Google LLC
  5327. *
  5328. * Licensed under the Apache License, Version 2.0 (the "License");
  5329. * you may not use this file except in compliance with the License.
  5330. * You may obtain a copy of the License at
  5331. *
  5332. * http://www.apache.org/licenses/LICENSE-2.0
  5333. *
  5334. * Unless required by applicable law or agreed to in writing, software
  5335. * distributed under the License is distributed on an "AS IS" BASIS,
  5336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5337. * See the License for the specific language governing permissions and
  5338. * limitations under the License.
  5339. */
  5340. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5341. let EMPTY_NODE;
  5342. /**
  5343. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5344. * (i.e. nodes with children). It implements Node and stores the
  5345. * list of children in the children property, sorted by child name.
  5346. */
  5347. class ChildrenNode {
  5348. /**
  5349. * @param children_ - List of children of this node..
  5350. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5351. */
  5352. constructor(children_, priorityNode_, indexMap_) {
  5353. this.children_ = children_;
  5354. this.priorityNode_ = priorityNode_;
  5355. this.indexMap_ = indexMap_;
  5356. this.lazyHash_ = null;
  5357. /**
  5358. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5359. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5360. * class instead of an empty ChildrenNode.
  5361. */
  5362. if (this.priorityNode_) {
  5363. validatePriorityNode(this.priorityNode_);
  5364. }
  5365. if (this.children_.isEmpty()) {
  5366. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5367. }
  5368. }
  5369. static get EMPTY_NODE() {
  5370. return (EMPTY_NODE ||
  5371. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5372. }
  5373. /** @inheritDoc */
  5374. isLeafNode() {
  5375. return false;
  5376. }
  5377. /** @inheritDoc */
  5378. getPriority() {
  5379. return this.priorityNode_ || EMPTY_NODE;
  5380. }
  5381. /** @inheritDoc */
  5382. updatePriority(newPriorityNode) {
  5383. if (this.children_.isEmpty()) {
  5384. // Don't allow priorities on empty nodes
  5385. return this;
  5386. }
  5387. else {
  5388. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5389. }
  5390. }
  5391. /** @inheritDoc */
  5392. getImmediateChild(childName) {
  5393. // Hack to treat priority as a regular child
  5394. if (childName === '.priority') {
  5395. return this.getPriority();
  5396. }
  5397. else {
  5398. const child = this.children_.get(childName);
  5399. return child === null ? EMPTY_NODE : child;
  5400. }
  5401. }
  5402. /** @inheritDoc */
  5403. getChild(path) {
  5404. const front = pathGetFront(path);
  5405. if (front === null) {
  5406. return this;
  5407. }
  5408. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5409. }
  5410. /** @inheritDoc */
  5411. hasChild(childName) {
  5412. return this.children_.get(childName) !== null;
  5413. }
  5414. /** @inheritDoc */
  5415. updateImmediateChild(childName, newChildNode) {
  5416. assert(newChildNode, 'We should always be passing snapshot nodes');
  5417. if (childName === '.priority') {
  5418. return this.updatePriority(newChildNode);
  5419. }
  5420. else {
  5421. const namedNode = new NamedNode(childName, newChildNode);
  5422. let newChildren, newIndexMap;
  5423. if (newChildNode.isEmpty()) {
  5424. newChildren = this.children_.remove(childName);
  5425. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5426. }
  5427. else {
  5428. newChildren = this.children_.insert(childName, newChildNode);
  5429. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5430. }
  5431. const newPriority = newChildren.isEmpty()
  5432. ? EMPTY_NODE
  5433. : this.priorityNode_;
  5434. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5435. }
  5436. }
  5437. /** @inheritDoc */
  5438. updateChild(path, newChildNode) {
  5439. const front = pathGetFront(path);
  5440. if (front === null) {
  5441. return newChildNode;
  5442. }
  5443. else {
  5444. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5445. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5446. return this.updateImmediateChild(front, newImmediateChild);
  5447. }
  5448. }
  5449. /** @inheritDoc */
  5450. isEmpty() {
  5451. return this.children_.isEmpty();
  5452. }
  5453. /** @inheritDoc */
  5454. numChildren() {
  5455. return this.children_.count();
  5456. }
  5457. /** @inheritDoc */
  5458. val(exportFormat) {
  5459. if (this.isEmpty()) {
  5460. return null;
  5461. }
  5462. const obj = {};
  5463. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5464. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5465. obj[key] = childNode.val(exportFormat);
  5466. numKeys++;
  5467. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5468. maxKey = Math.max(maxKey, Number(key));
  5469. }
  5470. else {
  5471. allIntegerKeys = false;
  5472. }
  5473. });
  5474. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5475. // convert to array.
  5476. const array = [];
  5477. // eslint-disable-next-line guard-for-in
  5478. for (const key in obj) {
  5479. array[key] = obj[key];
  5480. }
  5481. return array;
  5482. }
  5483. else {
  5484. if (exportFormat && !this.getPriority().isEmpty()) {
  5485. obj['.priority'] = this.getPriority().val();
  5486. }
  5487. return obj;
  5488. }
  5489. }
  5490. /** @inheritDoc */
  5491. hash() {
  5492. if (this.lazyHash_ === null) {
  5493. let toHash = '';
  5494. if (!this.getPriority().isEmpty()) {
  5495. toHash +=
  5496. 'priority:' +
  5497. priorityHashText(this.getPriority().val()) +
  5498. ':';
  5499. }
  5500. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5501. const childHash = childNode.hash();
  5502. if (childHash !== '') {
  5503. toHash += ':' + key + ':' + childHash;
  5504. }
  5505. });
  5506. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5507. }
  5508. return this.lazyHash_;
  5509. }
  5510. /** @inheritDoc */
  5511. getPredecessorChildName(childName, childNode, index) {
  5512. const idx = this.resolveIndex_(index);
  5513. if (idx) {
  5514. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5515. return predecessor ? predecessor.name : null;
  5516. }
  5517. else {
  5518. return this.children_.getPredecessorKey(childName);
  5519. }
  5520. }
  5521. getFirstChildName(indexDefinition) {
  5522. const idx = this.resolveIndex_(indexDefinition);
  5523. if (idx) {
  5524. const minKey = idx.minKey();
  5525. return minKey && minKey.name;
  5526. }
  5527. else {
  5528. return this.children_.minKey();
  5529. }
  5530. }
  5531. getFirstChild(indexDefinition) {
  5532. const minKey = this.getFirstChildName(indexDefinition);
  5533. if (minKey) {
  5534. return new NamedNode(minKey, this.children_.get(minKey));
  5535. }
  5536. else {
  5537. return null;
  5538. }
  5539. }
  5540. /**
  5541. * Given an index, return the key name of the largest value we have, according to that index
  5542. */
  5543. getLastChildName(indexDefinition) {
  5544. const idx = this.resolveIndex_(indexDefinition);
  5545. if (idx) {
  5546. const maxKey = idx.maxKey();
  5547. return maxKey && maxKey.name;
  5548. }
  5549. else {
  5550. return this.children_.maxKey();
  5551. }
  5552. }
  5553. getLastChild(indexDefinition) {
  5554. const maxKey = this.getLastChildName(indexDefinition);
  5555. if (maxKey) {
  5556. return new NamedNode(maxKey, this.children_.get(maxKey));
  5557. }
  5558. else {
  5559. return null;
  5560. }
  5561. }
  5562. forEachChild(index, action) {
  5563. const idx = this.resolveIndex_(index);
  5564. if (idx) {
  5565. return idx.inorderTraversal(wrappedNode => {
  5566. return action(wrappedNode.name, wrappedNode.node);
  5567. });
  5568. }
  5569. else {
  5570. return this.children_.inorderTraversal(action);
  5571. }
  5572. }
  5573. getIterator(indexDefinition) {
  5574. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5575. }
  5576. getIteratorFrom(startPost, indexDefinition) {
  5577. const idx = this.resolveIndex_(indexDefinition);
  5578. if (idx) {
  5579. return idx.getIteratorFrom(startPost, key => key);
  5580. }
  5581. else {
  5582. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5583. let next = iterator.peek();
  5584. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5585. iterator.getNext();
  5586. next = iterator.peek();
  5587. }
  5588. return iterator;
  5589. }
  5590. }
  5591. getReverseIterator(indexDefinition) {
  5592. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5593. }
  5594. getReverseIteratorFrom(endPost, indexDefinition) {
  5595. const idx = this.resolveIndex_(indexDefinition);
  5596. if (idx) {
  5597. return idx.getReverseIteratorFrom(endPost, key => {
  5598. return key;
  5599. });
  5600. }
  5601. else {
  5602. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5603. let next = iterator.peek();
  5604. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5605. iterator.getNext();
  5606. next = iterator.peek();
  5607. }
  5608. return iterator;
  5609. }
  5610. }
  5611. compareTo(other) {
  5612. if (this.isEmpty()) {
  5613. if (other.isEmpty()) {
  5614. return 0;
  5615. }
  5616. else {
  5617. return -1;
  5618. }
  5619. }
  5620. else if (other.isLeafNode() || other.isEmpty()) {
  5621. return 1;
  5622. }
  5623. else if (other === MAX_NODE) {
  5624. return -1;
  5625. }
  5626. else {
  5627. // Must be another node with children.
  5628. return 0;
  5629. }
  5630. }
  5631. withIndex(indexDefinition) {
  5632. if (indexDefinition === KEY_INDEX ||
  5633. this.indexMap_.hasIndex(indexDefinition)) {
  5634. return this;
  5635. }
  5636. else {
  5637. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5638. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5639. }
  5640. }
  5641. isIndexed(index) {
  5642. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5643. }
  5644. equals(other) {
  5645. if (other === this) {
  5646. return true;
  5647. }
  5648. else if (other.isLeafNode()) {
  5649. return false;
  5650. }
  5651. else {
  5652. const otherChildrenNode = other;
  5653. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5654. return false;
  5655. }
  5656. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5657. const thisIter = this.getIterator(PRIORITY_INDEX);
  5658. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5659. let thisCurrent = thisIter.getNext();
  5660. let otherCurrent = otherIter.getNext();
  5661. while (thisCurrent && otherCurrent) {
  5662. if (thisCurrent.name !== otherCurrent.name ||
  5663. !thisCurrent.node.equals(otherCurrent.node)) {
  5664. return false;
  5665. }
  5666. thisCurrent = thisIter.getNext();
  5667. otherCurrent = otherIter.getNext();
  5668. }
  5669. return thisCurrent === null && otherCurrent === null;
  5670. }
  5671. else {
  5672. return false;
  5673. }
  5674. }
  5675. }
  5676. /**
  5677. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5678. * instead.
  5679. *
  5680. */
  5681. resolveIndex_(indexDefinition) {
  5682. if (indexDefinition === KEY_INDEX) {
  5683. return null;
  5684. }
  5685. else {
  5686. return this.indexMap_.get(indexDefinition.toString());
  5687. }
  5688. }
  5689. }
  5690. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5691. class MaxNode extends ChildrenNode {
  5692. constructor() {
  5693. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5694. }
  5695. compareTo(other) {
  5696. if (other === this) {
  5697. return 0;
  5698. }
  5699. else {
  5700. return 1;
  5701. }
  5702. }
  5703. equals(other) {
  5704. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5705. return other === this;
  5706. }
  5707. getPriority() {
  5708. return this;
  5709. }
  5710. getImmediateChild(childName) {
  5711. return ChildrenNode.EMPTY_NODE;
  5712. }
  5713. isEmpty() {
  5714. return false;
  5715. }
  5716. }
  5717. /**
  5718. * Marker that will sort higher than any other snapshot.
  5719. */
  5720. const MAX_NODE = new MaxNode();
  5721. Object.defineProperties(NamedNode, {
  5722. MIN: {
  5723. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5724. },
  5725. MAX: {
  5726. value: new NamedNode(MAX_NAME, MAX_NODE)
  5727. }
  5728. });
  5729. /**
  5730. * Reference Extensions
  5731. */
  5732. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5733. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5734. setMaxNode$1(MAX_NODE);
  5735. setMaxNode(MAX_NODE);
  5736. /**
  5737. * @license
  5738. * Copyright 2017 Google LLC
  5739. *
  5740. * Licensed under the Apache License, Version 2.0 (the "License");
  5741. * you may not use this file except in compliance with the License.
  5742. * You may obtain a copy of the License at
  5743. *
  5744. * http://www.apache.org/licenses/LICENSE-2.0
  5745. *
  5746. * Unless required by applicable law or agreed to in writing, software
  5747. * distributed under the License is distributed on an "AS IS" BASIS,
  5748. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5749. * See the License for the specific language governing permissions and
  5750. * limitations under the License.
  5751. */
  5752. const USE_HINZE = true;
  5753. /**
  5754. * Constructs a snapshot node representing the passed JSON and returns it.
  5755. * @param json - JSON to create a node for.
  5756. * @param priority - Optional priority to use. This will be ignored if the
  5757. * passed JSON contains a .priority property.
  5758. */
  5759. function nodeFromJSON(json, priority = null) {
  5760. if (json === null) {
  5761. return ChildrenNode.EMPTY_NODE;
  5762. }
  5763. if (typeof json === 'object' && '.priority' in json) {
  5764. priority = json['.priority'];
  5765. }
  5766. assert(priority === null ||
  5767. typeof priority === 'string' ||
  5768. typeof priority === 'number' ||
  5769. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5770. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5771. json = json['.value'];
  5772. }
  5773. // Valid leaf nodes include non-objects or server-value wrapper objects
  5774. if (typeof json !== 'object' || '.sv' in json) {
  5775. const jsonLeaf = json;
  5776. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5777. }
  5778. if (!(json instanceof Array) && USE_HINZE) {
  5779. const children = [];
  5780. let childrenHavePriority = false;
  5781. const hinzeJsonObj = json;
  5782. each(hinzeJsonObj, (key, child) => {
  5783. if (key.substring(0, 1) !== '.') {
  5784. // Ignore metadata nodes
  5785. const childNode = nodeFromJSON(child);
  5786. if (!childNode.isEmpty()) {
  5787. childrenHavePriority =
  5788. childrenHavePriority || !childNode.getPriority().isEmpty();
  5789. children.push(new NamedNode(key, childNode));
  5790. }
  5791. }
  5792. });
  5793. if (children.length === 0) {
  5794. return ChildrenNode.EMPTY_NODE;
  5795. }
  5796. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5797. if (childrenHavePriority) {
  5798. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5799. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5800. }
  5801. else {
  5802. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5803. }
  5804. }
  5805. else {
  5806. let node = ChildrenNode.EMPTY_NODE;
  5807. each(json, (key, childData) => {
  5808. if (contains(json, key)) {
  5809. if (key.substring(0, 1) !== '.') {
  5810. // ignore metadata nodes.
  5811. const childNode = nodeFromJSON(childData);
  5812. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5813. node = node.updateImmediateChild(key, childNode);
  5814. }
  5815. }
  5816. }
  5817. });
  5818. return node.updatePriority(nodeFromJSON(priority));
  5819. }
  5820. }
  5821. setNodeFromJSON(nodeFromJSON);
  5822. /**
  5823. * @license
  5824. * Copyright 2017 Google LLC
  5825. *
  5826. * Licensed under the Apache License, Version 2.0 (the "License");
  5827. * you may not use this file except in compliance with the License.
  5828. * You may obtain a copy of the License at
  5829. *
  5830. * http://www.apache.org/licenses/LICENSE-2.0
  5831. *
  5832. * Unless required by applicable law or agreed to in writing, software
  5833. * distributed under the License is distributed on an "AS IS" BASIS,
  5834. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5835. * See the License for the specific language governing permissions and
  5836. * limitations under the License.
  5837. */
  5838. class PathIndex extends Index {
  5839. constructor(indexPath_) {
  5840. super();
  5841. this.indexPath_ = indexPath_;
  5842. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5843. }
  5844. extractChild(snap) {
  5845. return snap.getChild(this.indexPath_);
  5846. }
  5847. isDefinedOn(node) {
  5848. return !node.getChild(this.indexPath_).isEmpty();
  5849. }
  5850. compare(a, b) {
  5851. const aChild = this.extractChild(a.node);
  5852. const bChild = this.extractChild(b.node);
  5853. const indexCmp = aChild.compareTo(bChild);
  5854. if (indexCmp === 0) {
  5855. return nameCompare(a.name, b.name);
  5856. }
  5857. else {
  5858. return indexCmp;
  5859. }
  5860. }
  5861. makePost(indexValue, name) {
  5862. const valueNode = nodeFromJSON(indexValue);
  5863. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5864. return new NamedNode(name, node);
  5865. }
  5866. maxPost() {
  5867. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5868. return new NamedNode(MAX_NAME, node);
  5869. }
  5870. toString() {
  5871. return pathSlice(this.indexPath_, 0).join('/');
  5872. }
  5873. }
  5874. /**
  5875. * @license
  5876. * Copyright 2017 Google LLC
  5877. *
  5878. * Licensed under the Apache License, Version 2.0 (the "License");
  5879. * you may not use this file except in compliance with the License.
  5880. * You may obtain a copy of the License at
  5881. *
  5882. * http://www.apache.org/licenses/LICENSE-2.0
  5883. *
  5884. * Unless required by applicable law or agreed to in writing, software
  5885. * distributed under the License is distributed on an "AS IS" BASIS,
  5886. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5887. * See the License for the specific language governing permissions and
  5888. * limitations under the License.
  5889. */
  5890. class ValueIndex extends Index {
  5891. compare(a, b) {
  5892. const indexCmp = a.node.compareTo(b.node);
  5893. if (indexCmp === 0) {
  5894. return nameCompare(a.name, b.name);
  5895. }
  5896. else {
  5897. return indexCmp;
  5898. }
  5899. }
  5900. isDefinedOn(node) {
  5901. return true;
  5902. }
  5903. indexedValueChanged(oldNode, newNode) {
  5904. return !oldNode.equals(newNode);
  5905. }
  5906. minPost() {
  5907. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5908. return NamedNode.MIN;
  5909. }
  5910. maxPost() {
  5911. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5912. return NamedNode.MAX;
  5913. }
  5914. makePost(indexValue, name) {
  5915. const valueNode = nodeFromJSON(indexValue);
  5916. return new NamedNode(name, valueNode);
  5917. }
  5918. /**
  5919. * @returns String representation for inclusion in a query spec
  5920. */
  5921. toString() {
  5922. return '.value';
  5923. }
  5924. }
  5925. const VALUE_INDEX = new ValueIndex();
  5926. /**
  5927. * @license
  5928. * Copyright 2017 Google LLC
  5929. *
  5930. * Licensed under the Apache License, Version 2.0 (the "License");
  5931. * you may not use this file except in compliance with the License.
  5932. * You may obtain a copy of the License at
  5933. *
  5934. * http://www.apache.org/licenses/LICENSE-2.0
  5935. *
  5936. * Unless required by applicable law or agreed to in writing, software
  5937. * distributed under the License is distributed on an "AS IS" BASIS,
  5938. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5939. * See the License for the specific language governing permissions and
  5940. * limitations under the License.
  5941. */
  5942. function changeValue(snapshotNode) {
  5943. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5944. }
  5945. function changeChildAdded(childName, snapshotNode) {
  5946. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5947. }
  5948. function changeChildRemoved(childName, snapshotNode) {
  5949. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5950. }
  5951. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5952. return {
  5953. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5954. snapshotNode,
  5955. childName,
  5956. oldSnap
  5957. };
  5958. }
  5959. function changeChildMoved(childName, snapshotNode) {
  5960. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5961. }
  5962. /**
  5963. * @license
  5964. * Copyright 2017 Google LLC
  5965. *
  5966. * Licensed under the Apache License, Version 2.0 (the "License");
  5967. * you may not use this file except in compliance with the License.
  5968. * You may obtain a copy of the License at
  5969. *
  5970. * http://www.apache.org/licenses/LICENSE-2.0
  5971. *
  5972. * Unless required by applicable law or agreed to in writing, software
  5973. * distributed under the License is distributed on an "AS IS" BASIS,
  5974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5975. * See the License for the specific language governing permissions and
  5976. * limitations under the License.
  5977. */
  5978. /**
  5979. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5980. */
  5981. class IndexedFilter {
  5982. constructor(index_) {
  5983. this.index_ = index_;
  5984. }
  5985. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5986. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5987. const oldChild = snap.getImmediateChild(key);
  5988. // Check if anything actually changed.
  5989. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5990. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5991. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5992. // to avoid treating these cases as "nothing changed."
  5993. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5994. // Nothing changed.
  5995. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5996. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5997. return snap;
  5998. }
  5999. }
  6000. if (optChangeAccumulator != null) {
  6001. if (newChild.isEmpty()) {
  6002. if (snap.hasChild(key)) {
  6003. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6004. }
  6005. else {
  6006. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6007. }
  6008. }
  6009. else if (oldChild.isEmpty()) {
  6010. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6011. }
  6012. else {
  6013. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6014. }
  6015. }
  6016. if (snap.isLeafNode() && newChild.isEmpty()) {
  6017. return snap;
  6018. }
  6019. else {
  6020. // Make sure the node is indexed
  6021. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6022. }
  6023. }
  6024. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6025. if (optChangeAccumulator != null) {
  6026. if (!oldSnap.isLeafNode()) {
  6027. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6028. if (!newSnap.hasChild(key)) {
  6029. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6030. }
  6031. });
  6032. }
  6033. if (!newSnap.isLeafNode()) {
  6034. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6035. if (oldSnap.hasChild(key)) {
  6036. const oldChild = oldSnap.getImmediateChild(key);
  6037. if (!oldChild.equals(childNode)) {
  6038. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6039. }
  6040. }
  6041. else {
  6042. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6043. }
  6044. });
  6045. }
  6046. }
  6047. return newSnap.withIndex(this.index_);
  6048. }
  6049. updatePriority(oldSnap, newPriority) {
  6050. if (oldSnap.isEmpty()) {
  6051. return ChildrenNode.EMPTY_NODE;
  6052. }
  6053. else {
  6054. return oldSnap.updatePriority(newPriority);
  6055. }
  6056. }
  6057. filtersNodes() {
  6058. return false;
  6059. }
  6060. getIndexedFilter() {
  6061. return this;
  6062. }
  6063. getIndex() {
  6064. return this.index_;
  6065. }
  6066. }
  6067. /**
  6068. * @license
  6069. * Copyright 2017 Google LLC
  6070. *
  6071. * Licensed under the Apache License, Version 2.0 (the "License");
  6072. * you may not use this file except in compliance with the License.
  6073. * You may obtain a copy of the License at
  6074. *
  6075. * http://www.apache.org/licenses/LICENSE-2.0
  6076. *
  6077. * Unless required by applicable law or agreed to in writing, software
  6078. * distributed under the License is distributed on an "AS IS" BASIS,
  6079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6080. * See the License for the specific language governing permissions and
  6081. * limitations under the License.
  6082. */
  6083. /**
  6084. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6085. */
  6086. class RangedFilter {
  6087. constructor(params) {
  6088. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6089. this.index_ = params.getIndex();
  6090. this.startPost_ = RangedFilter.getStartPost_(params);
  6091. this.endPost_ = RangedFilter.getEndPost_(params);
  6092. this.startIsInclusive_ = !params.startAfterSet_;
  6093. this.endIsInclusive_ = !params.endBeforeSet_;
  6094. }
  6095. getStartPost() {
  6096. return this.startPost_;
  6097. }
  6098. getEndPost() {
  6099. return this.endPost_;
  6100. }
  6101. matches(node) {
  6102. const isWithinStart = this.startIsInclusive_
  6103. ? this.index_.compare(this.getStartPost(), node) <= 0
  6104. : this.index_.compare(this.getStartPost(), node) < 0;
  6105. const isWithinEnd = this.endIsInclusive_
  6106. ? this.index_.compare(node, this.getEndPost()) <= 0
  6107. : this.index_.compare(node, this.getEndPost()) < 0;
  6108. return isWithinStart && isWithinEnd;
  6109. }
  6110. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6111. if (!this.matches(new NamedNode(key, newChild))) {
  6112. newChild = ChildrenNode.EMPTY_NODE;
  6113. }
  6114. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6115. }
  6116. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6117. if (newSnap.isLeafNode()) {
  6118. // Make sure we have a children node with the correct index, not a leaf node;
  6119. newSnap = ChildrenNode.EMPTY_NODE;
  6120. }
  6121. let filtered = newSnap.withIndex(this.index_);
  6122. // Don't support priorities on queries
  6123. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6124. const self = this;
  6125. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6126. if (!self.matches(new NamedNode(key, childNode))) {
  6127. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6128. }
  6129. });
  6130. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6131. }
  6132. updatePriority(oldSnap, newPriority) {
  6133. // Don't support priorities on queries
  6134. return oldSnap;
  6135. }
  6136. filtersNodes() {
  6137. return true;
  6138. }
  6139. getIndexedFilter() {
  6140. return this.indexedFilter_;
  6141. }
  6142. getIndex() {
  6143. return this.index_;
  6144. }
  6145. static getStartPost_(params) {
  6146. if (params.hasStart()) {
  6147. const startName = params.getIndexStartName();
  6148. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6149. }
  6150. else {
  6151. return params.getIndex().minPost();
  6152. }
  6153. }
  6154. static getEndPost_(params) {
  6155. if (params.hasEnd()) {
  6156. const endName = params.getIndexEndName();
  6157. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6158. }
  6159. else {
  6160. return params.getIndex().maxPost();
  6161. }
  6162. }
  6163. }
  6164. /**
  6165. * @license
  6166. * Copyright 2017 Google LLC
  6167. *
  6168. * Licensed under the Apache License, Version 2.0 (the "License");
  6169. * you may not use this file except in compliance with the License.
  6170. * You may obtain a copy of the License at
  6171. *
  6172. * http://www.apache.org/licenses/LICENSE-2.0
  6173. *
  6174. * Unless required by applicable law or agreed to in writing, software
  6175. * distributed under the License is distributed on an "AS IS" BASIS,
  6176. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6177. * See the License for the specific language governing permissions and
  6178. * limitations under the License.
  6179. */
  6180. /**
  6181. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6182. */
  6183. class LimitedFilter {
  6184. constructor(params) {
  6185. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6186. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6187. this.withinStartPost = (node) => {
  6188. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6189. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6190. };
  6191. this.withinEndPost = (node) => {
  6192. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6193. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6194. };
  6195. this.rangedFilter_ = new RangedFilter(params);
  6196. this.index_ = params.getIndex();
  6197. this.limit_ = params.getLimit();
  6198. this.reverse_ = !params.isViewFromLeft();
  6199. this.startIsInclusive_ = !params.startAfterSet_;
  6200. this.endIsInclusive_ = !params.endBeforeSet_;
  6201. }
  6202. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6203. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6204. newChild = ChildrenNode.EMPTY_NODE;
  6205. }
  6206. if (snap.getImmediateChild(key).equals(newChild)) {
  6207. // No change
  6208. return snap;
  6209. }
  6210. else if (snap.numChildren() < this.limit_) {
  6211. return this.rangedFilter_
  6212. .getIndexedFilter()
  6213. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6214. }
  6215. else {
  6216. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6217. }
  6218. }
  6219. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6220. let filtered;
  6221. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6222. // Make sure we have a children node with the correct index, not a leaf node;
  6223. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6224. }
  6225. else {
  6226. if (this.limit_ * 2 < newSnap.numChildren() &&
  6227. newSnap.isIndexed(this.index_)) {
  6228. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6229. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6230. // anchor to the startPost, endPost, or last element as appropriate
  6231. let iterator;
  6232. if (this.reverse_) {
  6233. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6234. }
  6235. else {
  6236. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6237. }
  6238. let count = 0;
  6239. while (iterator.hasNext() && count < this.limit_) {
  6240. const next = iterator.getNext();
  6241. if (!this.withinDirectionalStart(next)) {
  6242. // if we have not reached the start, skip to the next element
  6243. continue;
  6244. }
  6245. else if (!this.withinDirectionalEnd(next)) {
  6246. // if we have reached the end, stop adding elements
  6247. break;
  6248. }
  6249. else {
  6250. filtered = filtered.updateImmediateChild(next.name, next.node);
  6251. count++;
  6252. }
  6253. }
  6254. }
  6255. else {
  6256. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6257. filtered = newSnap.withIndex(this.index_);
  6258. // Don't support priorities on queries
  6259. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6260. let iterator;
  6261. if (this.reverse_) {
  6262. iterator = filtered.getReverseIterator(this.index_);
  6263. }
  6264. else {
  6265. iterator = filtered.getIterator(this.index_);
  6266. }
  6267. let count = 0;
  6268. while (iterator.hasNext()) {
  6269. const next = iterator.getNext();
  6270. const inRange = count < this.limit_ &&
  6271. this.withinDirectionalStart(next) &&
  6272. this.withinDirectionalEnd(next);
  6273. if (inRange) {
  6274. count++;
  6275. }
  6276. else {
  6277. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6278. }
  6279. }
  6280. }
  6281. }
  6282. return this.rangedFilter_
  6283. .getIndexedFilter()
  6284. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6285. }
  6286. updatePriority(oldSnap, newPriority) {
  6287. // Don't support priorities on queries
  6288. return oldSnap;
  6289. }
  6290. filtersNodes() {
  6291. return true;
  6292. }
  6293. getIndexedFilter() {
  6294. return this.rangedFilter_.getIndexedFilter();
  6295. }
  6296. getIndex() {
  6297. return this.index_;
  6298. }
  6299. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6300. // TODO: rename all cache stuff etc to general snap terminology
  6301. let cmp;
  6302. if (this.reverse_) {
  6303. const indexCmp = this.index_.getCompare();
  6304. cmp = (a, b) => indexCmp(b, a);
  6305. }
  6306. else {
  6307. cmp = this.index_.getCompare();
  6308. }
  6309. const oldEventCache = snap;
  6310. assert(oldEventCache.numChildren() === this.limit_, '');
  6311. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6312. const windowBoundary = this.reverse_
  6313. ? oldEventCache.getFirstChild(this.index_)
  6314. : oldEventCache.getLastChild(this.index_);
  6315. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6316. if (oldEventCache.hasChild(childKey)) {
  6317. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6318. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6319. while (nextChild != null &&
  6320. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6321. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6322. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6323. // the limited filter...
  6324. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6325. }
  6326. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6327. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6328. if (remainsInWindow) {
  6329. if (changeAccumulator != null) {
  6330. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6331. }
  6332. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6333. }
  6334. else {
  6335. if (changeAccumulator != null) {
  6336. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6337. }
  6338. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6339. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6340. if (nextChildInRange) {
  6341. if (changeAccumulator != null) {
  6342. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6343. }
  6344. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6345. }
  6346. else {
  6347. return newEventCache;
  6348. }
  6349. }
  6350. }
  6351. else if (childSnap.isEmpty()) {
  6352. // we're deleting a node, but it was not in the window, so ignore it
  6353. return snap;
  6354. }
  6355. else if (inRange) {
  6356. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6357. if (changeAccumulator != null) {
  6358. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6359. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6360. }
  6361. return oldEventCache
  6362. .updateImmediateChild(childKey, childSnap)
  6363. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6364. }
  6365. else {
  6366. return snap;
  6367. }
  6368. }
  6369. else {
  6370. return snap;
  6371. }
  6372. }
  6373. }
  6374. /**
  6375. * @license
  6376. * Copyright 2017 Google LLC
  6377. *
  6378. * Licensed under the Apache License, Version 2.0 (the "License");
  6379. * you may not use this file except in compliance with the License.
  6380. * You may obtain a copy of the License at
  6381. *
  6382. * http://www.apache.org/licenses/LICENSE-2.0
  6383. *
  6384. * Unless required by applicable law or agreed to in writing, software
  6385. * distributed under the License is distributed on an "AS IS" BASIS,
  6386. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6387. * See the License for the specific language governing permissions and
  6388. * limitations under the License.
  6389. */
  6390. /**
  6391. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6392. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6393. * user-facing API level, so it is not done here.
  6394. *
  6395. * @internal
  6396. */
  6397. class QueryParams {
  6398. constructor() {
  6399. this.limitSet_ = false;
  6400. this.startSet_ = false;
  6401. this.startNameSet_ = false;
  6402. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6403. this.endSet_ = false;
  6404. this.endNameSet_ = false;
  6405. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6406. this.limit_ = 0;
  6407. this.viewFrom_ = '';
  6408. this.indexStartValue_ = null;
  6409. this.indexStartName_ = '';
  6410. this.indexEndValue_ = null;
  6411. this.indexEndName_ = '';
  6412. this.index_ = PRIORITY_INDEX;
  6413. }
  6414. hasStart() {
  6415. return this.startSet_;
  6416. }
  6417. /**
  6418. * @returns True if it would return from left.
  6419. */
  6420. isViewFromLeft() {
  6421. if (this.viewFrom_ === '') {
  6422. // limit(), rather than limitToFirst or limitToLast was called.
  6423. // This means that only one of startSet_ and endSet_ is true. Use them
  6424. // to calculate which side of the view to anchor to. If neither is set,
  6425. // anchor to the end.
  6426. return this.startSet_;
  6427. }
  6428. else {
  6429. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6430. }
  6431. }
  6432. /**
  6433. * Only valid to call if hasStart() returns true
  6434. */
  6435. getIndexStartValue() {
  6436. assert(this.startSet_, 'Only valid if start has been set');
  6437. return this.indexStartValue_;
  6438. }
  6439. /**
  6440. * Only valid to call if hasStart() returns true.
  6441. * Returns the starting key name for the range defined by these query parameters
  6442. */
  6443. getIndexStartName() {
  6444. assert(this.startSet_, 'Only valid if start has been set');
  6445. if (this.startNameSet_) {
  6446. return this.indexStartName_;
  6447. }
  6448. else {
  6449. return MIN_NAME;
  6450. }
  6451. }
  6452. hasEnd() {
  6453. return this.endSet_;
  6454. }
  6455. /**
  6456. * Only valid to call if hasEnd() returns true.
  6457. */
  6458. getIndexEndValue() {
  6459. assert(this.endSet_, 'Only valid if end has been set');
  6460. return this.indexEndValue_;
  6461. }
  6462. /**
  6463. * Only valid to call if hasEnd() returns true.
  6464. * Returns the end key name for the range defined by these query parameters
  6465. */
  6466. getIndexEndName() {
  6467. assert(this.endSet_, 'Only valid if end has been set');
  6468. if (this.endNameSet_) {
  6469. return this.indexEndName_;
  6470. }
  6471. else {
  6472. return MAX_NAME;
  6473. }
  6474. }
  6475. hasLimit() {
  6476. return this.limitSet_;
  6477. }
  6478. /**
  6479. * @returns True if a limit has been set and it has been explicitly anchored
  6480. */
  6481. hasAnchoredLimit() {
  6482. return this.limitSet_ && this.viewFrom_ !== '';
  6483. }
  6484. /**
  6485. * Only valid to call if hasLimit() returns true
  6486. */
  6487. getLimit() {
  6488. assert(this.limitSet_, 'Only valid if limit has been set');
  6489. return this.limit_;
  6490. }
  6491. getIndex() {
  6492. return this.index_;
  6493. }
  6494. loadsAllData() {
  6495. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6496. }
  6497. isDefault() {
  6498. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6499. }
  6500. copy() {
  6501. const copy = new QueryParams();
  6502. copy.limitSet_ = this.limitSet_;
  6503. copy.limit_ = this.limit_;
  6504. copy.startSet_ = this.startSet_;
  6505. copy.startAfterSet_ = this.startAfterSet_;
  6506. copy.indexStartValue_ = this.indexStartValue_;
  6507. copy.startNameSet_ = this.startNameSet_;
  6508. copy.indexStartName_ = this.indexStartName_;
  6509. copy.endSet_ = this.endSet_;
  6510. copy.endBeforeSet_ = this.endBeforeSet_;
  6511. copy.indexEndValue_ = this.indexEndValue_;
  6512. copy.endNameSet_ = this.endNameSet_;
  6513. copy.indexEndName_ = this.indexEndName_;
  6514. copy.index_ = this.index_;
  6515. copy.viewFrom_ = this.viewFrom_;
  6516. return copy;
  6517. }
  6518. }
  6519. function queryParamsGetNodeFilter(queryParams) {
  6520. if (queryParams.loadsAllData()) {
  6521. return new IndexedFilter(queryParams.getIndex());
  6522. }
  6523. else if (queryParams.hasLimit()) {
  6524. return new LimitedFilter(queryParams);
  6525. }
  6526. else {
  6527. return new RangedFilter(queryParams);
  6528. }
  6529. }
  6530. function queryParamsLimitToFirst(queryParams, newLimit) {
  6531. const newParams = queryParams.copy();
  6532. newParams.limitSet_ = true;
  6533. newParams.limit_ = newLimit;
  6534. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6535. return newParams;
  6536. }
  6537. function queryParamsLimitToLast(queryParams, newLimit) {
  6538. const newParams = queryParams.copy();
  6539. newParams.limitSet_ = true;
  6540. newParams.limit_ = newLimit;
  6541. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6542. return newParams;
  6543. }
  6544. function queryParamsStartAt(queryParams, indexValue, key) {
  6545. const newParams = queryParams.copy();
  6546. newParams.startSet_ = true;
  6547. if (indexValue === undefined) {
  6548. indexValue = null;
  6549. }
  6550. newParams.indexStartValue_ = indexValue;
  6551. if (key != null) {
  6552. newParams.startNameSet_ = true;
  6553. newParams.indexStartName_ = key;
  6554. }
  6555. else {
  6556. newParams.startNameSet_ = false;
  6557. newParams.indexStartName_ = '';
  6558. }
  6559. return newParams;
  6560. }
  6561. function queryParamsStartAfter(queryParams, indexValue, key) {
  6562. let params;
  6563. if (queryParams.index_ === KEY_INDEX || !!key) {
  6564. params = queryParamsStartAt(queryParams, indexValue, key);
  6565. }
  6566. else {
  6567. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6568. }
  6569. params.startAfterSet_ = true;
  6570. return params;
  6571. }
  6572. function queryParamsEndAt(queryParams, indexValue, key) {
  6573. const newParams = queryParams.copy();
  6574. newParams.endSet_ = true;
  6575. if (indexValue === undefined) {
  6576. indexValue = null;
  6577. }
  6578. newParams.indexEndValue_ = indexValue;
  6579. if (key !== undefined) {
  6580. newParams.endNameSet_ = true;
  6581. newParams.indexEndName_ = key;
  6582. }
  6583. else {
  6584. newParams.endNameSet_ = false;
  6585. newParams.indexEndName_ = '';
  6586. }
  6587. return newParams;
  6588. }
  6589. function queryParamsEndBefore(queryParams, indexValue, key) {
  6590. let params;
  6591. if (queryParams.index_ === KEY_INDEX || !!key) {
  6592. params = queryParamsEndAt(queryParams, indexValue, key);
  6593. }
  6594. else {
  6595. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6596. }
  6597. params.endBeforeSet_ = true;
  6598. return params;
  6599. }
  6600. function queryParamsOrderBy(queryParams, index) {
  6601. const newParams = queryParams.copy();
  6602. newParams.index_ = index;
  6603. return newParams;
  6604. }
  6605. /**
  6606. * Returns a set of REST query string parameters representing this query.
  6607. *
  6608. * @returns query string parameters
  6609. */
  6610. function queryParamsToRestQueryStringParameters(queryParams) {
  6611. const qs = {};
  6612. if (queryParams.isDefault()) {
  6613. return qs;
  6614. }
  6615. let orderBy;
  6616. if (queryParams.index_ === PRIORITY_INDEX) {
  6617. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6618. }
  6619. else if (queryParams.index_ === VALUE_INDEX) {
  6620. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6621. }
  6622. else if (queryParams.index_ === KEY_INDEX) {
  6623. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6624. }
  6625. else {
  6626. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6627. orderBy = queryParams.index_.toString();
  6628. }
  6629. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6630. if (queryParams.startSet_) {
  6631. const startParam = queryParams.startAfterSet_
  6632. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6633. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6634. qs[startParam] = stringify(queryParams.indexStartValue_);
  6635. if (queryParams.startNameSet_) {
  6636. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6637. }
  6638. }
  6639. if (queryParams.endSet_) {
  6640. const endParam = queryParams.endBeforeSet_
  6641. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6642. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6643. qs[endParam] = stringify(queryParams.indexEndValue_);
  6644. if (queryParams.endNameSet_) {
  6645. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6646. }
  6647. }
  6648. if (queryParams.limitSet_) {
  6649. if (queryParams.isViewFromLeft()) {
  6650. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6651. }
  6652. else {
  6653. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6654. }
  6655. }
  6656. return qs;
  6657. }
  6658. function queryParamsGetQueryObject(queryParams) {
  6659. const obj = {};
  6660. if (queryParams.startSet_) {
  6661. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6662. queryParams.indexStartValue_;
  6663. if (queryParams.startNameSet_) {
  6664. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6665. queryParams.indexStartName_;
  6666. }
  6667. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6668. !queryParams.startAfterSet_;
  6669. }
  6670. if (queryParams.endSet_) {
  6671. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6672. if (queryParams.endNameSet_) {
  6673. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6674. }
  6675. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6676. !queryParams.endBeforeSet_;
  6677. }
  6678. if (queryParams.limitSet_) {
  6679. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6680. let viewFrom = queryParams.viewFrom_;
  6681. if (viewFrom === '') {
  6682. if (queryParams.isViewFromLeft()) {
  6683. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6684. }
  6685. else {
  6686. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6687. }
  6688. }
  6689. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6690. }
  6691. // For now, priority index is the default, so we only specify if it's some other index
  6692. if (queryParams.index_ !== PRIORITY_INDEX) {
  6693. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6694. }
  6695. return obj;
  6696. }
  6697. /**
  6698. * @license
  6699. * Copyright 2017 Google LLC
  6700. *
  6701. * Licensed under the Apache License, Version 2.0 (the "License");
  6702. * you may not use this file except in compliance with the License.
  6703. * You may obtain a copy of the License at
  6704. *
  6705. * http://www.apache.org/licenses/LICENSE-2.0
  6706. *
  6707. * Unless required by applicable law or agreed to in writing, software
  6708. * distributed under the License is distributed on an "AS IS" BASIS,
  6709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6710. * See the License for the specific language governing permissions and
  6711. * limitations under the License.
  6712. */
  6713. /**
  6714. * An implementation of ServerActions that communicates with the server via REST requests.
  6715. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6716. * persistent connection (using WebSockets or long-polling)
  6717. */
  6718. class ReadonlyRestClient extends ServerActions {
  6719. /**
  6720. * @param repoInfo_ - Data about the namespace we are connecting to
  6721. * @param onDataUpdate_ - A callback for new data from the server
  6722. */
  6723. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6724. super();
  6725. this.repoInfo_ = repoInfo_;
  6726. this.onDataUpdate_ = onDataUpdate_;
  6727. this.authTokenProvider_ = authTokenProvider_;
  6728. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6729. /** @private {function(...[*])} */
  6730. this.log_ = logWrapper('p:rest:');
  6731. /**
  6732. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6733. * that's been removed. :-/
  6734. */
  6735. this.listens_ = {};
  6736. }
  6737. reportStats(stats) {
  6738. throw new Error('Method not implemented.');
  6739. }
  6740. static getListenId_(query, tag) {
  6741. if (tag !== undefined) {
  6742. return 'tag$' + tag;
  6743. }
  6744. else {
  6745. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6746. return query._path.toString();
  6747. }
  6748. }
  6749. /** @inheritDoc */
  6750. listen(query, currentHashFn, tag, onComplete) {
  6751. const pathString = query._path.toString();
  6752. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6753. // Mark this listener so we can tell if it's removed.
  6754. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6755. const thisListen = {};
  6756. this.listens_[listenId] = thisListen;
  6757. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6758. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6759. let data = result;
  6760. if (error === 404) {
  6761. data = null;
  6762. error = null;
  6763. }
  6764. if (error === null) {
  6765. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6766. }
  6767. if (safeGet(this.listens_, listenId) === thisListen) {
  6768. let status;
  6769. if (!error) {
  6770. status = 'ok';
  6771. }
  6772. else if (error === 401) {
  6773. status = 'permission_denied';
  6774. }
  6775. else {
  6776. status = 'rest_error:' + error;
  6777. }
  6778. onComplete(status, null);
  6779. }
  6780. });
  6781. }
  6782. /** @inheritDoc */
  6783. unlisten(query, tag) {
  6784. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6785. delete this.listens_[listenId];
  6786. }
  6787. get(query) {
  6788. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6789. const pathString = query._path.toString();
  6790. const deferred = new Deferred();
  6791. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6792. let data = result;
  6793. if (error === 404) {
  6794. data = null;
  6795. error = null;
  6796. }
  6797. if (error === null) {
  6798. this.onDataUpdate_(pathString, data,
  6799. /*isMerge=*/ false,
  6800. /*tag=*/ null);
  6801. deferred.resolve(data);
  6802. }
  6803. else {
  6804. deferred.reject(new Error(data));
  6805. }
  6806. });
  6807. return deferred.promise;
  6808. }
  6809. /** @inheritDoc */
  6810. refreshAuthToken(token) {
  6811. // no-op since we just always call getToken.
  6812. }
  6813. /**
  6814. * Performs a REST request to the given path, with the provided query string parameters,
  6815. * and any auth credentials we have.
  6816. */
  6817. restRequest_(pathString, queryStringParameters = {}, callback) {
  6818. queryStringParameters['format'] = 'export';
  6819. return Promise.all([
  6820. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6821. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6822. ]).then(([authToken, appCheckToken]) => {
  6823. if (authToken && authToken.accessToken) {
  6824. queryStringParameters['auth'] = authToken.accessToken;
  6825. }
  6826. if (appCheckToken && appCheckToken.token) {
  6827. queryStringParameters['ac'] = appCheckToken.token;
  6828. }
  6829. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6830. this.repoInfo_.host +
  6831. pathString +
  6832. '?' +
  6833. 'ns=' +
  6834. this.repoInfo_.namespace +
  6835. querystring(queryStringParameters);
  6836. this.log_('Sending REST request for ' + url);
  6837. const xhr = new XMLHttpRequest();
  6838. xhr.onreadystatechange = () => {
  6839. if (callback && xhr.readyState === 4) {
  6840. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6841. let res = null;
  6842. if (xhr.status >= 200 && xhr.status < 300) {
  6843. try {
  6844. res = jsonEval(xhr.responseText);
  6845. }
  6846. catch (e) {
  6847. warn('Failed to parse JSON response for ' +
  6848. url +
  6849. ': ' +
  6850. xhr.responseText);
  6851. }
  6852. callback(null, res);
  6853. }
  6854. else {
  6855. // 401 and 404 are expected.
  6856. if (xhr.status !== 401 && xhr.status !== 404) {
  6857. warn('Got unsuccessful REST response for ' +
  6858. url +
  6859. ' Status: ' +
  6860. xhr.status);
  6861. }
  6862. callback(xhr.status);
  6863. }
  6864. callback = null;
  6865. }
  6866. };
  6867. xhr.open('GET', url, /*asynchronous=*/ true);
  6868. xhr.send();
  6869. });
  6870. }
  6871. }
  6872. /**
  6873. * @license
  6874. * Copyright 2017 Google LLC
  6875. *
  6876. * Licensed under the Apache License, Version 2.0 (the "License");
  6877. * you may not use this file except in compliance with the License.
  6878. * You may obtain a copy of the License at
  6879. *
  6880. * http://www.apache.org/licenses/LICENSE-2.0
  6881. *
  6882. * Unless required by applicable law or agreed to in writing, software
  6883. * distributed under the License is distributed on an "AS IS" BASIS,
  6884. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6885. * See the License for the specific language governing permissions and
  6886. * limitations under the License.
  6887. */
  6888. /**
  6889. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6890. */
  6891. class SnapshotHolder {
  6892. constructor() {
  6893. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6894. }
  6895. getNode(path) {
  6896. return this.rootNode_.getChild(path);
  6897. }
  6898. updateSnapshot(path, newSnapshotNode) {
  6899. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6900. }
  6901. }
  6902. /**
  6903. * @license
  6904. * Copyright 2017 Google LLC
  6905. *
  6906. * Licensed under the Apache License, Version 2.0 (the "License");
  6907. * you may not use this file except in compliance with the License.
  6908. * You may obtain a copy of the License at
  6909. *
  6910. * http://www.apache.org/licenses/LICENSE-2.0
  6911. *
  6912. * Unless required by applicable law or agreed to in writing, software
  6913. * distributed under the License is distributed on an "AS IS" BASIS,
  6914. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6915. * See the License for the specific language governing permissions and
  6916. * limitations under the License.
  6917. */
  6918. function newSparseSnapshotTree() {
  6919. return {
  6920. value: null,
  6921. children: new Map()
  6922. };
  6923. }
  6924. /**
  6925. * Stores the given node at the specified path. If there is already a node
  6926. * at a shallower path, it merges the new data into that snapshot node.
  6927. *
  6928. * @param path - Path to look up snapshot for.
  6929. * @param data - The new data, or null.
  6930. */
  6931. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6932. if (pathIsEmpty(path)) {
  6933. sparseSnapshotTree.value = data;
  6934. sparseSnapshotTree.children.clear();
  6935. }
  6936. else if (sparseSnapshotTree.value !== null) {
  6937. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6938. }
  6939. else {
  6940. const childKey = pathGetFront(path);
  6941. if (!sparseSnapshotTree.children.has(childKey)) {
  6942. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6943. }
  6944. const child = sparseSnapshotTree.children.get(childKey);
  6945. path = pathPopFront(path);
  6946. sparseSnapshotTreeRemember(child, path, data);
  6947. }
  6948. }
  6949. /**
  6950. * Purge the data at path from the cache.
  6951. *
  6952. * @param path - Path to look up snapshot for.
  6953. * @returns True if this node should now be removed.
  6954. */
  6955. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6956. if (pathIsEmpty(path)) {
  6957. sparseSnapshotTree.value = null;
  6958. sparseSnapshotTree.children.clear();
  6959. return true;
  6960. }
  6961. else {
  6962. if (sparseSnapshotTree.value !== null) {
  6963. if (sparseSnapshotTree.value.isLeafNode()) {
  6964. // We're trying to forget a node that doesn't exist
  6965. return false;
  6966. }
  6967. else {
  6968. const value = sparseSnapshotTree.value;
  6969. sparseSnapshotTree.value = null;
  6970. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6971. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6972. });
  6973. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6974. }
  6975. }
  6976. else if (sparseSnapshotTree.children.size > 0) {
  6977. const childKey = pathGetFront(path);
  6978. path = pathPopFront(path);
  6979. if (sparseSnapshotTree.children.has(childKey)) {
  6980. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6981. if (safeToRemove) {
  6982. sparseSnapshotTree.children.delete(childKey);
  6983. }
  6984. }
  6985. return sparseSnapshotTree.children.size === 0;
  6986. }
  6987. else {
  6988. return true;
  6989. }
  6990. }
  6991. }
  6992. /**
  6993. * Recursively iterates through all of the stored tree and calls the
  6994. * callback on each one.
  6995. *
  6996. * @param prefixPath - Path to look up node for.
  6997. * @param func - The function to invoke for each tree.
  6998. */
  6999. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7000. if (sparseSnapshotTree.value !== null) {
  7001. func(prefixPath, sparseSnapshotTree.value);
  7002. }
  7003. else {
  7004. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  7005. const path = new Path(prefixPath.toString() + '/' + key);
  7006. sparseSnapshotTreeForEachTree(tree, path, func);
  7007. });
  7008. }
  7009. }
  7010. /**
  7011. * Iterates through each immediate child and triggers the callback.
  7012. * Only seems to be used in tests.
  7013. *
  7014. * @param func - The function to invoke for each child.
  7015. */
  7016. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7017. sparseSnapshotTree.children.forEach((tree, key) => {
  7018. func(key, tree);
  7019. });
  7020. }
  7021. /**
  7022. * @license
  7023. * Copyright 2017 Google LLC
  7024. *
  7025. * Licensed under the Apache License, Version 2.0 (the "License");
  7026. * you may not use this file except in compliance with the License.
  7027. * You may obtain a copy of the License at
  7028. *
  7029. * http://www.apache.org/licenses/LICENSE-2.0
  7030. *
  7031. * Unless required by applicable law or agreed to in writing, software
  7032. * distributed under the License is distributed on an "AS IS" BASIS,
  7033. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7034. * See the License for the specific language governing permissions and
  7035. * limitations under the License.
  7036. */
  7037. /**
  7038. * Returns the delta from the previous call to get stats.
  7039. *
  7040. * @param collection_ - The collection to "listen" to.
  7041. */
  7042. class StatsListener {
  7043. constructor(collection_) {
  7044. this.collection_ = collection_;
  7045. this.last_ = null;
  7046. }
  7047. get() {
  7048. const newStats = this.collection_.get();
  7049. const delta = Object.assign({}, newStats);
  7050. if (this.last_) {
  7051. each(this.last_, (stat, value) => {
  7052. delta[stat] = delta[stat] - value;
  7053. });
  7054. }
  7055. this.last_ = newStats;
  7056. return delta;
  7057. }
  7058. }
  7059. /**
  7060. * @license
  7061. * Copyright 2017 Google LLC
  7062. *
  7063. * Licensed under the Apache License, Version 2.0 (the "License");
  7064. * you may not use this file except in compliance with the License.
  7065. * You may obtain a copy of the License at
  7066. *
  7067. * http://www.apache.org/licenses/LICENSE-2.0
  7068. *
  7069. * Unless required by applicable law or agreed to in writing, software
  7070. * distributed under the License is distributed on an "AS IS" BASIS,
  7071. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7072. * See the License for the specific language governing permissions and
  7073. * limitations under the License.
  7074. */
  7075. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7076. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7077. // seconds to try to ensure the Firebase connection is established / settled.
  7078. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7079. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7080. // We'll continue to report stats on average every 5 minutes.
  7081. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7082. class StatsReporter {
  7083. constructor(collection, server_) {
  7084. this.server_ = server_;
  7085. this.statsToReport_ = {};
  7086. this.statsListener_ = new StatsListener(collection);
  7087. const timeout = FIRST_STATS_MIN_TIME +
  7088. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7089. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7090. }
  7091. reportStats_() {
  7092. const stats = this.statsListener_.get();
  7093. const reportedStats = {};
  7094. let haveStatsToReport = false;
  7095. each(stats, (stat, value) => {
  7096. if (value > 0 && contains(this.statsToReport_, stat)) {
  7097. reportedStats[stat] = value;
  7098. haveStatsToReport = true;
  7099. }
  7100. });
  7101. if (haveStatsToReport) {
  7102. this.server_.reportStats(reportedStats);
  7103. }
  7104. // queue our next run.
  7105. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7106. }
  7107. }
  7108. /**
  7109. * @license
  7110. * Copyright 2017 Google LLC
  7111. *
  7112. * Licensed under the Apache License, Version 2.0 (the "License");
  7113. * you may not use this file except in compliance with the License.
  7114. * You may obtain a copy of the License at
  7115. *
  7116. * http://www.apache.org/licenses/LICENSE-2.0
  7117. *
  7118. * Unless required by applicable law or agreed to in writing, software
  7119. * distributed under the License is distributed on an "AS IS" BASIS,
  7120. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7121. * See the License for the specific language governing permissions and
  7122. * limitations under the License.
  7123. */
  7124. /**
  7125. *
  7126. * @enum
  7127. */
  7128. var OperationType;
  7129. (function (OperationType) {
  7130. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7131. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7132. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7133. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7134. })(OperationType || (OperationType = {}));
  7135. function newOperationSourceUser() {
  7136. return {
  7137. fromUser: true,
  7138. fromServer: false,
  7139. queryId: null,
  7140. tagged: false
  7141. };
  7142. }
  7143. function newOperationSourceServer() {
  7144. return {
  7145. fromUser: false,
  7146. fromServer: true,
  7147. queryId: null,
  7148. tagged: false
  7149. };
  7150. }
  7151. function newOperationSourceServerTaggedQuery(queryId) {
  7152. return {
  7153. fromUser: false,
  7154. fromServer: true,
  7155. queryId,
  7156. tagged: true
  7157. };
  7158. }
  7159. /**
  7160. * @license
  7161. * Copyright 2017 Google LLC
  7162. *
  7163. * Licensed under the Apache License, Version 2.0 (the "License");
  7164. * you may not use this file except in compliance with the License.
  7165. * You may obtain a copy of the License at
  7166. *
  7167. * http://www.apache.org/licenses/LICENSE-2.0
  7168. *
  7169. * Unless required by applicable law or agreed to in writing, software
  7170. * distributed under the License is distributed on an "AS IS" BASIS,
  7171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7172. * See the License for the specific language governing permissions and
  7173. * limitations under the License.
  7174. */
  7175. class AckUserWrite {
  7176. /**
  7177. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7178. */
  7179. constructor(
  7180. /** @inheritDoc */ path,
  7181. /** @inheritDoc */ affectedTree,
  7182. /** @inheritDoc */ revert) {
  7183. this.path = path;
  7184. this.affectedTree = affectedTree;
  7185. this.revert = revert;
  7186. /** @inheritDoc */
  7187. this.type = OperationType.ACK_USER_WRITE;
  7188. /** @inheritDoc */
  7189. this.source = newOperationSourceUser();
  7190. }
  7191. operationForChild(childName) {
  7192. if (!pathIsEmpty(this.path)) {
  7193. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7194. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7195. }
  7196. else if (this.affectedTree.value != null) {
  7197. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7198. // All child locations are affected as well; just return same operation.
  7199. return this;
  7200. }
  7201. else {
  7202. const childTree = this.affectedTree.subtree(new Path(childName));
  7203. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7204. }
  7205. }
  7206. }
  7207. /**
  7208. * @license
  7209. * Copyright 2017 Google LLC
  7210. *
  7211. * Licensed under the Apache License, Version 2.0 (the "License");
  7212. * you may not use this file except in compliance with the License.
  7213. * You may obtain a copy of the License at
  7214. *
  7215. * http://www.apache.org/licenses/LICENSE-2.0
  7216. *
  7217. * Unless required by applicable law or agreed to in writing, software
  7218. * distributed under the License is distributed on an "AS IS" BASIS,
  7219. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7220. * See the License for the specific language governing permissions and
  7221. * limitations under the License.
  7222. */
  7223. class ListenComplete {
  7224. constructor(source, path) {
  7225. this.source = source;
  7226. this.path = path;
  7227. /** @inheritDoc */
  7228. this.type = OperationType.LISTEN_COMPLETE;
  7229. }
  7230. operationForChild(childName) {
  7231. if (pathIsEmpty(this.path)) {
  7232. return new ListenComplete(this.source, newEmptyPath());
  7233. }
  7234. else {
  7235. return new ListenComplete(this.source, pathPopFront(this.path));
  7236. }
  7237. }
  7238. }
  7239. /**
  7240. * @license
  7241. * Copyright 2017 Google LLC
  7242. *
  7243. * Licensed under the Apache License, Version 2.0 (the "License");
  7244. * you may not use this file except in compliance with the License.
  7245. * You may obtain a copy of the License at
  7246. *
  7247. * http://www.apache.org/licenses/LICENSE-2.0
  7248. *
  7249. * Unless required by applicable law or agreed to in writing, software
  7250. * distributed under the License is distributed on an "AS IS" BASIS,
  7251. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7252. * See the License for the specific language governing permissions and
  7253. * limitations under the License.
  7254. */
  7255. class Overwrite {
  7256. constructor(source, path, snap) {
  7257. this.source = source;
  7258. this.path = path;
  7259. this.snap = snap;
  7260. /** @inheritDoc */
  7261. this.type = OperationType.OVERWRITE;
  7262. }
  7263. operationForChild(childName) {
  7264. if (pathIsEmpty(this.path)) {
  7265. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7266. }
  7267. else {
  7268. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7269. }
  7270. }
  7271. }
  7272. /**
  7273. * @license
  7274. * Copyright 2017 Google LLC
  7275. *
  7276. * Licensed under the Apache License, Version 2.0 (the "License");
  7277. * you may not use this file except in compliance with the License.
  7278. * You may obtain a copy of the License at
  7279. *
  7280. * http://www.apache.org/licenses/LICENSE-2.0
  7281. *
  7282. * Unless required by applicable law or agreed to in writing, software
  7283. * distributed under the License is distributed on an "AS IS" BASIS,
  7284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7285. * See the License for the specific language governing permissions and
  7286. * limitations under the License.
  7287. */
  7288. class Merge {
  7289. constructor(
  7290. /** @inheritDoc */ source,
  7291. /** @inheritDoc */ path,
  7292. /** @inheritDoc */ children) {
  7293. this.source = source;
  7294. this.path = path;
  7295. this.children = children;
  7296. /** @inheritDoc */
  7297. this.type = OperationType.MERGE;
  7298. }
  7299. operationForChild(childName) {
  7300. if (pathIsEmpty(this.path)) {
  7301. const childTree = this.children.subtree(new Path(childName));
  7302. if (childTree.isEmpty()) {
  7303. // This child is unaffected
  7304. return null;
  7305. }
  7306. else if (childTree.value) {
  7307. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7308. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7309. }
  7310. else {
  7311. // This is a merge at a deeper level
  7312. return new Merge(this.source, newEmptyPath(), childTree);
  7313. }
  7314. }
  7315. else {
  7316. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7317. return new Merge(this.source, pathPopFront(this.path), this.children);
  7318. }
  7319. }
  7320. toString() {
  7321. return ('Operation(' +
  7322. this.path +
  7323. ': ' +
  7324. this.source.toString() +
  7325. ' merge: ' +
  7326. this.children.toString() +
  7327. ')');
  7328. }
  7329. }
  7330. /**
  7331. * @license
  7332. * Copyright 2017 Google LLC
  7333. *
  7334. * Licensed under the Apache License, Version 2.0 (the "License");
  7335. * you may not use this file except in compliance with the License.
  7336. * You may obtain a copy of the License at
  7337. *
  7338. * http://www.apache.org/licenses/LICENSE-2.0
  7339. *
  7340. * Unless required by applicable law or agreed to in writing, software
  7341. * distributed under the License is distributed on an "AS IS" BASIS,
  7342. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7343. * See the License for the specific language governing permissions and
  7344. * limitations under the License.
  7345. */
  7346. /**
  7347. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7348. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7349. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7350. * whether a node potentially had children removed due to a filter.
  7351. */
  7352. class CacheNode {
  7353. constructor(node_, fullyInitialized_, filtered_) {
  7354. this.node_ = node_;
  7355. this.fullyInitialized_ = fullyInitialized_;
  7356. this.filtered_ = filtered_;
  7357. }
  7358. /**
  7359. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7360. */
  7361. isFullyInitialized() {
  7362. return this.fullyInitialized_;
  7363. }
  7364. /**
  7365. * Returns whether this node is potentially missing children due to a filter applied to the node
  7366. */
  7367. isFiltered() {
  7368. return this.filtered_;
  7369. }
  7370. isCompleteForPath(path) {
  7371. if (pathIsEmpty(path)) {
  7372. return this.isFullyInitialized() && !this.filtered_;
  7373. }
  7374. const childKey = pathGetFront(path);
  7375. return this.isCompleteForChild(childKey);
  7376. }
  7377. isCompleteForChild(key) {
  7378. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7379. }
  7380. getNode() {
  7381. return this.node_;
  7382. }
  7383. }
  7384. /**
  7385. * @license
  7386. * Copyright 2017 Google LLC
  7387. *
  7388. * Licensed under the Apache License, Version 2.0 (the "License");
  7389. * you may not use this file except in compliance with the License.
  7390. * You may obtain a copy of the License at
  7391. *
  7392. * http://www.apache.org/licenses/LICENSE-2.0
  7393. *
  7394. * Unless required by applicable law or agreed to in writing, software
  7395. * distributed under the License is distributed on an "AS IS" BASIS,
  7396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7397. * See the License for the specific language governing permissions and
  7398. * limitations under the License.
  7399. */
  7400. /**
  7401. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7402. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7403. * for details.
  7404. *
  7405. */
  7406. class EventGenerator {
  7407. constructor(query_) {
  7408. this.query_ = query_;
  7409. this.index_ = this.query_._queryParams.getIndex();
  7410. }
  7411. }
  7412. /**
  7413. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7414. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7415. *
  7416. * Notes:
  7417. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7418. * our index.
  7419. * - prevName will be calculated based on the index ordering.
  7420. */
  7421. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7422. const events = [];
  7423. const moves = [];
  7424. changes.forEach(change => {
  7425. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7426. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7427. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7428. }
  7429. });
  7430. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7431. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7432. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7433. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7434. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7435. return events;
  7436. }
  7437. /**
  7438. * Given changes of a single change type, generate the corresponding events.
  7439. */
  7440. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7441. const filteredChanges = changes.filter(change => change.type === eventType);
  7442. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7443. filteredChanges.forEach(change => {
  7444. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7445. registrations.forEach(registration => {
  7446. if (registration.respondsTo(change.type)) {
  7447. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7448. }
  7449. });
  7450. });
  7451. }
  7452. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7453. if (change.type === 'value' || change.type === 'child_removed') {
  7454. return change;
  7455. }
  7456. else {
  7457. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7458. return change;
  7459. }
  7460. }
  7461. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7462. if (a.childName == null || b.childName == null) {
  7463. throw assertionError('Should only compare child_ events.');
  7464. }
  7465. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7466. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7467. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7468. }
  7469. /**
  7470. * @license
  7471. * Copyright 2017 Google LLC
  7472. *
  7473. * Licensed under the Apache License, Version 2.0 (the "License");
  7474. * you may not use this file except in compliance with the License.
  7475. * You may obtain a copy of the License at
  7476. *
  7477. * http://www.apache.org/licenses/LICENSE-2.0
  7478. *
  7479. * Unless required by applicable law or agreed to in writing, software
  7480. * distributed under the License is distributed on an "AS IS" BASIS,
  7481. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7482. * See the License for the specific language governing permissions and
  7483. * limitations under the License.
  7484. */
  7485. function newViewCache(eventCache, serverCache) {
  7486. return { eventCache, serverCache };
  7487. }
  7488. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7489. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7490. }
  7491. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7492. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7493. }
  7494. function viewCacheGetCompleteEventSnap(viewCache) {
  7495. return viewCache.eventCache.isFullyInitialized()
  7496. ? viewCache.eventCache.getNode()
  7497. : null;
  7498. }
  7499. function viewCacheGetCompleteServerSnap(viewCache) {
  7500. return viewCache.serverCache.isFullyInitialized()
  7501. ? viewCache.serverCache.getNode()
  7502. : null;
  7503. }
  7504. /**
  7505. * @license
  7506. * Copyright 2017 Google LLC
  7507. *
  7508. * Licensed under the Apache License, Version 2.0 (the "License");
  7509. * you may not use this file except in compliance with the License.
  7510. * You may obtain a copy of the License at
  7511. *
  7512. * http://www.apache.org/licenses/LICENSE-2.0
  7513. *
  7514. * Unless required by applicable law or agreed to in writing, software
  7515. * distributed under the License is distributed on an "AS IS" BASIS,
  7516. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7517. * See the License for the specific language governing permissions and
  7518. * limitations under the License.
  7519. */
  7520. let emptyChildrenSingleton;
  7521. /**
  7522. * Singleton empty children collection.
  7523. *
  7524. */
  7525. const EmptyChildren = () => {
  7526. if (!emptyChildrenSingleton) {
  7527. emptyChildrenSingleton = new SortedMap(stringCompare);
  7528. }
  7529. return emptyChildrenSingleton;
  7530. };
  7531. /**
  7532. * A tree with immutable elements.
  7533. */
  7534. class ImmutableTree {
  7535. constructor(value, children = EmptyChildren()) {
  7536. this.value = value;
  7537. this.children = children;
  7538. }
  7539. static fromObject(obj) {
  7540. let tree = new ImmutableTree(null);
  7541. each(obj, (childPath, childSnap) => {
  7542. tree = tree.set(new Path(childPath), childSnap);
  7543. });
  7544. return tree;
  7545. }
  7546. /**
  7547. * True if the value is empty and there are no children
  7548. */
  7549. isEmpty() {
  7550. return this.value === null && this.children.isEmpty();
  7551. }
  7552. /**
  7553. * Given a path and predicate, return the first node and the path to that node
  7554. * where the predicate returns true.
  7555. *
  7556. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7557. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7558. *
  7559. * @param relativePath - The remainder of the path
  7560. * @param predicate - The predicate to satisfy to return a node
  7561. */
  7562. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7563. if (this.value != null && predicate(this.value)) {
  7564. return { path: newEmptyPath(), value: this.value };
  7565. }
  7566. else {
  7567. if (pathIsEmpty(relativePath)) {
  7568. return null;
  7569. }
  7570. else {
  7571. const front = pathGetFront(relativePath);
  7572. const child = this.children.get(front);
  7573. if (child !== null) {
  7574. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7575. if (childExistingPathAndValue != null) {
  7576. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7577. return { path: fullPath, value: childExistingPathAndValue.value };
  7578. }
  7579. else {
  7580. return null;
  7581. }
  7582. }
  7583. else {
  7584. return null;
  7585. }
  7586. }
  7587. }
  7588. }
  7589. /**
  7590. * Find, if it exists, the shortest subpath of the given path that points a defined
  7591. * value in the tree
  7592. */
  7593. findRootMostValueAndPath(relativePath) {
  7594. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7595. }
  7596. /**
  7597. * @returns The subtree at the given path
  7598. */
  7599. subtree(relativePath) {
  7600. if (pathIsEmpty(relativePath)) {
  7601. return this;
  7602. }
  7603. else {
  7604. const front = pathGetFront(relativePath);
  7605. const childTree = this.children.get(front);
  7606. if (childTree !== null) {
  7607. return childTree.subtree(pathPopFront(relativePath));
  7608. }
  7609. else {
  7610. return new ImmutableTree(null);
  7611. }
  7612. }
  7613. }
  7614. /**
  7615. * Sets a value at the specified path.
  7616. *
  7617. * @param relativePath - Path to set value at.
  7618. * @param toSet - Value to set.
  7619. * @returns Resulting tree.
  7620. */
  7621. set(relativePath, toSet) {
  7622. if (pathIsEmpty(relativePath)) {
  7623. return new ImmutableTree(toSet, this.children);
  7624. }
  7625. else {
  7626. const front = pathGetFront(relativePath);
  7627. const child = this.children.get(front) || new ImmutableTree(null);
  7628. const newChild = child.set(pathPopFront(relativePath), toSet);
  7629. const newChildren = this.children.insert(front, newChild);
  7630. return new ImmutableTree(this.value, newChildren);
  7631. }
  7632. }
  7633. /**
  7634. * Removes the value at the specified path.
  7635. *
  7636. * @param relativePath - Path to value to remove.
  7637. * @returns Resulting tree.
  7638. */
  7639. remove(relativePath) {
  7640. if (pathIsEmpty(relativePath)) {
  7641. if (this.children.isEmpty()) {
  7642. return new ImmutableTree(null);
  7643. }
  7644. else {
  7645. return new ImmutableTree(null, this.children);
  7646. }
  7647. }
  7648. else {
  7649. const front = pathGetFront(relativePath);
  7650. const child = this.children.get(front);
  7651. if (child) {
  7652. const newChild = child.remove(pathPopFront(relativePath));
  7653. let newChildren;
  7654. if (newChild.isEmpty()) {
  7655. newChildren = this.children.remove(front);
  7656. }
  7657. else {
  7658. newChildren = this.children.insert(front, newChild);
  7659. }
  7660. if (this.value === null && newChildren.isEmpty()) {
  7661. return new ImmutableTree(null);
  7662. }
  7663. else {
  7664. return new ImmutableTree(this.value, newChildren);
  7665. }
  7666. }
  7667. else {
  7668. return this;
  7669. }
  7670. }
  7671. }
  7672. /**
  7673. * Gets a value from the tree.
  7674. *
  7675. * @param relativePath - Path to get value for.
  7676. * @returns Value at path, or null.
  7677. */
  7678. get(relativePath) {
  7679. if (pathIsEmpty(relativePath)) {
  7680. return this.value;
  7681. }
  7682. else {
  7683. const front = pathGetFront(relativePath);
  7684. const child = this.children.get(front);
  7685. if (child) {
  7686. return child.get(pathPopFront(relativePath));
  7687. }
  7688. else {
  7689. return null;
  7690. }
  7691. }
  7692. }
  7693. /**
  7694. * Replace the subtree at the specified path with the given new tree.
  7695. *
  7696. * @param relativePath - Path to replace subtree for.
  7697. * @param newTree - New tree.
  7698. * @returns Resulting tree.
  7699. */
  7700. setTree(relativePath, newTree) {
  7701. if (pathIsEmpty(relativePath)) {
  7702. return newTree;
  7703. }
  7704. else {
  7705. const front = pathGetFront(relativePath);
  7706. const child = this.children.get(front) || new ImmutableTree(null);
  7707. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7708. let newChildren;
  7709. if (newChild.isEmpty()) {
  7710. newChildren = this.children.remove(front);
  7711. }
  7712. else {
  7713. newChildren = this.children.insert(front, newChild);
  7714. }
  7715. return new ImmutableTree(this.value, newChildren);
  7716. }
  7717. }
  7718. /**
  7719. * Performs a depth first fold on this tree. Transforms a tree into a single
  7720. * value, given a function that operates on the path to a node, an optional
  7721. * current value, and a map of child names to folded subtrees
  7722. */
  7723. fold(fn) {
  7724. return this.fold_(newEmptyPath(), fn);
  7725. }
  7726. /**
  7727. * Recursive helper for public-facing fold() method
  7728. */
  7729. fold_(pathSoFar, fn) {
  7730. const accum = {};
  7731. this.children.inorderTraversal((childKey, childTree) => {
  7732. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7733. });
  7734. return fn(pathSoFar, this.value, accum);
  7735. }
  7736. /**
  7737. * Find the first matching value on the given path. Return the result of applying f to it.
  7738. */
  7739. findOnPath(path, f) {
  7740. return this.findOnPath_(path, newEmptyPath(), f);
  7741. }
  7742. findOnPath_(pathToFollow, pathSoFar, f) {
  7743. const result = this.value ? f(pathSoFar, this.value) : false;
  7744. if (result) {
  7745. return result;
  7746. }
  7747. else {
  7748. if (pathIsEmpty(pathToFollow)) {
  7749. return null;
  7750. }
  7751. else {
  7752. const front = pathGetFront(pathToFollow);
  7753. const nextChild = this.children.get(front);
  7754. if (nextChild) {
  7755. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7756. }
  7757. else {
  7758. return null;
  7759. }
  7760. }
  7761. }
  7762. }
  7763. foreachOnPath(path, f) {
  7764. return this.foreachOnPath_(path, newEmptyPath(), f);
  7765. }
  7766. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7767. if (pathIsEmpty(pathToFollow)) {
  7768. return this;
  7769. }
  7770. else {
  7771. if (this.value) {
  7772. f(currentRelativePath, this.value);
  7773. }
  7774. const front = pathGetFront(pathToFollow);
  7775. const nextChild = this.children.get(front);
  7776. if (nextChild) {
  7777. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7778. }
  7779. else {
  7780. return new ImmutableTree(null);
  7781. }
  7782. }
  7783. }
  7784. /**
  7785. * Calls the given function for each node in the tree that has a value.
  7786. *
  7787. * @param f - A function to be called with the path from the root of the tree to
  7788. * a node, and the value at that node. Called in depth-first order.
  7789. */
  7790. foreach(f) {
  7791. this.foreach_(newEmptyPath(), f);
  7792. }
  7793. foreach_(currentRelativePath, f) {
  7794. this.children.inorderTraversal((childName, childTree) => {
  7795. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7796. });
  7797. if (this.value) {
  7798. f(currentRelativePath, this.value);
  7799. }
  7800. }
  7801. foreachChild(f) {
  7802. this.children.inorderTraversal((childName, childTree) => {
  7803. if (childTree.value) {
  7804. f(childName, childTree.value);
  7805. }
  7806. });
  7807. }
  7808. }
  7809. /**
  7810. * @license
  7811. * Copyright 2017 Google LLC
  7812. *
  7813. * Licensed under the Apache License, Version 2.0 (the "License");
  7814. * you may not use this file except in compliance with the License.
  7815. * You may obtain a copy of the License at
  7816. *
  7817. * http://www.apache.org/licenses/LICENSE-2.0
  7818. *
  7819. * Unless required by applicable law or agreed to in writing, software
  7820. * distributed under the License is distributed on an "AS IS" BASIS,
  7821. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7822. * See the License for the specific language governing permissions and
  7823. * limitations under the License.
  7824. */
  7825. /**
  7826. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7827. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7828. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7829. * to reflect the write added.
  7830. */
  7831. class CompoundWrite {
  7832. constructor(writeTree_) {
  7833. this.writeTree_ = writeTree_;
  7834. }
  7835. static empty() {
  7836. return new CompoundWrite(new ImmutableTree(null));
  7837. }
  7838. }
  7839. function compoundWriteAddWrite(compoundWrite, path, node) {
  7840. if (pathIsEmpty(path)) {
  7841. return new CompoundWrite(new ImmutableTree(node));
  7842. }
  7843. else {
  7844. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7845. if (rootmost != null) {
  7846. const rootMostPath = rootmost.path;
  7847. let value = rootmost.value;
  7848. const relativePath = newRelativePath(rootMostPath, path);
  7849. value = value.updateChild(relativePath, node);
  7850. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7851. }
  7852. else {
  7853. const subtree = new ImmutableTree(node);
  7854. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7855. return new CompoundWrite(newWriteTree);
  7856. }
  7857. }
  7858. }
  7859. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7860. let newWrite = compoundWrite;
  7861. each(updates, (childKey, node) => {
  7862. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7863. });
  7864. return newWrite;
  7865. }
  7866. /**
  7867. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7868. * location, which must be removed by calling this method with that path.
  7869. *
  7870. * @param compoundWrite - The CompoundWrite to remove.
  7871. * @param path - The path at which a write and all deeper writes should be removed
  7872. * @returns The new CompoundWrite with the removed path
  7873. */
  7874. function compoundWriteRemoveWrite(compoundWrite, path) {
  7875. if (pathIsEmpty(path)) {
  7876. return CompoundWrite.empty();
  7877. }
  7878. else {
  7879. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7880. return new CompoundWrite(newWriteTree);
  7881. }
  7882. }
  7883. /**
  7884. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7885. * considered "complete".
  7886. *
  7887. * @param compoundWrite - The CompoundWrite to check.
  7888. * @param path - The path to check for
  7889. * @returns Whether there is a complete write at that path
  7890. */
  7891. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7892. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7893. }
  7894. /**
  7895. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7896. * writes from deeper paths, but will return child nodes from a more shallow path.
  7897. *
  7898. * @param compoundWrite - The CompoundWrite to get the node from.
  7899. * @param path - The path to get a complete write
  7900. * @returns The node if complete at that path, or null otherwise.
  7901. */
  7902. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7903. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7904. if (rootmost != null) {
  7905. return compoundWrite.writeTree_
  7906. .get(rootmost.path)
  7907. .getChild(newRelativePath(rootmost.path, path));
  7908. }
  7909. else {
  7910. return null;
  7911. }
  7912. }
  7913. /**
  7914. * Returns all children that are guaranteed to be a complete overwrite.
  7915. *
  7916. * @param compoundWrite - The CompoundWrite to get children from.
  7917. * @returns A list of all complete children.
  7918. */
  7919. function compoundWriteGetCompleteChildren(compoundWrite) {
  7920. const children = [];
  7921. const node = compoundWrite.writeTree_.value;
  7922. if (node != null) {
  7923. // If it's a leaf node, it has no children; so nothing to do.
  7924. if (!node.isLeafNode()) {
  7925. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7926. children.push(new NamedNode(childName, childNode));
  7927. });
  7928. }
  7929. }
  7930. else {
  7931. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7932. if (childTree.value != null) {
  7933. children.push(new NamedNode(childName, childTree.value));
  7934. }
  7935. });
  7936. }
  7937. return children;
  7938. }
  7939. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7940. if (pathIsEmpty(path)) {
  7941. return compoundWrite;
  7942. }
  7943. else {
  7944. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7945. if (shadowingNode != null) {
  7946. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7947. }
  7948. else {
  7949. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7950. }
  7951. }
  7952. }
  7953. /**
  7954. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7955. * @returns Whether this CompoundWrite is empty
  7956. */
  7957. function compoundWriteIsEmpty(compoundWrite) {
  7958. return compoundWrite.writeTree_.isEmpty();
  7959. }
  7960. /**
  7961. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7962. * node
  7963. * @param node - The node to apply this CompoundWrite to
  7964. * @returns The node with all writes applied
  7965. */
  7966. function compoundWriteApply(compoundWrite, node) {
  7967. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7968. }
  7969. function applySubtreeWrite(relativePath, writeTree, node) {
  7970. if (writeTree.value != null) {
  7971. // Since there a write is always a leaf, we're done here
  7972. return node.updateChild(relativePath, writeTree.value);
  7973. }
  7974. else {
  7975. let priorityWrite = null;
  7976. writeTree.children.inorderTraversal((childKey, childTree) => {
  7977. if (childKey === '.priority') {
  7978. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7979. // to apply priorities to empty nodes that are later filled
  7980. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7981. priorityWrite = childTree.value;
  7982. }
  7983. else {
  7984. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7985. }
  7986. });
  7987. // If there was a priority write, we only apply it if the node is not empty
  7988. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7989. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7990. }
  7991. return node;
  7992. }
  7993. }
  7994. /**
  7995. * @license
  7996. * Copyright 2017 Google LLC
  7997. *
  7998. * Licensed under the Apache License, Version 2.0 (the "License");
  7999. * you may not use this file except in compliance with the License.
  8000. * You may obtain a copy of the License at
  8001. *
  8002. * http://www.apache.org/licenses/LICENSE-2.0
  8003. *
  8004. * Unless required by applicable law or agreed to in writing, software
  8005. * distributed under the License is distributed on an "AS IS" BASIS,
  8006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8007. * See the License for the specific language governing permissions and
  8008. * limitations under the License.
  8009. */
  8010. /**
  8011. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8012. *
  8013. */
  8014. function writeTreeChildWrites(writeTree, path) {
  8015. return newWriteTreeRef(path, writeTree);
  8016. }
  8017. /**
  8018. * Record a new overwrite from user code.
  8019. *
  8020. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8021. */
  8022. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8023. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8024. if (visible === undefined) {
  8025. visible = true;
  8026. }
  8027. writeTree.allWrites.push({
  8028. path,
  8029. snap,
  8030. writeId,
  8031. visible
  8032. });
  8033. if (visible) {
  8034. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8035. }
  8036. writeTree.lastWriteId = writeId;
  8037. }
  8038. /**
  8039. * Record a new merge from user code.
  8040. */
  8041. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8042. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8043. writeTree.allWrites.push({
  8044. path,
  8045. children: changedChildren,
  8046. writeId,
  8047. visible: true
  8048. });
  8049. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8050. writeTree.lastWriteId = writeId;
  8051. }
  8052. function writeTreeGetWrite(writeTree, writeId) {
  8053. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8054. const record = writeTree.allWrites[i];
  8055. if (record.writeId === writeId) {
  8056. return record;
  8057. }
  8058. }
  8059. return null;
  8060. }
  8061. /**
  8062. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8063. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8064. *
  8065. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8066. * events as a result).
  8067. */
  8068. function writeTreeRemoveWrite(writeTree, writeId) {
  8069. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8070. // out of order.
  8071. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8072. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8073. const idx = writeTree.allWrites.findIndex(s => {
  8074. return s.writeId === writeId;
  8075. });
  8076. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8077. const writeToRemove = writeTree.allWrites[idx];
  8078. writeTree.allWrites.splice(idx, 1);
  8079. let removedWriteWasVisible = writeToRemove.visible;
  8080. let removedWriteOverlapsWithOtherWrites = false;
  8081. let i = writeTree.allWrites.length - 1;
  8082. while (removedWriteWasVisible && i >= 0) {
  8083. const currentWrite = writeTree.allWrites[i];
  8084. if (currentWrite.visible) {
  8085. if (i >= idx &&
  8086. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8087. // The removed write was completely shadowed by a subsequent write.
  8088. removedWriteWasVisible = false;
  8089. }
  8090. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8091. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8092. removedWriteOverlapsWithOtherWrites = true;
  8093. }
  8094. }
  8095. i--;
  8096. }
  8097. if (!removedWriteWasVisible) {
  8098. return false;
  8099. }
  8100. else if (removedWriteOverlapsWithOtherWrites) {
  8101. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8102. writeTreeResetTree_(writeTree);
  8103. return true;
  8104. }
  8105. else {
  8106. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8107. if (writeToRemove.snap) {
  8108. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8109. }
  8110. else {
  8111. const children = writeToRemove.children;
  8112. each(children, (childName) => {
  8113. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8114. });
  8115. }
  8116. return true;
  8117. }
  8118. }
  8119. function writeTreeRecordContainsPath_(writeRecord, path) {
  8120. if (writeRecord.snap) {
  8121. return pathContains(writeRecord.path, path);
  8122. }
  8123. else {
  8124. for (const childName in writeRecord.children) {
  8125. if (writeRecord.children.hasOwnProperty(childName) &&
  8126. pathContains(pathChild(writeRecord.path, childName), path)) {
  8127. return true;
  8128. }
  8129. }
  8130. return false;
  8131. }
  8132. }
  8133. /**
  8134. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8135. */
  8136. function writeTreeResetTree_(writeTree) {
  8137. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8138. if (writeTree.allWrites.length > 0) {
  8139. writeTree.lastWriteId =
  8140. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8141. }
  8142. else {
  8143. writeTree.lastWriteId = -1;
  8144. }
  8145. }
  8146. /**
  8147. * The default filter used when constructing the tree. Keep everything that's visible.
  8148. */
  8149. function writeTreeDefaultFilter_(write) {
  8150. return write.visible;
  8151. }
  8152. /**
  8153. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8154. * event data at that path.
  8155. */
  8156. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8157. let compoundWrite = CompoundWrite.empty();
  8158. for (let i = 0; i < writes.length; ++i) {
  8159. const write = writes[i];
  8160. // Theory, a later set will either:
  8161. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8162. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8163. if (filter(write)) {
  8164. const writePath = write.path;
  8165. let relativePath;
  8166. if (write.snap) {
  8167. if (pathContains(treeRoot, writePath)) {
  8168. relativePath = newRelativePath(treeRoot, writePath);
  8169. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8170. }
  8171. else if (pathContains(writePath, treeRoot)) {
  8172. relativePath = newRelativePath(writePath, treeRoot);
  8173. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8174. }
  8175. else ;
  8176. }
  8177. else if (write.children) {
  8178. if (pathContains(treeRoot, writePath)) {
  8179. relativePath = newRelativePath(treeRoot, writePath);
  8180. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8181. }
  8182. else if (pathContains(writePath, treeRoot)) {
  8183. relativePath = newRelativePath(writePath, treeRoot);
  8184. if (pathIsEmpty(relativePath)) {
  8185. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8186. }
  8187. else {
  8188. const child = safeGet(write.children, pathGetFront(relativePath));
  8189. if (child) {
  8190. // There exists a child in this node that matches the root path
  8191. const deepNode = child.getChild(pathPopFront(relativePath));
  8192. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8193. }
  8194. }
  8195. }
  8196. else ;
  8197. }
  8198. else {
  8199. throw assertionError('WriteRecord should have .snap or .children');
  8200. }
  8201. }
  8202. }
  8203. return compoundWrite;
  8204. }
  8205. /**
  8206. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8207. * writes), attempt to calculate a complete snapshot for the given path
  8208. *
  8209. * @param writeIdsToExclude - An optional set to be excluded
  8210. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8211. */
  8212. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8213. if (!writeIdsToExclude && !includeHiddenWrites) {
  8214. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8215. if (shadowingNode != null) {
  8216. return shadowingNode;
  8217. }
  8218. else {
  8219. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8220. if (compoundWriteIsEmpty(subMerge)) {
  8221. return completeServerCache;
  8222. }
  8223. else if (completeServerCache == null &&
  8224. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8225. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8226. return null;
  8227. }
  8228. else {
  8229. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8230. return compoundWriteApply(subMerge, layeredCache);
  8231. }
  8232. }
  8233. }
  8234. else {
  8235. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8236. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8237. return completeServerCache;
  8238. }
  8239. else {
  8240. // If the server cache is null, and we don't have a complete cache, we need to return null
  8241. if (!includeHiddenWrites &&
  8242. completeServerCache == null &&
  8243. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8244. return null;
  8245. }
  8246. else {
  8247. const filter = function (write) {
  8248. return ((write.visible || includeHiddenWrites) &&
  8249. (!writeIdsToExclude ||
  8250. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8251. (pathContains(write.path, treePath) ||
  8252. pathContains(treePath, write.path)));
  8253. };
  8254. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8255. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8256. return compoundWriteApply(mergeAtPath, layeredCache);
  8257. }
  8258. }
  8259. }
  8260. }
  8261. /**
  8262. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8263. * Used when creating new views, to pre-fill their complete event children snapshot.
  8264. */
  8265. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8266. let completeChildren = ChildrenNode.EMPTY_NODE;
  8267. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8268. if (topLevelSet) {
  8269. if (!topLevelSet.isLeafNode()) {
  8270. // we're shadowing everything. Return the children.
  8271. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8272. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8273. });
  8274. }
  8275. return completeChildren;
  8276. }
  8277. else if (completeServerChildren) {
  8278. // Layer any children we have on top of this
  8279. // We know we don't have a top-level set, so just enumerate existing children
  8280. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8281. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8282. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8283. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8284. });
  8285. // Add any complete children we have from the set
  8286. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8287. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8288. });
  8289. return completeChildren;
  8290. }
  8291. else {
  8292. // We don't have anything to layer on top of. Layer on any children we have
  8293. // Note that we can return an empty snap if we have a defined delete
  8294. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8295. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8296. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8297. });
  8298. return completeChildren;
  8299. }
  8300. }
  8301. /**
  8302. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8303. * applied to the event cache.
  8304. *
  8305. * Possibilities:
  8306. *
  8307. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8308. *
  8309. * 2. Some write is completely shadowing. No events to be raised
  8310. *
  8311. * 3. Is partially shadowed. Events
  8312. *
  8313. * Either existingEventSnap or existingServerSnap must exist
  8314. */
  8315. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8316. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8317. const path = pathChild(treePath, childPath);
  8318. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8319. // At this point we can probably guarantee that we're in case 2, meaning no events
  8320. // May need to check visibility while doing the findRootMostValueAndPath call
  8321. return null;
  8322. }
  8323. else {
  8324. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8325. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8326. if (compoundWriteIsEmpty(childMerge)) {
  8327. // We're not shadowing at all. Case 1
  8328. return existingServerSnap.getChild(childPath);
  8329. }
  8330. else {
  8331. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8332. // However this is tricky to find out, since user updates don't necessary change the server
  8333. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8334. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8335. // only check if the updates change the serverNode.
  8336. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8337. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8338. }
  8339. }
  8340. }
  8341. /**
  8342. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8343. * complete child for this ChildKey.
  8344. */
  8345. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8346. const path = pathChild(treePath, childKey);
  8347. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8348. if (shadowingNode != null) {
  8349. return shadowingNode;
  8350. }
  8351. else {
  8352. if (existingServerSnap.isCompleteForChild(childKey)) {
  8353. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8354. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8355. }
  8356. else {
  8357. return null;
  8358. }
  8359. }
  8360. }
  8361. /**
  8362. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8363. * a higher path, this will return the child of that write relative to the write and this path.
  8364. * Returns null if there is no write at this path.
  8365. */
  8366. function writeTreeShadowingWrite(writeTree, path) {
  8367. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8368. }
  8369. /**
  8370. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8371. * the window, but may now be in the window.
  8372. */
  8373. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8374. let toIterate;
  8375. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8376. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8377. if (shadowingNode != null) {
  8378. toIterate = shadowingNode;
  8379. }
  8380. else if (completeServerData != null) {
  8381. toIterate = compoundWriteApply(merge, completeServerData);
  8382. }
  8383. else {
  8384. // no children to iterate on
  8385. return [];
  8386. }
  8387. toIterate = toIterate.withIndex(index);
  8388. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8389. const nodes = [];
  8390. const cmp = index.getCompare();
  8391. const iter = reverse
  8392. ? toIterate.getReverseIteratorFrom(startPost, index)
  8393. : toIterate.getIteratorFrom(startPost, index);
  8394. let next = iter.getNext();
  8395. while (next && nodes.length < count) {
  8396. if (cmp(next, startPost) !== 0) {
  8397. nodes.push(next);
  8398. }
  8399. next = iter.getNext();
  8400. }
  8401. return nodes;
  8402. }
  8403. else {
  8404. return [];
  8405. }
  8406. }
  8407. function newWriteTree() {
  8408. return {
  8409. visibleWrites: CompoundWrite.empty(),
  8410. allWrites: [],
  8411. lastWriteId: -1
  8412. };
  8413. }
  8414. /**
  8415. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8416. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8417. * can lead to a more expensive calculation.
  8418. *
  8419. * @param writeIdsToExclude - Optional writes to exclude.
  8420. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8421. */
  8422. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8423. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8424. }
  8425. /**
  8426. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8427. * mix of the given server data and write data.
  8428. *
  8429. */
  8430. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8431. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8432. }
  8433. /**
  8434. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8435. * if anything, needs to be applied to the event cache.
  8436. *
  8437. * Possibilities:
  8438. *
  8439. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8440. *
  8441. * 2. Some write is completely shadowing. No events to be raised
  8442. *
  8443. * 3. Is partially shadowed. Events should be raised
  8444. *
  8445. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8446. *
  8447. *
  8448. */
  8449. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8450. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8451. }
  8452. /**
  8453. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8454. * a higher path, this will return the child of that write relative to the write and this path.
  8455. * Returns null if there is no write at this path.
  8456. *
  8457. */
  8458. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8459. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8460. }
  8461. /**
  8462. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8463. * the window, but may now be in the window
  8464. */
  8465. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8466. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8467. }
  8468. /**
  8469. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8470. * complete child for this ChildKey.
  8471. */
  8472. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8473. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8474. }
  8475. /**
  8476. * Return a WriteTreeRef for a child.
  8477. */
  8478. function writeTreeRefChild(writeTreeRef, childName) {
  8479. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8480. }
  8481. function newWriteTreeRef(path, writeTree) {
  8482. return {
  8483. treePath: path,
  8484. writeTree
  8485. };
  8486. }
  8487. /**
  8488. * @license
  8489. * Copyright 2017 Google LLC
  8490. *
  8491. * Licensed under the Apache License, Version 2.0 (the "License");
  8492. * you may not use this file except in compliance with the License.
  8493. * You may obtain a copy of the License at
  8494. *
  8495. * http://www.apache.org/licenses/LICENSE-2.0
  8496. *
  8497. * Unless required by applicable law or agreed to in writing, software
  8498. * distributed under the License is distributed on an "AS IS" BASIS,
  8499. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8500. * See the License for the specific language governing permissions and
  8501. * limitations under the License.
  8502. */
  8503. class ChildChangeAccumulator {
  8504. constructor() {
  8505. this.changeMap = new Map();
  8506. }
  8507. trackChildChange(change) {
  8508. const type = change.type;
  8509. const childKey = change.childName;
  8510. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8511. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8512. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8513. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8514. const oldChange = this.changeMap.get(childKey);
  8515. if (oldChange) {
  8516. const oldType = oldChange.type;
  8517. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8518. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8519. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8520. }
  8521. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8522. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8523. this.changeMap.delete(childKey);
  8524. }
  8525. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8526. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8527. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8528. }
  8529. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8530. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8531. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8532. }
  8533. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8534. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8535. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8536. }
  8537. else {
  8538. throw assertionError('Illegal combination of changes: ' +
  8539. change +
  8540. ' occurred after ' +
  8541. oldChange);
  8542. }
  8543. }
  8544. else {
  8545. this.changeMap.set(childKey, change);
  8546. }
  8547. }
  8548. getChanges() {
  8549. return Array.from(this.changeMap.values());
  8550. }
  8551. }
  8552. /**
  8553. * @license
  8554. * Copyright 2017 Google LLC
  8555. *
  8556. * Licensed under the Apache License, Version 2.0 (the "License");
  8557. * you may not use this file except in compliance with the License.
  8558. * You may obtain a copy of the License at
  8559. *
  8560. * http://www.apache.org/licenses/LICENSE-2.0
  8561. *
  8562. * Unless required by applicable law or agreed to in writing, software
  8563. * distributed under the License is distributed on an "AS IS" BASIS,
  8564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8565. * See the License for the specific language governing permissions and
  8566. * limitations under the License.
  8567. */
  8568. /**
  8569. * An implementation of CompleteChildSource that never returns any additional children
  8570. */
  8571. // eslint-disable-next-line @typescript-eslint/naming-convention
  8572. class NoCompleteChildSource_ {
  8573. getCompleteChild(childKey) {
  8574. return null;
  8575. }
  8576. getChildAfterChild(index, child, reverse) {
  8577. return null;
  8578. }
  8579. }
  8580. /**
  8581. * Singleton instance.
  8582. */
  8583. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8584. /**
  8585. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8586. * old event caches available to calculate complete children.
  8587. */
  8588. class WriteTreeCompleteChildSource {
  8589. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8590. this.writes_ = writes_;
  8591. this.viewCache_ = viewCache_;
  8592. this.optCompleteServerCache_ = optCompleteServerCache_;
  8593. }
  8594. getCompleteChild(childKey) {
  8595. const node = this.viewCache_.eventCache;
  8596. if (node.isCompleteForChild(childKey)) {
  8597. return node.getNode().getImmediateChild(childKey);
  8598. }
  8599. else {
  8600. const serverNode = this.optCompleteServerCache_ != null
  8601. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8602. : this.viewCache_.serverCache;
  8603. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8604. }
  8605. }
  8606. getChildAfterChild(index, child, reverse) {
  8607. const completeServerData = this.optCompleteServerCache_ != null
  8608. ? this.optCompleteServerCache_
  8609. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8610. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8611. if (nodes.length === 0) {
  8612. return null;
  8613. }
  8614. else {
  8615. return nodes[0];
  8616. }
  8617. }
  8618. }
  8619. /**
  8620. * @license
  8621. * Copyright 2017 Google LLC
  8622. *
  8623. * Licensed under the Apache License, Version 2.0 (the "License");
  8624. * you may not use this file except in compliance with the License.
  8625. * You may obtain a copy of the License at
  8626. *
  8627. * http://www.apache.org/licenses/LICENSE-2.0
  8628. *
  8629. * Unless required by applicable law or agreed to in writing, software
  8630. * distributed under the License is distributed on an "AS IS" BASIS,
  8631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8632. * See the License for the specific language governing permissions and
  8633. * limitations under the License.
  8634. */
  8635. function newViewProcessor(filter) {
  8636. return { filter };
  8637. }
  8638. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8639. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8640. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8641. }
  8642. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8643. const accumulator = new ChildChangeAccumulator();
  8644. let newViewCache, filterServerNode;
  8645. if (operation.type === OperationType.OVERWRITE) {
  8646. const overwrite = operation;
  8647. if (overwrite.source.fromUser) {
  8648. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8649. }
  8650. else {
  8651. assert(overwrite.source.fromServer, 'Unknown source.');
  8652. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8653. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8654. // again
  8655. filterServerNode =
  8656. overwrite.source.tagged ||
  8657. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8658. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8659. }
  8660. }
  8661. else if (operation.type === OperationType.MERGE) {
  8662. const merge = operation;
  8663. if (merge.source.fromUser) {
  8664. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8665. }
  8666. else {
  8667. assert(merge.source.fromServer, 'Unknown source.');
  8668. // We filter the node if it's a tagged update or the node has been previously filtered
  8669. filterServerNode =
  8670. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8671. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8672. }
  8673. }
  8674. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8675. const ackUserWrite = operation;
  8676. if (!ackUserWrite.revert) {
  8677. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8678. }
  8679. else {
  8680. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8681. }
  8682. }
  8683. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8684. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8685. }
  8686. else {
  8687. throw assertionError('Unknown operation type: ' + operation.type);
  8688. }
  8689. const changes = accumulator.getChanges();
  8690. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8691. return { viewCache: newViewCache, changes };
  8692. }
  8693. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8694. const eventSnap = newViewCache.eventCache;
  8695. if (eventSnap.isFullyInitialized()) {
  8696. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8697. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8698. if (accumulator.length > 0 ||
  8699. !oldViewCache.eventCache.isFullyInitialized() ||
  8700. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8701. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8702. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8703. }
  8704. }
  8705. }
  8706. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8707. const oldEventSnap = viewCache.eventCache;
  8708. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8709. // we have a shadowing write, ignore changes
  8710. return viewCache;
  8711. }
  8712. else {
  8713. let newEventCache, serverNode;
  8714. if (pathIsEmpty(changePath)) {
  8715. // TODO: figure out how this plays with "sliding ack windows"
  8716. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8717. if (viewCache.serverCache.isFiltered()) {
  8718. // We need to special case this, because we need to only apply writes to complete children, or
  8719. // we might end up raising events for incomplete children. If the server data is filtered deep
  8720. // writes cannot be guaranteed to be complete
  8721. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8722. const completeChildren = serverCache instanceof ChildrenNode
  8723. ? serverCache
  8724. : ChildrenNode.EMPTY_NODE;
  8725. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8726. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8727. }
  8728. else {
  8729. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8730. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8731. }
  8732. }
  8733. else {
  8734. const childKey = pathGetFront(changePath);
  8735. if (childKey === '.priority') {
  8736. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8737. const oldEventNode = oldEventSnap.getNode();
  8738. serverNode = viewCache.serverCache.getNode();
  8739. // we might have overwrites for this priority
  8740. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8741. if (updatedPriority != null) {
  8742. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8743. }
  8744. else {
  8745. // priority didn't change, keep old node
  8746. newEventCache = oldEventSnap.getNode();
  8747. }
  8748. }
  8749. else {
  8750. const childChangePath = pathPopFront(changePath);
  8751. // update child
  8752. let newEventChild;
  8753. if (oldEventSnap.isCompleteForChild(childKey)) {
  8754. serverNode = viewCache.serverCache.getNode();
  8755. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8756. if (eventChildUpdate != null) {
  8757. newEventChild = oldEventSnap
  8758. .getNode()
  8759. .getImmediateChild(childKey)
  8760. .updateChild(childChangePath, eventChildUpdate);
  8761. }
  8762. else {
  8763. // Nothing changed, just keep the old child
  8764. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8765. }
  8766. }
  8767. else {
  8768. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8769. }
  8770. if (newEventChild != null) {
  8771. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8772. }
  8773. else {
  8774. // no complete child available or no change
  8775. newEventCache = oldEventSnap.getNode();
  8776. }
  8777. }
  8778. }
  8779. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8780. }
  8781. }
  8782. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8783. const oldServerSnap = oldViewCache.serverCache;
  8784. let newServerCache;
  8785. const serverFilter = filterServerNode
  8786. ? viewProcessor.filter
  8787. : viewProcessor.filter.getIndexedFilter();
  8788. if (pathIsEmpty(changePath)) {
  8789. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8790. }
  8791. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8792. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8793. const newServerNode = oldServerSnap
  8794. .getNode()
  8795. .updateChild(changePath, changedSnap);
  8796. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8797. }
  8798. else {
  8799. const childKey = pathGetFront(changePath);
  8800. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8801. pathGetLength(changePath) > 1) {
  8802. // We don't update incomplete nodes with updates intended for other listeners
  8803. return oldViewCache;
  8804. }
  8805. const childChangePath = pathPopFront(changePath);
  8806. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8807. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8808. if (childKey === '.priority') {
  8809. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8810. }
  8811. else {
  8812. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8813. }
  8814. }
  8815. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8816. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8817. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8818. }
  8819. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8820. const oldEventSnap = oldViewCache.eventCache;
  8821. let newViewCache, newEventCache;
  8822. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8823. if (pathIsEmpty(changePath)) {
  8824. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8825. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8826. }
  8827. else {
  8828. const childKey = pathGetFront(changePath);
  8829. if (childKey === '.priority') {
  8830. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8831. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8832. }
  8833. else {
  8834. const childChangePath = pathPopFront(changePath);
  8835. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8836. let newChild;
  8837. if (pathIsEmpty(childChangePath)) {
  8838. // Child overwrite, we can replace the child
  8839. newChild = changedSnap;
  8840. }
  8841. else {
  8842. const childNode = source.getCompleteChild(childKey);
  8843. if (childNode != null) {
  8844. if (pathGetBack(childChangePath) === '.priority' &&
  8845. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8846. // This is a priority update on an empty node. If this node exists on the server, the
  8847. // server will send down the priority in the update, so ignore for now
  8848. newChild = childNode;
  8849. }
  8850. else {
  8851. newChild = childNode.updateChild(childChangePath, changedSnap);
  8852. }
  8853. }
  8854. else {
  8855. // There is no complete child node available
  8856. newChild = ChildrenNode.EMPTY_NODE;
  8857. }
  8858. }
  8859. if (!oldChild.equals(newChild)) {
  8860. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8861. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8862. }
  8863. else {
  8864. newViewCache = oldViewCache;
  8865. }
  8866. }
  8867. }
  8868. return newViewCache;
  8869. }
  8870. function viewProcessorCacheHasChild(viewCache, childKey) {
  8871. return viewCache.eventCache.isCompleteForChild(childKey);
  8872. }
  8873. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8874. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8875. // window leaving room for new items. It's important we process these changes first, so we
  8876. // iterate the changes twice, first processing any that affect items currently in view.
  8877. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8878. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8879. // not the other.
  8880. let curViewCache = viewCache;
  8881. changedChildren.foreach((relativePath, childNode) => {
  8882. const writePath = pathChild(path, relativePath);
  8883. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8884. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8885. }
  8886. });
  8887. changedChildren.foreach((relativePath, childNode) => {
  8888. const writePath = pathChild(path, relativePath);
  8889. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8890. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8891. }
  8892. });
  8893. return curViewCache;
  8894. }
  8895. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8896. merge.foreach((relativePath, childNode) => {
  8897. node = node.updateChild(relativePath, childNode);
  8898. });
  8899. return node;
  8900. }
  8901. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8902. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8903. // wait for the complete data update coming soon.
  8904. if (viewCache.serverCache.getNode().isEmpty() &&
  8905. !viewCache.serverCache.isFullyInitialized()) {
  8906. return viewCache;
  8907. }
  8908. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8909. // window leaving room for new items. It's important we process these changes first, so we
  8910. // iterate the changes twice, first processing any that affect items currently in view.
  8911. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8912. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8913. // not the other.
  8914. let curViewCache = viewCache;
  8915. let viewMergeTree;
  8916. if (pathIsEmpty(path)) {
  8917. viewMergeTree = changedChildren;
  8918. }
  8919. else {
  8920. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8921. }
  8922. const serverNode = viewCache.serverCache.getNode();
  8923. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8924. if (serverNode.hasChild(childKey)) {
  8925. const serverChild = viewCache.serverCache
  8926. .getNode()
  8927. .getImmediateChild(childKey);
  8928. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8929. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8930. }
  8931. });
  8932. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8933. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8934. childMergeTree.value === null;
  8935. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8936. const serverChild = viewCache.serverCache
  8937. .getNode()
  8938. .getImmediateChild(childKey);
  8939. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8940. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8941. }
  8942. });
  8943. return curViewCache;
  8944. }
  8945. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8946. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8947. return viewCache;
  8948. }
  8949. // Only filter server node if it is currently filtered
  8950. const filterServerNode = viewCache.serverCache.isFiltered();
  8951. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8952. // now that it won't be shadowed.
  8953. const serverCache = viewCache.serverCache;
  8954. if (affectedTree.value != null) {
  8955. // This is an overwrite.
  8956. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8957. serverCache.isCompleteForPath(ackPath)) {
  8958. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8959. }
  8960. else if (pathIsEmpty(ackPath)) {
  8961. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8962. // should just re-apply whatever we have in our cache as a merge.
  8963. let changedChildren = new ImmutableTree(null);
  8964. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8965. changedChildren = changedChildren.set(new Path(name), node);
  8966. });
  8967. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8968. }
  8969. else {
  8970. return viewCache;
  8971. }
  8972. }
  8973. else {
  8974. // This is a merge.
  8975. let changedChildren = new ImmutableTree(null);
  8976. affectedTree.foreach((mergePath, value) => {
  8977. const serverCachePath = pathChild(ackPath, mergePath);
  8978. if (serverCache.isCompleteForPath(serverCachePath)) {
  8979. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8980. }
  8981. });
  8982. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8983. }
  8984. }
  8985. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8986. const oldServerNode = viewCache.serverCache;
  8987. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8988. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8989. }
  8990. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8991. let complete;
  8992. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8993. return viewCache;
  8994. }
  8995. else {
  8996. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8997. const oldEventCache = viewCache.eventCache.getNode();
  8998. let newEventCache;
  8999. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9000. let newNode;
  9001. if (viewCache.serverCache.isFullyInitialized()) {
  9002. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9003. }
  9004. else {
  9005. const serverChildren = viewCache.serverCache.getNode();
  9006. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9007. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9008. }
  9009. newNode = newNode;
  9010. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9011. }
  9012. else {
  9013. const childKey = pathGetFront(path);
  9014. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9015. if (newChild == null &&
  9016. viewCache.serverCache.isCompleteForChild(childKey)) {
  9017. newChild = oldEventCache.getImmediateChild(childKey);
  9018. }
  9019. if (newChild != null) {
  9020. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9021. }
  9022. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9023. // No complete child available, delete the existing one, if any
  9024. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9025. }
  9026. else {
  9027. newEventCache = oldEventCache;
  9028. }
  9029. if (newEventCache.isEmpty() &&
  9030. viewCache.serverCache.isFullyInitialized()) {
  9031. // We might have reverted all child writes. Maybe the old event was a leaf node
  9032. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9033. if (complete.isLeafNode()) {
  9034. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9035. }
  9036. }
  9037. }
  9038. complete =
  9039. viewCache.serverCache.isFullyInitialized() ||
  9040. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9041. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9042. }
  9043. }
  9044. /**
  9045. * @license
  9046. * Copyright 2017 Google LLC
  9047. *
  9048. * Licensed under the Apache License, Version 2.0 (the "License");
  9049. * you may not use this file except in compliance with the License.
  9050. * You may obtain a copy of the License at
  9051. *
  9052. * http://www.apache.org/licenses/LICENSE-2.0
  9053. *
  9054. * Unless required by applicable law or agreed to in writing, software
  9055. * distributed under the License is distributed on an "AS IS" BASIS,
  9056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9057. * See the License for the specific language governing permissions and
  9058. * limitations under the License.
  9059. */
  9060. /**
  9061. * A view represents a specific location and query that has 1 or more event registrations.
  9062. *
  9063. * It does several things:
  9064. * - Maintains the list of event registrations for this location/query.
  9065. * - Maintains a cache of the data visible for this location/query.
  9066. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9067. * registrations returns the set of events to be raised.
  9068. */
  9069. class View {
  9070. constructor(query_, initialViewCache) {
  9071. this.query_ = query_;
  9072. this.eventRegistrations_ = [];
  9073. const params = this.query_._queryParams;
  9074. const indexFilter = new IndexedFilter(params.getIndex());
  9075. const filter = queryParamsGetNodeFilter(params);
  9076. this.processor_ = newViewProcessor(filter);
  9077. const initialServerCache = initialViewCache.serverCache;
  9078. const initialEventCache = initialViewCache.eventCache;
  9079. // Don't filter server node with other filter than index, wait for tagged listen
  9080. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9081. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9082. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9083. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9084. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9085. this.eventGenerator_ = new EventGenerator(this.query_);
  9086. }
  9087. get query() {
  9088. return this.query_;
  9089. }
  9090. }
  9091. function viewGetServerCache(view) {
  9092. return view.viewCache_.serverCache.getNode();
  9093. }
  9094. function viewGetCompleteNode(view) {
  9095. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9096. }
  9097. function viewGetCompleteServerCache(view, path) {
  9098. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9099. if (cache) {
  9100. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9101. // we need to see if it contains the child we're interested in.
  9102. if (view.query._queryParams.loadsAllData() ||
  9103. (!pathIsEmpty(path) &&
  9104. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9105. return cache.getChild(path);
  9106. }
  9107. }
  9108. return null;
  9109. }
  9110. function viewIsEmpty(view) {
  9111. return view.eventRegistrations_.length === 0;
  9112. }
  9113. function viewAddEventRegistration(view, eventRegistration) {
  9114. view.eventRegistrations_.push(eventRegistration);
  9115. }
  9116. /**
  9117. * @param eventRegistration - If null, remove all callbacks.
  9118. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9119. * @returns Cancel events, if cancelError was provided.
  9120. */
  9121. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9122. const cancelEvents = [];
  9123. if (cancelError) {
  9124. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9125. const path = view.query._path;
  9126. view.eventRegistrations_.forEach(registration => {
  9127. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9128. if (maybeEvent) {
  9129. cancelEvents.push(maybeEvent);
  9130. }
  9131. });
  9132. }
  9133. if (eventRegistration) {
  9134. let remaining = [];
  9135. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9136. const existing = view.eventRegistrations_[i];
  9137. if (!existing.matches(eventRegistration)) {
  9138. remaining.push(existing);
  9139. }
  9140. else if (eventRegistration.hasAnyCallback()) {
  9141. // We're removing just this one
  9142. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9143. break;
  9144. }
  9145. }
  9146. view.eventRegistrations_ = remaining;
  9147. }
  9148. else {
  9149. view.eventRegistrations_ = [];
  9150. }
  9151. return cancelEvents;
  9152. }
  9153. /**
  9154. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9155. */
  9156. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9157. if (operation.type === OperationType.MERGE &&
  9158. operation.source.queryId !== null) {
  9159. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9160. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9161. }
  9162. const oldViewCache = view.viewCache_;
  9163. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9164. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9165. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9166. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9167. view.viewCache_ = result.viewCache;
  9168. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9169. }
  9170. function viewGetInitialEvents(view, registration) {
  9171. const eventSnap = view.viewCache_.eventCache;
  9172. const initialChanges = [];
  9173. if (!eventSnap.getNode().isLeafNode()) {
  9174. const eventNode = eventSnap.getNode();
  9175. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9176. initialChanges.push(changeChildAdded(key, childNode));
  9177. });
  9178. }
  9179. if (eventSnap.isFullyInitialized()) {
  9180. initialChanges.push(changeValue(eventSnap.getNode()));
  9181. }
  9182. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9183. }
  9184. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9185. const registrations = eventRegistration
  9186. ? [eventRegistration]
  9187. : view.eventRegistrations_;
  9188. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9189. }
  9190. /**
  9191. * @license
  9192. * Copyright 2017 Google LLC
  9193. *
  9194. * Licensed under the Apache License, Version 2.0 (the "License");
  9195. * you may not use this file except in compliance with the License.
  9196. * You may obtain a copy of the License at
  9197. *
  9198. * http://www.apache.org/licenses/LICENSE-2.0
  9199. *
  9200. * Unless required by applicable law or agreed to in writing, software
  9201. * distributed under the License is distributed on an "AS IS" BASIS,
  9202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9203. * See the License for the specific language governing permissions and
  9204. * limitations under the License.
  9205. */
  9206. let referenceConstructor$1;
  9207. /**
  9208. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9209. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9210. * and user writes (set, transaction, update).
  9211. *
  9212. * It's responsible for:
  9213. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9214. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9215. * applyUserOverwrite, etc.)
  9216. */
  9217. class SyncPoint {
  9218. constructor() {
  9219. /**
  9220. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9221. * queryId and the value is the View for that query.
  9222. *
  9223. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9224. */
  9225. this.views = new Map();
  9226. }
  9227. }
  9228. function syncPointSetReferenceConstructor(val) {
  9229. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9230. referenceConstructor$1 = val;
  9231. }
  9232. function syncPointGetReferenceConstructor() {
  9233. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9234. return referenceConstructor$1;
  9235. }
  9236. function syncPointIsEmpty(syncPoint) {
  9237. return syncPoint.views.size === 0;
  9238. }
  9239. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9240. const queryId = operation.source.queryId;
  9241. if (queryId !== null) {
  9242. const view = syncPoint.views.get(queryId);
  9243. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9244. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9245. }
  9246. else {
  9247. let events = [];
  9248. for (const view of syncPoint.views.values()) {
  9249. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9250. }
  9251. return events;
  9252. }
  9253. }
  9254. /**
  9255. * Get a view for the specified query.
  9256. *
  9257. * @param query - The query to return a view for
  9258. * @param writesCache
  9259. * @param serverCache
  9260. * @param serverCacheComplete
  9261. * @returns Events to raise.
  9262. */
  9263. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9264. const queryId = query._queryIdentifier;
  9265. const view = syncPoint.views.get(queryId);
  9266. if (!view) {
  9267. // TODO: make writesCache take flag for complete server node
  9268. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9269. let eventCacheComplete = false;
  9270. if (eventCache) {
  9271. eventCacheComplete = true;
  9272. }
  9273. else if (serverCache instanceof ChildrenNode) {
  9274. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9275. eventCacheComplete = false;
  9276. }
  9277. else {
  9278. eventCache = ChildrenNode.EMPTY_NODE;
  9279. eventCacheComplete = false;
  9280. }
  9281. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9282. return new View(query, viewCache);
  9283. }
  9284. return view;
  9285. }
  9286. /**
  9287. * Add an event callback for the specified query.
  9288. *
  9289. * @param query
  9290. * @param eventRegistration
  9291. * @param writesCache
  9292. * @param serverCache - Complete server cache, if we have it.
  9293. * @param serverCacheComplete
  9294. * @returns Events to raise.
  9295. */
  9296. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9297. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9298. if (!syncPoint.views.has(query._queryIdentifier)) {
  9299. syncPoint.views.set(query._queryIdentifier, view);
  9300. }
  9301. // This is guaranteed to exist now, we just created anything that was missing
  9302. viewAddEventRegistration(view, eventRegistration);
  9303. return viewGetInitialEvents(view, eventRegistration);
  9304. }
  9305. /**
  9306. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9307. *
  9308. * If query is the default query, we'll check all views for the specified eventRegistration.
  9309. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9310. *
  9311. * @param eventRegistration - If null, remove all callbacks.
  9312. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9313. * @returns removed queries and any cancel events
  9314. */
  9315. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9316. const queryId = query._queryIdentifier;
  9317. const removed = [];
  9318. let cancelEvents = [];
  9319. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9320. if (queryId === 'default') {
  9321. // When you do ref.off(...), we search all views for the registration to remove.
  9322. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9323. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9324. if (viewIsEmpty(view)) {
  9325. syncPoint.views.delete(viewQueryId);
  9326. // We'll deal with complete views later.
  9327. if (!view.query._queryParams.loadsAllData()) {
  9328. removed.push(view.query);
  9329. }
  9330. }
  9331. }
  9332. }
  9333. else {
  9334. // remove the callback from the specific view.
  9335. const view = syncPoint.views.get(queryId);
  9336. if (view) {
  9337. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9338. if (viewIsEmpty(view)) {
  9339. syncPoint.views.delete(queryId);
  9340. // We'll deal with complete views later.
  9341. if (!view.query._queryParams.loadsAllData()) {
  9342. removed.push(view.query);
  9343. }
  9344. }
  9345. }
  9346. }
  9347. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9348. // We removed our last complete view.
  9349. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9350. }
  9351. return { removed, events: cancelEvents };
  9352. }
  9353. function syncPointGetQueryViews(syncPoint) {
  9354. const result = [];
  9355. for (const view of syncPoint.views.values()) {
  9356. if (!view.query._queryParams.loadsAllData()) {
  9357. result.push(view);
  9358. }
  9359. }
  9360. return result;
  9361. }
  9362. /**
  9363. * @param path - The path to the desired complete snapshot
  9364. * @returns A complete cache, if it exists
  9365. */
  9366. function syncPointGetCompleteServerCache(syncPoint, path) {
  9367. let serverCache = null;
  9368. for (const view of syncPoint.views.values()) {
  9369. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9370. }
  9371. return serverCache;
  9372. }
  9373. function syncPointViewForQuery(syncPoint, query) {
  9374. const params = query._queryParams;
  9375. if (params.loadsAllData()) {
  9376. return syncPointGetCompleteView(syncPoint);
  9377. }
  9378. else {
  9379. const queryId = query._queryIdentifier;
  9380. return syncPoint.views.get(queryId);
  9381. }
  9382. }
  9383. function syncPointViewExistsForQuery(syncPoint, query) {
  9384. return syncPointViewForQuery(syncPoint, query) != null;
  9385. }
  9386. function syncPointHasCompleteView(syncPoint) {
  9387. return syncPointGetCompleteView(syncPoint) != null;
  9388. }
  9389. function syncPointGetCompleteView(syncPoint) {
  9390. for (const view of syncPoint.views.values()) {
  9391. if (view.query._queryParams.loadsAllData()) {
  9392. return view;
  9393. }
  9394. }
  9395. return null;
  9396. }
  9397. /**
  9398. * @license
  9399. * Copyright 2017 Google LLC
  9400. *
  9401. * Licensed under the Apache License, Version 2.0 (the "License");
  9402. * you may not use this file except in compliance with the License.
  9403. * You may obtain a copy of the License at
  9404. *
  9405. * http://www.apache.org/licenses/LICENSE-2.0
  9406. *
  9407. * Unless required by applicable law or agreed to in writing, software
  9408. * distributed under the License is distributed on an "AS IS" BASIS,
  9409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9410. * See the License for the specific language governing permissions and
  9411. * limitations under the License.
  9412. */
  9413. let referenceConstructor;
  9414. function syncTreeSetReferenceConstructor(val) {
  9415. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9416. referenceConstructor = val;
  9417. }
  9418. function syncTreeGetReferenceConstructor() {
  9419. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9420. return referenceConstructor;
  9421. }
  9422. /**
  9423. * Static tracker for next query tag.
  9424. */
  9425. let syncTreeNextQueryTag_ = 1;
  9426. /**
  9427. * SyncTree is the central class for managing event callback registration, data caching, views
  9428. * (query processing), and event generation. There are typically two SyncTree instances for
  9429. * each Repo, one for the normal Firebase data, and one for the .info data.
  9430. *
  9431. * It has a number of responsibilities, including:
  9432. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9433. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9434. * (applyUserOverwrite(), applyUserMerge()).
  9435. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9436. * applyServerMerge()).
  9437. * - Generating user-facing events for server and user changes (all of the apply* methods
  9438. * return the set of events that need to be raised as a result).
  9439. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9440. * to the correct set of paths and queries to satisfy the current set of user event
  9441. * callbacks (listens are started/stopped using the provided listenProvider).
  9442. *
  9443. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9444. * events are returned to the caller rather than raised synchronously.
  9445. *
  9446. */
  9447. class SyncTree {
  9448. /**
  9449. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9450. * to server data.
  9451. */
  9452. constructor(listenProvider_) {
  9453. this.listenProvider_ = listenProvider_;
  9454. /**
  9455. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9456. */
  9457. this.syncPointTree_ = new ImmutableTree(null);
  9458. /**
  9459. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9460. */
  9461. this.pendingWriteTree_ = newWriteTree();
  9462. this.tagToQueryMap = new Map();
  9463. this.queryToTagMap = new Map();
  9464. }
  9465. }
  9466. /**
  9467. * Apply the data changes for a user-generated set() or transaction() call.
  9468. *
  9469. * @returns Events to raise.
  9470. */
  9471. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9472. // Record pending write.
  9473. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9474. if (!visible) {
  9475. return [];
  9476. }
  9477. else {
  9478. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9479. }
  9480. }
  9481. /**
  9482. * Apply the data from a user-generated update() call
  9483. *
  9484. * @returns Events to raise.
  9485. */
  9486. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9487. // Record pending merge.
  9488. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9489. const changeTree = ImmutableTree.fromObject(changedChildren);
  9490. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9491. }
  9492. /**
  9493. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9494. *
  9495. * @param revert - True if the given write failed and needs to be reverted
  9496. * @returns Events to raise.
  9497. */
  9498. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9499. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9500. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9501. if (!needToReevaluate) {
  9502. return [];
  9503. }
  9504. else {
  9505. let affectedTree = new ImmutableTree(null);
  9506. if (write.snap != null) {
  9507. // overwrite
  9508. affectedTree = affectedTree.set(newEmptyPath(), true);
  9509. }
  9510. else {
  9511. each(write.children, (pathString) => {
  9512. affectedTree = affectedTree.set(new Path(pathString), true);
  9513. });
  9514. }
  9515. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9516. }
  9517. }
  9518. /**
  9519. * Apply new server data for the specified path..
  9520. *
  9521. * @returns Events to raise.
  9522. */
  9523. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9524. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9525. }
  9526. /**
  9527. * Apply new server data to be merged in at the specified path.
  9528. *
  9529. * @returns Events to raise.
  9530. */
  9531. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9532. const changeTree = ImmutableTree.fromObject(changedChildren);
  9533. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9534. }
  9535. /**
  9536. * Apply a listen complete for a query
  9537. *
  9538. * @returns Events to raise.
  9539. */
  9540. function syncTreeApplyListenComplete(syncTree, path) {
  9541. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9542. }
  9543. /**
  9544. * Apply a listen complete for a tagged query
  9545. *
  9546. * @returns Events to raise.
  9547. */
  9548. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9549. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9550. if (queryKey) {
  9551. const r = syncTreeParseQueryKey_(queryKey);
  9552. const queryPath = r.path, queryId = r.queryId;
  9553. const relativePath = newRelativePath(queryPath, path);
  9554. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9555. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9556. }
  9557. else {
  9558. // We've already removed the query. No big deal, ignore the update
  9559. return [];
  9560. }
  9561. }
  9562. /**
  9563. * Remove event callback(s).
  9564. *
  9565. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9566. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9567. *
  9568. * @param eventRegistration - If null, all callbacks are removed.
  9569. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9570. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9571. * deduping needs to take place. This flag allows toggling of that behavior
  9572. * @returns Cancel events, if cancelError was provided.
  9573. */
  9574. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9575. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9576. const path = query._path;
  9577. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9578. let cancelEvents = [];
  9579. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9580. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9581. // not loadsAllData().
  9582. if (maybeSyncPoint &&
  9583. (query._queryIdentifier === 'default' ||
  9584. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9585. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9586. if (syncPointIsEmpty(maybeSyncPoint)) {
  9587. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9588. }
  9589. const removed = removedAndEvents.removed;
  9590. cancelEvents = removedAndEvents.events;
  9591. if (!skipListenerDedup) {
  9592. /**
  9593. * We may have just removed one of many listeners and can short-circuit this whole process
  9594. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9595. * properly set up.
  9596. */
  9597. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9598. // queryId === 'default'
  9599. const removingDefault = -1 !==
  9600. removed.findIndex(query => {
  9601. return query._queryParams.loadsAllData();
  9602. });
  9603. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9604. if (removingDefault && !covered) {
  9605. const subtree = syncTree.syncPointTree_.subtree(path);
  9606. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9607. // removal
  9608. if (!subtree.isEmpty()) {
  9609. // We need to fold over our subtree and collect the listeners to send
  9610. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9611. // Ok, we've collected all the listens we need. Set them up.
  9612. for (let i = 0; i < newViews.length; ++i) {
  9613. const view = newViews[i], newQuery = view.query;
  9614. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9615. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9616. }
  9617. }
  9618. // Otherwise there's nothing below us, so nothing we need to start listening on
  9619. }
  9620. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9621. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9622. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9623. if (!covered && removed.length > 0 && !cancelError) {
  9624. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9625. // default. Otherwise, we need to iterate through and cancel each individual query
  9626. if (removingDefault) {
  9627. // We don't tag default listeners
  9628. const defaultTag = null;
  9629. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9630. }
  9631. else {
  9632. removed.forEach((queryToRemove) => {
  9633. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9634. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9635. });
  9636. }
  9637. }
  9638. }
  9639. // Now, clear all of the tags we're tracking for the removed listens
  9640. syncTreeRemoveTags_(syncTree, removed);
  9641. }
  9642. return cancelEvents;
  9643. }
  9644. /**
  9645. * Apply new server data for the specified tagged query.
  9646. *
  9647. * @returns Events to raise.
  9648. */
  9649. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9650. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9651. if (queryKey != null) {
  9652. const r = syncTreeParseQueryKey_(queryKey);
  9653. const queryPath = r.path, queryId = r.queryId;
  9654. const relativePath = newRelativePath(queryPath, path);
  9655. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9656. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9657. }
  9658. else {
  9659. // Query must have been removed already
  9660. return [];
  9661. }
  9662. }
  9663. /**
  9664. * Apply server data to be merged in for the specified tagged query.
  9665. *
  9666. * @returns Events to raise.
  9667. */
  9668. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9669. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9670. if (queryKey) {
  9671. const r = syncTreeParseQueryKey_(queryKey);
  9672. const queryPath = r.path, queryId = r.queryId;
  9673. const relativePath = newRelativePath(queryPath, path);
  9674. const changeTree = ImmutableTree.fromObject(changedChildren);
  9675. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9676. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9677. }
  9678. else {
  9679. // We've already removed the query. No big deal, ignore the update
  9680. return [];
  9681. }
  9682. }
  9683. /**
  9684. * Add an event callback for the specified query.
  9685. *
  9686. * @returns Events to raise.
  9687. */
  9688. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9689. const path = query._path;
  9690. let serverCache = null;
  9691. let foundAncestorDefaultView = false;
  9692. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9693. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9694. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9695. const relativePath = newRelativePath(pathToSyncPoint, path);
  9696. serverCache =
  9697. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9698. foundAncestorDefaultView =
  9699. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9700. });
  9701. let syncPoint = syncTree.syncPointTree_.get(path);
  9702. if (!syncPoint) {
  9703. syncPoint = new SyncPoint();
  9704. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9705. }
  9706. else {
  9707. foundAncestorDefaultView =
  9708. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9709. serverCache =
  9710. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9711. }
  9712. let serverCacheComplete;
  9713. if (serverCache != null) {
  9714. serverCacheComplete = true;
  9715. }
  9716. else {
  9717. serverCacheComplete = false;
  9718. serverCache = ChildrenNode.EMPTY_NODE;
  9719. const subtree = syncTree.syncPointTree_.subtree(path);
  9720. subtree.foreachChild((childName, childSyncPoint) => {
  9721. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9722. if (completeCache) {
  9723. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9724. }
  9725. });
  9726. }
  9727. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9728. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9729. // We need to track a tag for this query
  9730. const queryKey = syncTreeMakeQueryKey_(query);
  9731. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9732. const tag = syncTreeGetNextQueryTag_();
  9733. syncTree.queryToTagMap.set(queryKey, tag);
  9734. syncTree.tagToQueryMap.set(tag, queryKey);
  9735. }
  9736. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9737. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9738. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9739. const view = syncPointViewForQuery(syncPoint, query);
  9740. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9741. }
  9742. return events;
  9743. }
  9744. /**
  9745. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9746. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9747. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9748. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9749. *
  9750. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9751. *
  9752. * @param path - The path to the data we want
  9753. * @param writeIdsToExclude - A specific set to be excluded
  9754. */
  9755. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9756. const includeHiddenSets = true;
  9757. const writeTree = syncTree.pendingWriteTree_;
  9758. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9759. const relativePath = newRelativePath(pathSoFar, path);
  9760. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9761. if (serverCache) {
  9762. return serverCache;
  9763. }
  9764. });
  9765. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9766. }
  9767. function syncTreeGetServerValue(syncTree, query) {
  9768. const path = query._path;
  9769. let serverCache = null;
  9770. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9771. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9772. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9773. const relativePath = newRelativePath(pathToSyncPoint, path);
  9774. serverCache =
  9775. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9776. });
  9777. let syncPoint = syncTree.syncPointTree_.get(path);
  9778. if (!syncPoint) {
  9779. syncPoint = new SyncPoint();
  9780. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9781. }
  9782. else {
  9783. serverCache =
  9784. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9785. }
  9786. const serverCacheComplete = serverCache != null;
  9787. const serverCacheNode = serverCacheComplete
  9788. ? new CacheNode(serverCache, true, false)
  9789. : null;
  9790. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9791. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9792. return viewGetCompleteNode(view);
  9793. }
  9794. /**
  9795. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9796. *
  9797. * NOTES:
  9798. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9799. *
  9800. * - We call applyOperation() on each SyncPoint passing three things:
  9801. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9802. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9803. * 3. A snapshot Node with cached server data, if we have it.
  9804. *
  9805. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9806. */
  9807. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9808. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9809. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9810. }
  9811. /**
  9812. * Recursive helper for applyOperationToSyncPoints_
  9813. */
  9814. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9815. if (pathIsEmpty(operation.path)) {
  9816. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9817. }
  9818. else {
  9819. const syncPoint = syncPointTree.get(newEmptyPath());
  9820. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9821. if (serverCache == null && syncPoint != null) {
  9822. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9823. }
  9824. let events = [];
  9825. const childName = pathGetFront(operation.path);
  9826. const childOperation = operation.operationForChild(childName);
  9827. const childTree = syncPointTree.children.get(childName);
  9828. if (childTree && childOperation) {
  9829. const childServerCache = serverCache
  9830. ? serverCache.getImmediateChild(childName)
  9831. : null;
  9832. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9833. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9834. }
  9835. if (syncPoint) {
  9836. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9837. }
  9838. return events;
  9839. }
  9840. }
  9841. /**
  9842. * Recursive helper for applyOperationToSyncPoints_
  9843. */
  9844. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9845. const syncPoint = syncPointTree.get(newEmptyPath());
  9846. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9847. if (serverCache == null && syncPoint != null) {
  9848. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9849. }
  9850. let events = [];
  9851. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9852. const childServerCache = serverCache
  9853. ? serverCache.getImmediateChild(childName)
  9854. : null;
  9855. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9856. const childOperation = operation.operationForChild(childName);
  9857. if (childOperation) {
  9858. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9859. }
  9860. });
  9861. if (syncPoint) {
  9862. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9863. }
  9864. return events;
  9865. }
  9866. function syncTreeCreateListenerForView_(syncTree, view) {
  9867. const query = view.query;
  9868. const tag = syncTreeTagForQuery(syncTree, query);
  9869. return {
  9870. hashFn: () => {
  9871. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9872. return cache.hash();
  9873. },
  9874. onComplete: (status) => {
  9875. if (status === 'ok') {
  9876. if (tag) {
  9877. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9878. }
  9879. else {
  9880. return syncTreeApplyListenComplete(syncTree, query._path);
  9881. }
  9882. }
  9883. else {
  9884. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9885. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9886. const error = errorForServerCode(status, query);
  9887. return syncTreeRemoveEventRegistration(syncTree, query,
  9888. /*eventRegistration*/ null, error);
  9889. }
  9890. }
  9891. };
  9892. }
  9893. /**
  9894. * Return the tag associated with the given query.
  9895. */
  9896. function syncTreeTagForQuery(syncTree, query) {
  9897. const queryKey = syncTreeMakeQueryKey_(query);
  9898. return syncTree.queryToTagMap.get(queryKey);
  9899. }
  9900. /**
  9901. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9902. */
  9903. function syncTreeMakeQueryKey_(query) {
  9904. return query._path.toString() + '$' + query._queryIdentifier;
  9905. }
  9906. /**
  9907. * Return the query associated with the given tag, if we have one
  9908. */
  9909. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9910. return syncTree.tagToQueryMap.get(tag);
  9911. }
  9912. /**
  9913. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9914. */
  9915. function syncTreeParseQueryKey_(queryKey) {
  9916. const splitIndex = queryKey.indexOf('$');
  9917. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9918. return {
  9919. queryId: queryKey.substr(splitIndex + 1),
  9920. path: new Path(queryKey.substr(0, splitIndex))
  9921. };
  9922. }
  9923. /**
  9924. * A helper method to apply tagged operations
  9925. */
  9926. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9927. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9928. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9929. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9930. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9931. }
  9932. /**
  9933. * This collapses multiple unfiltered views into a single view, since we only need a single
  9934. * listener for them.
  9935. */
  9936. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9937. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9938. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9939. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9940. return [completeView];
  9941. }
  9942. else {
  9943. // No complete view here, flatten any deeper listens into an array
  9944. let views = [];
  9945. if (maybeChildSyncPoint) {
  9946. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9947. }
  9948. each(childMap, (_key, childViews) => {
  9949. views = views.concat(childViews);
  9950. });
  9951. return views;
  9952. }
  9953. });
  9954. }
  9955. /**
  9956. * Normalizes a query to a query we send the server for listening
  9957. *
  9958. * @returns The normalized query
  9959. */
  9960. function syncTreeQueryForListening_(query) {
  9961. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9962. // We treat queries that load all data as default queries
  9963. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9964. // from Query
  9965. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9966. }
  9967. else {
  9968. return query;
  9969. }
  9970. }
  9971. function syncTreeRemoveTags_(syncTree, queries) {
  9972. for (let j = 0; j < queries.length; ++j) {
  9973. const removedQuery = queries[j];
  9974. if (!removedQuery._queryParams.loadsAllData()) {
  9975. // We should have a tag for this
  9976. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9977. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9978. syncTree.queryToTagMap.delete(removedQueryKey);
  9979. syncTree.tagToQueryMap.delete(removedQueryTag);
  9980. }
  9981. }
  9982. }
  9983. /**
  9984. * Static accessor for query tags.
  9985. */
  9986. function syncTreeGetNextQueryTag_() {
  9987. return syncTreeNextQueryTag_++;
  9988. }
  9989. /**
  9990. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9991. *
  9992. * @returns This method can return events to support synchronous data sources
  9993. */
  9994. function syncTreeSetupListener_(syncTree, query, view) {
  9995. const path = query._path;
  9996. const tag = syncTreeTagForQuery(syncTree, query);
  9997. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9998. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9999. const subtree = syncTree.syncPointTree_.subtree(path);
  10000. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10001. // may need to shadow other listens as well.
  10002. if (tag) {
  10003. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10004. }
  10005. else {
  10006. // Shadow everything at or below this location, this is a default listener.
  10007. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10008. if (!pathIsEmpty(relativePath) &&
  10009. maybeChildSyncPoint &&
  10010. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10011. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10012. }
  10013. else {
  10014. // No default listener here, flatten any deeper queries into an array
  10015. let queries = [];
  10016. if (maybeChildSyncPoint) {
  10017. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10018. }
  10019. each(childMap, (_key, childQueries) => {
  10020. queries = queries.concat(childQueries);
  10021. });
  10022. return queries;
  10023. }
  10024. });
  10025. for (let i = 0; i < queriesToStop.length; ++i) {
  10026. const queryToStop = queriesToStop[i];
  10027. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10028. }
  10029. }
  10030. return events;
  10031. }
  10032. /**
  10033. * @license
  10034. * Copyright 2017 Google LLC
  10035. *
  10036. * Licensed under the Apache License, Version 2.0 (the "License");
  10037. * you may not use this file except in compliance with the License.
  10038. * You may obtain a copy of the License at
  10039. *
  10040. * http://www.apache.org/licenses/LICENSE-2.0
  10041. *
  10042. * Unless required by applicable law or agreed to in writing, software
  10043. * distributed under the License is distributed on an "AS IS" BASIS,
  10044. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10045. * See the License for the specific language governing permissions and
  10046. * limitations under the License.
  10047. */
  10048. class ExistingValueProvider {
  10049. constructor(node_) {
  10050. this.node_ = node_;
  10051. }
  10052. getImmediateChild(childName) {
  10053. const child = this.node_.getImmediateChild(childName);
  10054. return new ExistingValueProvider(child);
  10055. }
  10056. node() {
  10057. return this.node_;
  10058. }
  10059. }
  10060. class DeferredValueProvider {
  10061. constructor(syncTree, path) {
  10062. this.syncTree_ = syncTree;
  10063. this.path_ = path;
  10064. }
  10065. getImmediateChild(childName) {
  10066. const childPath = pathChild(this.path_, childName);
  10067. return new DeferredValueProvider(this.syncTree_, childPath);
  10068. }
  10069. node() {
  10070. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10071. }
  10072. }
  10073. /**
  10074. * Generate placeholders for deferred values.
  10075. */
  10076. const generateWithValues = function (values) {
  10077. values = values || {};
  10078. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10079. return values;
  10080. };
  10081. /**
  10082. * Value to use when firing local events. When writing server values, fire
  10083. * local events with an approximate value, otherwise return value as-is.
  10084. */
  10085. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10086. if (!value || typeof value !== 'object') {
  10087. return value;
  10088. }
  10089. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10090. if (typeof value['.sv'] === 'string') {
  10091. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10092. }
  10093. else if (typeof value['.sv'] === 'object') {
  10094. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10095. }
  10096. else {
  10097. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10098. }
  10099. };
  10100. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10101. switch (op) {
  10102. case 'timestamp':
  10103. return serverValues['timestamp'];
  10104. default:
  10105. assert(false, 'Unexpected server value: ' + op);
  10106. }
  10107. };
  10108. const resolveComplexDeferredValue = function (op, existing, unused) {
  10109. if (!op.hasOwnProperty('increment')) {
  10110. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10111. }
  10112. const delta = op['increment'];
  10113. if (typeof delta !== 'number') {
  10114. assert(false, 'Unexpected increment value: ' + delta);
  10115. }
  10116. const existingNode = existing.node();
  10117. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10118. // Incrementing a non-number sets the value to the incremented amount
  10119. if (!existingNode.isLeafNode()) {
  10120. return delta;
  10121. }
  10122. const leaf = existingNode;
  10123. const existingVal = leaf.getValue();
  10124. if (typeof existingVal !== 'number') {
  10125. return delta;
  10126. }
  10127. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10128. return existingVal + delta;
  10129. };
  10130. /**
  10131. * Recursively replace all deferred values and priorities in the tree with the
  10132. * specified generated replacement values.
  10133. * @param path - path to which write is relative
  10134. * @param node - new data written at path
  10135. * @param syncTree - current data
  10136. */
  10137. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10138. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10139. };
  10140. /**
  10141. * Recursively replace all deferred values and priorities in the node with the
  10142. * specified generated replacement values. If there are no server values in the node,
  10143. * it'll be returned as-is.
  10144. */
  10145. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10146. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10147. };
  10148. function resolveDeferredValue(node, existingVal, serverValues) {
  10149. const rawPri = node.getPriority().val();
  10150. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10151. let newNode;
  10152. if (node.isLeafNode()) {
  10153. const leafNode = node;
  10154. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10155. if (value !== leafNode.getValue() ||
  10156. priority !== leafNode.getPriority().val()) {
  10157. return new LeafNode(value, nodeFromJSON(priority));
  10158. }
  10159. else {
  10160. return node;
  10161. }
  10162. }
  10163. else {
  10164. const childrenNode = node;
  10165. newNode = childrenNode;
  10166. if (priority !== childrenNode.getPriority().val()) {
  10167. newNode = newNode.updatePriority(new LeafNode(priority));
  10168. }
  10169. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10170. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10171. if (newChildNode !== childNode) {
  10172. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10173. }
  10174. });
  10175. return newNode;
  10176. }
  10177. }
  10178. /**
  10179. * @license
  10180. * Copyright 2017 Google LLC
  10181. *
  10182. * Licensed under the Apache License, Version 2.0 (the "License");
  10183. * you may not use this file except in compliance with the License.
  10184. * You may obtain a copy of the License at
  10185. *
  10186. * http://www.apache.org/licenses/LICENSE-2.0
  10187. *
  10188. * Unless required by applicable law or agreed to in writing, software
  10189. * distributed under the License is distributed on an "AS IS" BASIS,
  10190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10191. * See the License for the specific language governing permissions and
  10192. * limitations under the License.
  10193. */
  10194. /**
  10195. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10196. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10197. * children.
  10198. */
  10199. class Tree {
  10200. /**
  10201. * @param name - Optional name of the node.
  10202. * @param parent - Optional parent node.
  10203. * @param node - Optional node to wrap.
  10204. */
  10205. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10206. this.name = name;
  10207. this.parent = parent;
  10208. this.node = node;
  10209. }
  10210. }
  10211. /**
  10212. * Returns a sub-Tree for the given path.
  10213. *
  10214. * @param pathObj - Path to look up.
  10215. * @returns Tree for path.
  10216. */
  10217. function treeSubTree(tree, pathObj) {
  10218. // TODO: Require pathObj to be Path?
  10219. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10220. let child = tree, next = pathGetFront(path);
  10221. while (next !== null) {
  10222. const childNode = safeGet(child.node.children, next) || {
  10223. children: {},
  10224. childCount: 0
  10225. };
  10226. child = new Tree(next, child, childNode);
  10227. path = pathPopFront(path);
  10228. next = pathGetFront(path);
  10229. }
  10230. return child;
  10231. }
  10232. /**
  10233. * Returns the data associated with this tree node.
  10234. *
  10235. * @returns The data or null if no data exists.
  10236. */
  10237. function treeGetValue(tree) {
  10238. return tree.node.value;
  10239. }
  10240. /**
  10241. * Sets data to this tree node.
  10242. *
  10243. * @param value - Value to set.
  10244. */
  10245. function treeSetValue(tree, value) {
  10246. tree.node.value = value;
  10247. treeUpdateParents(tree);
  10248. }
  10249. /**
  10250. * @returns Whether the tree has any children.
  10251. */
  10252. function treeHasChildren(tree) {
  10253. return tree.node.childCount > 0;
  10254. }
  10255. /**
  10256. * @returns Whether the tree is empty (no value or children).
  10257. */
  10258. function treeIsEmpty(tree) {
  10259. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10260. }
  10261. /**
  10262. * Calls action for each child of this tree node.
  10263. *
  10264. * @param action - Action to be called for each child.
  10265. */
  10266. function treeForEachChild(tree, action) {
  10267. each(tree.node.children, (child, childTree) => {
  10268. action(new Tree(child, tree, childTree));
  10269. });
  10270. }
  10271. /**
  10272. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10273. *
  10274. * @param action - Action to be called for each child.
  10275. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10276. * false.
  10277. * @param childrenFirst - Whether to call action on children before calling it on
  10278. * parent.
  10279. */
  10280. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10281. if (includeSelf && !childrenFirst) {
  10282. action(tree);
  10283. }
  10284. treeForEachChild(tree, child => {
  10285. treeForEachDescendant(child, action, true, childrenFirst);
  10286. });
  10287. if (includeSelf && childrenFirst) {
  10288. action(tree);
  10289. }
  10290. }
  10291. /**
  10292. * Calls action on each ancestor node.
  10293. *
  10294. * @param action - Action to be called on each parent; return
  10295. * true to abort.
  10296. * @param includeSelf - Whether to call action on this node as well.
  10297. * @returns true if the action callback returned true.
  10298. */
  10299. function treeForEachAncestor(tree, action, includeSelf) {
  10300. let node = includeSelf ? tree : tree.parent;
  10301. while (node !== null) {
  10302. if (action(node)) {
  10303. return true;
  10304. }
  10305. node = node.parent;
  10306. }
  10307. return false;
  10308. }
  10309. /**
  10310. * @returns The path of this tree node, as a Path.
  10311. */
  10312. function treeGetPath(tree) {
  10313. return new Path(tree.parent === null
  10314. ? tree.name
  10315. : treeGetPath(tree.parent) + '/' + tree.name);
  10316. }
  10317. /**
  10318. * Adds or removes this child from its parent based on whether it's empty or not.
  10319. */
  10320. function treeUpdateParents(tree) {
  10321. if (tree.parent !== null) {
  10322. treeUpdateChild(tree.parent, tree.name, tree);
  10323. }
  10324. }
  10325. /**
  10326. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10327. *
  10328. * @param childName - The name of the child to update.
  10329. * @param child - The child to update.
  10330. */
  10331. function treeUpdateChild(tree, childName, child) {
  10332. const childEmpty = treeIsEmpty(child);
  10333. const childExists = contains(tree.node.children, childName);
  10334. if (childEmpty && childExists) {
  10335. delete tree.node.children[childName];
  10336. tree.node.childCount--;
  10337. treeUpdateParents(tree);
  10338. }
  10339. else if (!childEmpty && !childExists) {
  10340. tree.node.children[childName] = child.node;
  10341. tree.node.childCount++;
  10342. treeUpdateParents(tree);
  10343. }
  10344. }
  10345. /**
  10346. * @license
  10347. * Copyright 2017 Google LLC
  10348. *
  10349. * Licensed under the Apache License, Version 2.0 (the "License");
  10350. * you may not use this file except in compliance with the License.
  10351. * You may obtain a copy of the License at
  10352. *
  10353. * http://www.apache.org/licenses/LICENSE-2.0
  10354. *
  10355. * Unless required by applicable law or agreed to in writing, software
  10356. * distributed under the License is distributed on an "AS IS" BASIS,
  10357. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10358. * See the License for the specific language governing permissions and
  10359. * limitations under the License.
  10360. */
  10361. /**
  10362. * True for invalid Firebase keys
  10363. */
  10364. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10365. /**
  10366. * True for invalid Firebase paths.
  10367. * Allows '/' in paths.
  10368. */
  10369. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10370. /**
  10371. * Maximum number of characters to allow in leaf value
  10372. */
  10373. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10374. const isValidKey = function (key) {
  10375. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10376. };
  10377. const isValidPathString = function (pathString) {
  10378. return (typeof pathString === 'string' &&
  10379. pathString.length !== 0 &&
  10380. !INVALID_PATH_REGEX_.test(pathString));
  10381. };
  10382. const isValidRootPathString = function (pathString) {
  10383. if (pathString) {
  10384. // Allow '/.info/' at the beginning.
  10385. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10386. }
  10387. return isValidPathString(pathString);
  10388. };
  10389. const isValidPriority = function (priority) {
  10390. return (priority === null ||
  10391. typeof priority === 'string' ||
  10392. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10393. (priority &&
  10394. typeof priority === 'object' &&
  10395. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10396. contains(priority, '.sv')));
  10397. };
  10398. /**
  10399. * Pre-validate a datum passed as an argument to Firebase function.
  10400. */
  10401. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10402. if (optional && value === undefined) {
  10403. return;
  10404. }
  10405. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10406. };
  10407. /**
  10408. * Validate a data object client-side before sending to server.
  10409. */
  10410. const validateFirebaseData = function (errorPrefix, data, path_) {
  10411. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10412. if (data === undefined) {
  10413. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10414. }
  10415. if (typeof data === 'function') {
  10416. throw new Error(errorPrefix +
  10417. 'contains a function ' +
  10418. validationPathToErrorString(path) +
  10419. ' with contents = ' +
  10420. data.toString());
  10421. }
  10422. if (isInvalidJSONNumber(data)) {
  10423. throw new Error(errorPrefix +
  10424. 'contains ' +
  10425. data.toString() +
  10426. ' ' +
  10427. validationPathToErrorString(path));
  10428. }
  10429. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10430. if (typeof data === 'string' &&
  10431. data.length > MAX_LEAF_SIZE_ / 3 &&
  10432. stringLength(data) > MAX_LEAF_SIZE_) {
  10433. throw new Error(errorPrefix +
  10434. 'contains a string greater than ' +
  10435. MAX_LEAF_SIZE_ +
  10436. ' utf8 bytes ' +
  10437. validationPathToErrorString(path) +
  10438. " ('" +
  10439. data.substring(0, 50) +
  10440. "...')");
  10441. }
  10442. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10443. // to save extra walking of large objects.
  10444. if (data && typeof data === 'object') {
  10445. let hasDotValue = false;
  10446. let hasActualChild = false;
  10447. each(data, (key, value) => {
  10448. if (key === '.value') {
  10449. hasDotValue = true;
  10450. }
  10451. else if (key !== '.priority' && key !== '.sv') {
  10452. hasActualChild = true;
  10453. if (!isValidKey(key)) {
  10454. throw new Error(errorPrefix +
  10455. ' contains an invalid key (' +
  10456. key +
  10457. ') ' +
  10458. validationPathToErrorString(path) +
  10459. '. Keys must be non-empty strings ' +
  10460. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10461. }
  10462. }
  10463. validationPathPush(path, key);
  10464. validateFirebaseData(errorPrefix, value, path);
  10465. validationPathPop(path);
  10466. });
  10467. if (hasDotValue && hasActualChild) {
  10468. throw new Error(errorPrefix +
  10469. ' contains ".value" child ' +
  10470. validationPathToErrorString(path) +
  10471. ' in addition to actual children.');
  10472. }
  10473. }
  10474. };
  10475. /**
  10476. * Pre-validate paths passed in the firebase function.
  10477. */
  10478. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10479. let i, curPath;
  10480. for (i = 0; i < mergePaths.length; i++) {
  10481. curPath = mergePaths[i];
  10482. const keys = pathSlice(curPath);
  10483. for (let j = 0; j < keys.length; j++) {
  10484. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10485. else if (!isValidKey(keys[j])) {
  10486. throw new Error(errorPrefix +
  10487. 'contains an invalid key (' +
  10488. keys[j] +
  10489. ') in path ' +
  10490. curPath.toString() +
  10491. '. Keys must be non-empty strings ' +
  10492. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10493. }
  10494. }
  10495. }
  10496. // Check that update keys are not descendants of each other.
  10497. // We rely on the property that sorting guarantees that ancestors come
  10498. // right before descendants.
  10499. mergePaths.sort(pathCompare);
  10500. let prevPath = null;
  10501. for (i = 0; i < mergePaths.length; i++) {
  10502. curPath = mergePaths[i];
  10503. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10504. throw new Error(errorPrefix +
  10505. 'contains a path ' +
  10506. prevPath.toString() +
  10507. ' that is ancestor of another path ' +
  10508. curPath.toString());
  10509. }
  10510. prevPath = curPath;
  10511. }
  10512. };
  10513. /**
  10514. * pre-validate an object passed as an argument to firebase function (
  10515. * must be an object - e.g. for firebase.update()).
  10516. */
  10517. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10518. if (optional && data === undefined) {
  10519. return;
  10520. }
  10521. const errorPrefix$1 = errorPrefix(fnName, 'values');
  10522. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10523. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10524. }
  10525. const mergePaths = [];
  10526. each(data, (key, value) => {
  10527. const curPath = new Path(key);
  10528. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10529. if (pathGetBack(curPath) === '.priority') {
  10530. if (!isValidPriority(value)) {
  10531. throw new Error(errorPrefix$1 +
  10532. "contains an invalid value for '" +
  10533. curPath.toString() +
  10534. "', which must be a valid " +
  10535. 'Firebase priority (a string, finite number, server value, or null).');
  10536. }
  10537. }
  10538. mergePaths.push(curPath);
  10539. });
  10540. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10541. };
  10542. const validatePriority = function (fnName, priority, optional) {
  10543. if (optional && priority === undefined) {
  10544. return;
  10545. }
  10546. if (isInvalidJSONNumber(priority)) {
  10547. throw new Error(errorPrefix(fnName, 'priority') +
  10548. 'is ' +
  10549. priority.toString() +
  10550. ', but must be a valid Firebase priority (a string, finite number, ' +
  10551. 'server value, or null).');
  10552. }
  10553. // Special case to allow importing data with a .sv.
  10554. if (!isValidPriority(priority)) {
  10555. throw new Error(errorPrefix(fnName, 'priority') +
  10556. 'must be a valid Firebase priority ' +
  10557. '(a string, finite number, server value, or null).');
  10558. }
  10559. };
  10560. const validateKey = function (fnName, argumentName, key, optional) {
  10561. if (optional && key === undefined) {
  10562. return;
  10563. }
  10564. if (!isValidKey(key)) {
  10565. throw new Error(errorPrefix(fnName, argumentName) +
  10566. 'was an invalid key = "' +
  10567. key +
  10568. '". Firebase keys must be non-empty strings and ' +
  10569. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10570. }
  10571. };
  10572. /**
  10573. * @internal
  10574. */
  10575. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10576. if (optional && pathString === undefined) {
  10577. return;
  10578. }
  10579. if (!isValidPathString(pathString)) {
  10580. throw new Error(errorPrefix(fnName, argumentName) +
  10581. 'was an invalid path = "' +
  10582. pathString +
  10583. '". Paths must be non-empty strings and ' +
  10584. 'can\'t contain ".", "#", "$", "[", or "]"');
  10585. }
  10586. };
  10587. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10588. if (pathString) {
  10589. // Allow '/.info/' at the beginning.
  10590. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10591. }
  10592. validatePathString(fnName, argumentName, pathString, optional);
  10593. };
  10594. /**
  10595. * @internal
  10596. */
  10597. const validateWritablePath = function (fnName, path) {
  10598. if (pathGetFront(path) === '.info') {
  10599. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10600. }
  10601. };
  10602. const validateUrl = function (fnName, parsedUrl) {
  10603. // TODO = Validate server better.
  10604. const pathString = parsedUrl.path.toString();
  10605. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10606. parsedUrl.repoInfo.host.length === 0 ||
  10607. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10608. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10609. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10610. throw new Error(errorPrefix(fnName, 'url') +
  10611. 'must be a valid firebase URL and ' +
  10612. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10613. }
  10614. };
  10615. /**
  10616. * @license
  10617. * Copyright 2017 Google LLC
  10618. *
  10619. * Licensed under the Apache License, Version 2.0 (the "License");
  10620. * you may not use this file except in compliance with the License.
  10621. * You may obtain a copy of the License at
  10622. *
  10623. * http://www.apache.org/licenses/LICENSE-2.0
  10624. *
  10625. * Unless required by applicable law or agreed to in writing, software
  10626. * distributed under the License is distributed on an "AS IS" BASIS,
  10627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10628. * See the License for the specific language governing permissions and
  10629. * limitations under the License.
  10630. */
  10631. /**
  10632. * The event queue serves a few purposes:
  10633. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10634. * events being queued.
  10635. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10636. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10637. * left off, ensuring that the events are still raised synchronously and in order.
  10638. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10639. * events are raised synchronously.
  10640. *
  10641. * NOTE: This can all go away if/when we move to async events.
  10642. *
  10643. */
  10644. class EventQueue {
  10645. constructor() {
  10646. this.eventLists_ = [];
  10647. /**
  10648. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10649. */
  10650. this.recursionDepth_ = 0;
  10651. }
  10652. }
  10653. /**
  10654. * @param eventDataList - The new events to queue.
  10655. */
  10656. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10657. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10658. let currList = null;
  10659. for (let i = 0; i < eventDataList.length; i++) {
  10660. const data = eventDataList[i];
  10661. const path = data.getPath();
  10662. if (currList !== null && !pathEquals(path, currList.path)) {
  10663. eventQueue.eventLists_.push(currList);
  10664. currList = null;
  10665. }
  10666. if (currList === null) {
  10667. currList = { events: [], path };
  10668. }
  10669. currList.events.push(data);
  10670. }
  10671. if (currList) {
  10672. eventQueue.eventLists_.push(currList);
  10673. }
  10674. }
  10675. /**
  10676. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10677. * for the specified path.
  10678. *
  10679. * It is assumed that the new events are all for the specified path.
  10680. *
  10681. * @param path - The path to raise events for.
  10682. * @param eventDataList - The new events to raise.
  10683. */
  10684. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10685. eventQueueQueueEvents(eventQueue, eventDataList);
  10686. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10687. }
  10688. /**
  10689. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10690. * locations related to the specified change path (i.e. all ancestors and descendants).
  10691. *
  10692. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10693. *
  10694. * @param changedPath - The path to raise events for.
  10695. * @param eventDataList - The events to raise
  10696. */
  10697. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10698. eventQueueQueueEvents(eventQueue, eventDataList);
  10699. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10700. pathContains(changedPath, eventPath));
  10701. }
  10702. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10703. eventQueue.recursionDepth_++;
  10704. let sentAll = true;
  10705. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10706. const eventList = eventQueue.eventLists_[i];
  10707. if (eventList) {
  10708. const eventPath = eventList.path;
  10709. if (predicate(eventPath)) {
  10710. eventListRaise(eventQueue.eventLists_[i]);
  10711. eventQueue.eventLists_[i] = null;
  10712. }
  10713. else {
  10714. sentAll = false;
  10715. }
  10716. }
  10717. }
  10718. if (sentAll) {
  10719. eventQueue.eventLists_ = [];
  10720. }
  10721. eventQueue.recursionDepth_--;
  10722. }
  10723. /**
  10724. * Iterates through the list and raises each event
  10725. */
  10726. function eventListRaise(eventList) {
  10727. for (let i = 0; i < eventList.events.length; i++) {
  10728. const eventData = eventList.events[i];
  10729. if (eventData !== null) {
  10730. eventList.events[i] = null;
  10731. const eventFn = eventData.getEventRunner();
  10732. if (logger) {
  10733. log('event: ' + eventData.toString());
  10734. }
  10735. exceptionGuard(eventFn);
  10736. }
  10737. }
  10738. }
  10739. /**
  10740. * @license
  10741. * Copyright 2017 Google LLC
  10742. *
  10743. * Licensed under the Apache License, Version 2.0 (the "License");
  10744. * you may not use this file except in compliance with the License.
  10745. * You may obtain a copy of the License at
  10746. *
  10747. * http://www.apache.org/licenses/LICENSE-2.0
  10748. *
  10749. * Unless required by applicable law or agreed to in writing, software
  10750. * distributed under the License is distributed on an "AS IS" BASIS,
  10751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10752. * See the License for the specific language governing permissions and
  10753. * limitations under the License.
  10754. */
  10755. const INTERRUPT_REASON = 'repo_interrupt';
  10756. /**
  10757. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10758. * things this ensure that if there's ever a bug causing a mismatch between
  10759. * client / server hashes for some data, we won't retry indefinitely.
  10760. */
  10761. const MAX_TRANSACTION_RETRIES = 25;
  10762. /**
  10763. * A connection to a single data repository.
  10764. */
  10765. class Repo {
  10766. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10767. this.repoInfo_ = repoInfo_;
  10768. this.forceRestClient_ = forceRestClient_;
  10769. this.authTokenProvider_ = authTokenProvider_;
  10770. this.appCheckProvider_ = appCheckProvider_;
  10771. this.dataUpdateCount = 0;
  10772. this.statsListener_ = null;
  10773. this.eventQueue_ = new EventQueue();
  10774. this.nextWriteId_ = 1;
  10775. this.interceptServerDataCallback_ = null;
  10776. /** A list of data pieces and paths to be set when this client disconnects. */
  10777. this.onDisconnect_ = newSparseSnapshotTree();
  10778. /** Stores queues of outstanding transactions for Firebase locations. */
  10779. this.transactionQueueTree_ = new Tree();
  10780. // TODO: This should be @private but it's used by test_access.js and internal.js
  10781. this.persistentConnection_ = null;
  10782. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10783. this.key = this.repoInfo_.toURLString();
  10784. }
  10785. /**
  10786. * @returns The URL corresponding to the root of this Firebase.
  10787. */
  10788. toString() {
  10789. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10790. }
  10791. }
  10792. function repoStart(repo, appId, authOverride) {
  10793. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10794. if (repo.forceRestClient_ || beingCrawled()) {
  10795. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10796. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10797. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10798. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10799. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10800. }
  10801. else {
  10802. // Validate authOverride
  10803. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10804. if (typeof authOverride !== 'object') {
  10805. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10806. }
  10807. try {
  10808. stringify(authOverride);
  10809. }
  10810. catch (e) {
  10811. throw new Error('Invalid authOverride provided: ' + e);
  10812. }
  10813. }
  10814. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10815. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10816. }, (connectStatus) => {
  10817. repoOnConnectStatus(repo, connectStatus);
  10818. }, (updates) => {
  10819. repoOnServerInfoUpdate(repo, updates);
  10820. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10821. repo.server_ = repo.persistentConnection_;
  10822. }
  10823. repo.authTokenProvider_.addTokenChangeListener(token => {
  10824. repo.server_.refreshAuthToken(token);
  10825. });
  10826. repo.appCheckProvider_.addTokenChangeListener(result => {
  10827. repo.server_.refreshAppCheckToken(result.token);
  10828. });
  10829. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10830. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10831. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10832. // Used for .info.
  10833. repo.infoData_ = new SnapshotHolder();
  10834. repo.infoSyncTree_ = new SyncTree({
  10835. startListening: (query, tag, currentHashFn, onComplete) => {
  10836. let infoEvents = [];
  10837. const node = repo.infoData_.getNode(query._path);
  10838. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10839. // on initial data...
  10840. if (!node.isEmpty()) {
  10841. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10842. setTimeout(() => {
  10843. onComplete('ok');
  10844. }, 0);
  10845. }
  10846. return infoEvents;
  10847. },
  10848. stopListening: () => { }
  10849. });
  10850. repoUpdateInfo(repo, 'connected', false);
  10851. repo.serverSyncTree_ = new SyncTree({
  10852. startListening: (query, tag, currentHashFn, onComplete) => {
  10853. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10854. const events = onComplete(status, data);
  10855. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10856. });
  10857. // No synchronous events for network-backed sync trees
  10858. return [];
  10859. },
  10860. stopListening: (query, tag) => {
  10861. repo.server_.unlisten(query, tag);
  10862. }
  10863. });
  10864. }
  10865. /**
  10866. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10867. */
  10868. function repoServerTime(repo) {
  10869. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10870. const offset = offsetNode.val() || 0;
  10871. return new Date().getTime() + offset;
  10872. }
  10873. /**
  10874. * Generate ServerValues using some variables from the repo object.
  10875. */
  10876. function repoGenerateServerValues(repo) {
  10877. return generateWithValues({
  10878. timestamp: repoServerTime(repo)
  10879. });
  10880. }
  10881. /**
  10882. * Called by realtime when we get new messages from the server.
  10883. */
  10884. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10885. // For testing.
  10886. repo.dataUpdateCount++;
  10887. const path = new Path(pathString);
  10888. data = repo.interceptServerDataCallback_
  10889. ? repo.interceptServerDataCallback_(pathString, data)
  10890. : data;
  10891. let events = [];
  10892. if (tag) {
  10893. if (isMerge) {
  10894. const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
  10895. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10896. }
  10897. else {
  10898. const taggedSnap = nodeFromJSON(data);
  10899. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10900. }
  10901. }
  10902. else if (isMerge) {
  10903. const changedChildren = map(data, (raw) => nodeFromJSON(raw));
  10904. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10905. }
  10906. else {
  10907. const snap = nodeFromJSON(data);
  10908. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10909. }
  10910. let affectedPath = path;
  10911. if (events.length > 0) {
  10912. // Since we have a listener outstanding for each transaction, receiving any events
  10913. // is a proxy for some change having occurred.
  10914. affectedPath = repoRerunTransactions(repo, path);
  10915. }
  10916. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10917. }
  10918. function repoOnConnectStatus(repo, connectStatus) {
  10919. repoUpdateInfo(repo, 'connected', connectStatus);
  10920. if (connectStatus === false) {
  10921. repoRunOnDisconnectEvents(repo);
  10922. }
  10923. }
  10924. function repoOnServerInfoUpdate(repo, updates) {
  10925. each(updates, (key, value) => {
  10926. repoUpdateInfo(repo, key, value);
  10927. });
  10928. }
  10929. function repoUpdateInfo(repo, pathString, value) {
  10930. const path = new Path('/.info/' + pathString);
  10931. const newNode = nodeFromJSON(value);
  10932. repo.infoData_.updateSnapshot(path, newNode);
  10933. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10934. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10935. }
  10936. function repoGetNextWriteId(repo) {
  10937. return repo.nextWriteId_++;
  10938. }
  10939. /**
  10940. * The purpose of `getValue` is to return the latest known value
  10941. * satisfying `query`.
  10942. *
  10943. * This method will first check for in-memory cached values
  10944. * belonging to active listeners. If they are found, such values
  10945. * are considered to be the most up-to-date.
  10946. *
  10947. * If the client is not connected, this method will wait until the
  10948. * repo has established a connection and then request the value for `query`.
  10949. * If the client is not able to retrieve the query result for another reason,
  10950. * it reports an error.
  10951. *
  10952. * @param query - The query to surface a value for.
  10953. */
  10954. function repoGetValue(repo, query, eventRegistration) {
  10955. // Only active queries are cached. There is no persisted cache.
  10956. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10957. if (cached != null) {
  10958. return Promise.resolve(cached);
  10959. }
  10960. return repo.server_.get(query).then(payload => {
  10961. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10962. /**
  10963. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10964. * Add an event registration,
  10965. * Update data at the path,
  10966. * Raise any events,
  10967. * Cleanup the SyncTree
  10968. */
  10969. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10970. let events;
  10971. if (query._queryParams.loadsAllData()) {
  10972. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10973. }
  10974. else {
  10975. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10976. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10977. }
  10978. /*
  10979. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10980. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10981. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10982. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10983. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10984. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10985. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10986. * ensure the corresponding child events will get fired.
  10987. */
  10988. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10989. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10990. return node;
  10991. }, err => {
  10992. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  10993. return Promise.reject(new Error(err));
  10994. });
  10995. }
  10996. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10997. repoLog(repo, 'set', {
  10998. path: path.toString(),
  10999. value: newVal,
  11000. priority: newPriority
  11001. });
  11002. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11003. // (b) store unresolved paths on JSON parse
  11004. const serverValues = repoGenerateServerValues(repo);
  11005. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11006. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11007. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11008. const writeId = repoGetNextWriteId(repo);
  11009. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11010. eventQueueQueueEvents(repo.eventQueue_, events);
  11011. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11012. const success = status === 'ok';
  11013. if (!success) {
  11014. warn('set at ' + path + ' failed: ' + status);
  11015. }
  11016. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11017. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11018. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11019. });
  11020. const affectedPath = repoAbortTransactions(repo, path);
  11021. repoRerunTransactions(repo, affectedPath);
  11022. // We queued the events above, so just flush the queue here
  11023. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11024. }
  11025. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11026. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11027. // Start with our existing data and merge each child into it.
  11028. let empty = true;
  11029. const serverValues = repoGenerateServerValues(repo);
  11030. const changedChildren = {};
  11031. each(childrenToMerge, (changedKey, changedValue) => {
  11032. empty = false;
  11033. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11034. });
  11035. if (!empty) {
  11036. const writeId = repoGetNextWriteId(repo);
  11037. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11038. eventQueueQueueEvents(repo.eventQueue_, events);
  11039. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11040. const success = status === 'ok';
  11041. if (!success) {
  11042. warn('update at ' + path + ' failed: ' + status);
  11043. }
  11044. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11045. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11046. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11047. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11048. });
  11049. each(childrenToMerge, (changedPath) => {
  11050. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11051. repoRerunTransactions(repo, affectedPath);
  11052. });
  11053. // We queued the events above, so just flush the queue here
  11054. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11055. }
  11056. else {
  11057. log("update() called with empty data. Don't do anything.");
  11058. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11059. }
  11060. }
  11061. /**
  11062. * Applies all of the changes stored up in the onDisconnect_ tree.
  11063. */
  11064. function repoRunOnDisconnectEvents(repo) {
  11065. repoLog(repo, 'onDisconnectEvents');
  11066. const serverValues = repoGenerateServerValues(repo);
  11067. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11068. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11069. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11070. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11071. });
  11072. let events = [];
  11073. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11074. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11075. const affectedPath = repoAbortTransactions(repo, path);
  11076. repoRerunTransactions(repo, affectedPath);
  11077. });
  11078. repo.onDisconnect_ = newSparseSnapshotTree();
  11079. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11080. }
  11081. function repoOnDisconnectCancel(repo, path, onComplete) {
  11082. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11083. if (status === 'ok') {
  11084. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11085. }
  11086. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11087. });
  11088. }
  11089. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11090. const newNode = nodeFromJSON(value);
  11091. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11092. if (status === 'ok') {
  11093. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11094. }
  11095. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11096. });
  11097. }
  11098. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11099. const newNode = nodeFromJSON(value, priority);
  11100. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11101. if (status === 'ok') {
  11102. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11103. }
  11104. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11105. });
  11106. }
  11107. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11108. if (isEmpty(childrenToMerge)) {
  11109. log("onDisconnect().update() called with empty data. Don't do anything.");
  11110. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11111. return;
  11112. }
  11113. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11114. if (status === 'ok') {
  11115. each(childrenToMerge, (childName, childNode) => {
  11116. const newChildNode = nodeFromJSON(childNode);
  11117. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11118. });
  11119. }
  11120. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11121. });
  11122. }
  11123. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11124. let events;
  11125. if (pathGetFront(query._path) === '.info') {
  11126. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11127. }
  11128. else {
  11129. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11130. }
  11131. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11132. }
  11133. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11134. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11135. // a little bit by handling the return values anyways.
  11136. let events;
  11137. if (pathGetFront(query._path) === '.info') {
  11138. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11139. }
  11140. else {
  11141. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11142. }
  11143. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11144. }
  11145. function repoInterrupt(repo) {
  11146. if (repo.persistentConnection_) {
  11147. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11148. }
  11149. }
  11150. function repoResume(repo) {
  11151. if (repo.persistentConnection_) {
  11152. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11153. }
  11154. }
  11155. function repoLog(repo, ...varArgs) {
  11156. let prefix = '';
  11157. if (repo.persistentConnection_) {
  11158. prefix = repo.persistentConnection_.id + ':';
  11159. }
  11160. log(prefix, ...varArgs);
  11161. }
  11162. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11163. if (callback) {
  11164. exceptionGuard(() => {
  11165. if (status === 'ok') {
  11166. callback(null);
  11167. }
  11168. else {
  11169. const code = (status || 'error').toUpperCase();
  11170. let message = code;
  11171. if (errorReason) {
  11172. message += ': ' + errorReason;
  11173. }
  11174. const error = new Error(message);
  11175. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11176. error.code = code;
  11177. callback(error);
  11178. }
  11179. });
  11180. }
  11181. }
  11182. /**
  11183. * Creates a new transaction, adds it to the transactions we're tracking, and
  11184. * sends it to the server if possible.
  11185. *
  11186. * @param path - Path at which to do transaction.
  11187. * @param transactionUpdate - Update callback.
  11188. * @param onComplete - Completion callback.
  11189. * @param unwatcher - Function that will be called when the transaction no longer
  11190. * need data updates for `path`.
  11191. * @param applyLocally - Whether or not to make intermediate results visible
  11192. */
  11193. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11194. repoLog(repo, 'transaction on ' + path);
  11195. // Initialize transaction.
  11196. const transaction = {
  11197. path,
  11198. update: transactionUpdate,
  11199. onComplete,
  11200. // One of TransactionStatus enums.
  11201. status: null,
  11202. // Used when combining transactions at different locations to figure out
  11203. // which one goes first.
  11204. order: LUIDGenerator(),
  11205. // Whether to raise local events for this transaction.
  11206. applyLocally,
  11207. // Count of how many times we've retried the transaction.
  11208. retryCount: 0,
  11209. // Function to call to clean up our .on() listener.
  11210. unwatcher,
  11211. // Stores why a transaction was aborted.
  11212. abortReason: null,
  11213. currentWriteId: null,
  11214. currentInputSnapshot: null,
  11215. currentOutputSnapshotRaw: null,
  11216. currentOutputSnapshotResolved: null
  11217. };
  11218. // Run transaction initially.
  11219. const currentState = repoGetLatestState(repo, path, undefined);
  11220. transaction.currentInputSnapshot = currentState;
  11221. const newVal = transaction.update(currentState.val());
  11222. if (newVal === undefined) {
  11223. // Abort transaction.
  11224. transaction.unwatcher();
  11225. transaction.currentOutputSnapshotRaw = null;
  11226. transaction.currentOutputSnapshotResolved = null;
  11227. if (transaction.onComplete) {
  11228. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11229. }
  11230. }
  11231. else {
  11232. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11233. // Mark as run and add to our queue.
  11234. transaction.status = 0 /* TransactionStatus.RUN */;
  11235. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11236. const nodeQueue = treeGetValue(queueNode) || [];
  11237. nodeQueue.push(transaction);
  11238. treeSetValue(queueNode, nodeQueue);
  11239. // Update visibleData and raise events
  11240. // Note: We intentionally raise events after updating all of our
  11241. // transaction state, since the user could start new transactions from the
  11242. // event callbacks.
  11243. let priorityForNode;
  11244. if (typeof newVal === 'object' &&
  11245. newVal !== null &&
  11246. contains(newVal, '.priority')) {
  11247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11248. priorityForNode = safeGet(newVal, '.priority');
  11249. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11250. 'Priority must be a valid string, finite number, server value, or null.');
  11251. }
  11252. else {
  11253. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11254. ChildrenNode.EMPTY_NODE;
  11255. priorityForNode = currentNode.getPriority().val();
  11256. }
  11257. const serverValues = repoGenerateServerValues(repo);
  11258. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11259. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11260. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11261. transaction.currentOutputSnapshotResolved = newNode;
  11262. transaction.currentWriteId = repoGetNextWriteId(repo);
  11263. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11264. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11265. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11266. }
  11267. }
  11268. /**
  11269. * @param excludeSets - A specific set to exclude
  11270. */
  11271. function repoGetLatestState(repo, path, excludeSets) {
  11272. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11273. ChildrenNode.EMPTY_NODE);
  11274. }
  11275. /**
  11276. * Sends any already-run transactions that aren't waiting for outstanding
  11277. * transactions to complete.
  11278. *
  11279. * Externally it's called with no arguments, but it calls itself recursively
  11280. * with a particular transactionQueueTree node to recurse through the tree.
  11281. *
  11282. * @param node - transactionQueueTree node to start at.
  11283. */
  11284. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11285. // Before recursing, make sure any completed transactions are removed.
  11286. if (!node) {
  11287. repoPruneCompletedTransactionsBelowNode(repo, node);
  11288. }
  11289. if (treeGetValue(node)) {
  11290. const queue = repoBuildTransactionQueue(repo, node);
  11291. assert(queue.length > 0, 'Sending zero length transaction queue');
  11292. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11293. // If they're all run (and not sent), we can send them. Else, we must wait.
  11294. if (allRun) {
  11295. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11296. }
  11297. }
  11298. else if (treeHasChildren(node)) {
  11299. treeForEachChild(node, childNode => {
  11300. repoSendReadyTransactions(repo, childNode);
  11301. });
  11302. }
  11303. }
  11304. /**
  11305. * Given a list of run transactions, send them to the server and then handle
  11306. * the result (success or failure).
  11307. *
  11308. * @param path - The location of the queue.
  11309. * @param queue - Queue of transactions under the specified location.
  11310. */
  11311. function repoSendTransactionQueue(repo, path, queue) {
  11312. // Mark transactions as sent and increment retry count!
  11313. const setsToIgnore = queue.map(txn => {
  11314. return txn.currentWriteId;
  11315. });
  11316. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11317. let snapToSend = latestState;
  11318. const latestHash = latestState.hash();
  11319. for (let i = 0; i < queue.length; i++) {
  11320. const txn = queue[i];
  11321. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11322. txn.status = 1 /* TransactionStatus.SENT */;
  11323. txn.retryCount++;
  11324. const relativePath = newRelativePath(path, txn.path);
  11325. // If we've gotten to this point, the output snapshot must be defined.
  11326. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11327. }
  11328. const dataToSend = snapToSend.val(true);
  11329. const pathToSend = path;
  11330. // Send the put.
  11331. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11332. repoLog(repo, 'transaction put response', {
  11333. path: pathToSend.toString(),
  11334. status
  11335. });
  11336. let events = [];
  11337. if (status === 'ok') {
  11338. // Queue up the callbacks and fire them after cleaning up all of our
  11339. // transaction state, since the callback could trigger more
  11340. // transactions or sets.
  11341. const callbacks = [];
  11342. for (let i = 0; i < queue.length; i++) {
  11343. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11344. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11345. if (queue[i].onComplete) {
  11346. // We never unset the output snapshot, and given that this
  11347. // transaction is complete, it should be set
  11348. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11349. }
  11350. queue[i].unwatcher();
  11351. }
  11352. // Now remove the completed transactions.
  11353. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11354. // There may be pending transactions that we can now send.
  11355. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11356. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11357. // Finally, trigger onComplete callbacks.
  11358. for (let i = 0; i < callbacks.length; i++) {
  11359. exceptionGuard(callbacks[i]);
  11360. }
  11361. }
  11362. else {
  11363. // transactions are no longer sent. Update their status appropriately.
  11364. if (status === 'datastale') {
  11365. for (let i = 0; i < queue.length; i++) {
  11366. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11367. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11368. }
  11369. else {
  11370. queue[i].status = 0 /* TransactionStatus.RUN */;
  11371. }
  11372. }
  11373. }
  11374. else {
  11375. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11376. for (let i = 0; i < queue.length; i++) {
  11377. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11378. queue[i].abortReason = status;
  11379. }
  11380. }
  11381. repoRerunTransactions(repo, path);
  11382. }
  11383. }, latestHash);
  11384. }
  11385. /**
  11386. * Finds all transactions dependent on the data at changedPath and reruns them.
  11387. *
  11388. * Should be called any time cached data changes.
  11389. *
  11390. * Return the highest path that was affected by rerunning transactions. This
  11391. * is the path at which events need to be raised for.
  11392. *
  11393. * @param changedPath - The path in mergedData that changed.
  11394. * @returns The rootmost path that was affected by rerunning transactions.
  11395. */
  11396. function repoRerunTransactions(repo, changedPath) {
  11397. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11398. const path = treeGetPath(rootMostTransactionNode);
  11399. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11400. repoRerunTransactionQueue(repo, queue, path);
  11401. return path;
  11402. }
  11403. /**
  11404. * Does all the work of rerunning transactions (as well as cleans up aborted
  11405. * transactions and whatnot).
  11406. *
  11407. * @param queue - The queue of transactions to run.
  11408. * @param path - The path the queue is for.
  11409. */
  11410. function repoRerunTransactionQueue(repo, queue, path) {
  11411. if (queue.length === 0) {
  11412. return; // Nothing to do!
  11413. }
  11414. // Queue up the callbacks and fire them after cleaning up all of our
  11415. // transaction state, since the callback could trigger more transactions or
  11416. // sets.
  11417. const callbacks = [];
  11418. let events = [];
  11419. // Ignore all of the sets we're going to re-run.
  11420. const txnsToRerun = queue.filter(q => {
  11421. return q.status === 0 /* TransactionStatus.RUN */;
  11422. });
  11423. const setsToIgnore = txnsToRerun.map(q => {
  11424. return q.currentWriteId;
  11425. });
  11426. for (let i = 0; i < queue.length; i++) {
  11427. const transaction = queue[i];
  11428. const relativePath = newRelativePath(path, transaction.path);
  11429. let abortTransaction = false, abortReason;
  11430. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11431. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11432. abortTransaction = true;
  11433. abortReason = transaction.abortReason;
  11434. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11435. }
  11436. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11437. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11438. abortTransaction = true;
  11439. abortReason = 'maxretry';
  11440. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11441. }
  11442. else {
  11443. // This code reruns a transaction
  11444. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11445. transaction.currentInputSnapshot = currentNode;
  11446. const newData = queue[i].update(currentNode.val());
  11447. if (newData !== undefined) {
  11448. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11449. let newDataNode = nodeFromJSON(newData);
  11450. const hasExplicitPriority = typeof newData === 'object' &&
  11451. newData != null &&
  11452. contains(newData, '.priority');
  11453. if (!hasExplicitPriority) {
  11454. // Keep the old priority if there wasn't a priority explicitly specified.
  11455. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11456. }
  11457. const oldWriteId = transaction.currentWriteId;
  11458. const serverValues = repoGenerateServerValues(repo);
  11459. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11460. transaction.currentOutputSnapshotRaw = newDataNode;
  11461. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11462. transaction.currentWriteId = repoGetNextWriteId(repo);
  11463. // Mutates setsToIgnore in place
  11464. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11465. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11466. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11467. }
  11468. else {
  11469. abortTransaction = true;
  11470. abortReason = 'nodata';
  11471. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11472. }
  11473. }
  11474. }
  11475. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11476. events = [];
  11477. if (abortTransaction) {
  11478. // Abort.
  11479. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11480. // Removing a listener can trigger pruning which can muck with
  11481. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11482. // until we're done.
  11483. (function (unwatcher) {
  11484. setTimeout(unwatcher, Math.floor(0));
  11485. })(queue[i].unwatcher);
  11486. if (queue[i].onComplete) {
  11487. if (abortReason === 'nodata') {
  11488. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11489. }
  11490. else {
  11491. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11492. }
  11493. }
  11494. }
  11495. }
  11496. // Clean up completed transactions.
  11497. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11498. // Now fire callbacks, now that we're in a good, known state.
  11499. for (let i = 0; i < callbacks.length; i++) {
  11500. exceptionGuard(callbacks[i]);
  11501. }
  11502. // Try to send the transaction result to the server.
  11503. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11504. }
  11505. /**
  11506. * Returns the rootmost ancestor node of the specified path that has a pending
  11507. * transaction on it, or just returns the node for the given path if there are
  11508. * no pending transactions on any ancestor.
  11509. *
  11510. * @param path - The location to start at.
  11511. * @returns The rootmost node with a transaction.
  11512. */
  11513. function repoGetAncestorTransactionNode(repo, path) {
  11514. let front;
  11515. // Start at the root and walk deeper into the tree towards path until we
  11516. // find a node with pending transactions.
  11517. let transactionNode = repo.transactionQueueTree_;
  11518. front = pathGetFront(path);
  11519. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11520. transactionNode = treeSubTree(transactionNode, front);
  11521. path = pathPopFront(path);
  11522. front = pathGetFront(path);
  11523. }
  11524. return transactionNode;
  11525. }
  11526. /**
  11527. * Builds the queue of all transactions at or below the specified
  11528. * transactionNode.
  11529. *
  11530. * @param transactionNode
  11531. * @returns The generated queue.
  11532. */
  11533. function repoBuildTransactionQueue(repo, transactionNode) {
  11534. // Walk any child transaction queues and aggregate them into a single queue.
  11535. const transactionQueue = [];
  11536. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11537. // Sort them by the order the transactions were created.
  11538. transactionQueue.sort((a, b) => a.order - b.order);
  11539. return transactionQueue;
  11540. }
  11541. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11542. const nodeQueue = treeGetValue(node);
  11543. if (nodeQueue) {
  11544. for (let i = 0; i < nodeQueue.length; i++) {
  11545. queue.push(nodeQueue[i]);
  11546. }
  11547. }
  11548. treeForEachChild(node, child => {
  11549. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11550. });
  11551. }
  11552. /**
  11553. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11554. */
  11555. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11556. const queue = treeGetValue(node);
  11557. if (queue) {
  11558. let to = 0;
  11559. for (let from = 0; from < queue.length; from++) {
  11560. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11561. queue[to] = queue[from];
  11562. to++;
  11563. }
  11564. }
  11565. queue.length = to;
  11566. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11567. }
  11568. treeForEachChild(node, childNode => {
  11569. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11570. });
  11571. }
  11572. /**
  11573. * Aborts all transactions on ancestors or descendants of the specified path.
  11574. * Called when doing a set() or update() since we consider them incompatible
  11575. * with transactions.
  11576. *
  11577. * @param path - Path for which we want to abort related transactions.
  11578. */
  11579. function repoAbortTransactions(repo, path) {
  11580. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11581. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11582. treeForEachAncestor(transactionNode, (node) => {
  11583. repoAbortTransactionsOnNode(repo, node);
  11584. });
  11585. repoAbortTransactionsOnNode(repo, transactionNode);
  11586. treeForEachDescendant(transactionNode, (node) => {
  11587. repoAbortTransactionsOnNode(repo, node);
  11588. });
  11589. return affectedPath;
  11590. }
  11591. /**
  11592. * Abort transactions stored in this transaction queue node.
  11593. *
  11594. * @param node - Node to abort transactions for.
  11595. */
  11596. function repoAbortTransactionsOnNode(repo, node) {
  11597. const queue = treeGetValue(node);
  11598. if (queue) {
  11599. // Queue up the callbacks and fire them after cleaning up all of our
  11600. // transaction state, since the callback could trigger more transactions
  11601. // or sets.
  11602. const callbacks = [];
  11603. // Go through queue. Any already-sent transactions must be marked for
  11604. // abort, while the unsent ones can be immediately aborted and removed.
  11605. let events = [];
  11606. let lastSent = -1;
  11607. for (let i = 0; i < queue.length; i++) {
  11608. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11609. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11610. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11611. lastSent = i;
  11612. // Mark transaction for abort when it comes back.
  11613. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11614. queue[i].abortReason = 'set';
  11615. }
  11616. else {
  11617. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11618. // We can abort it immediately.
  11619. queue[i].unwatcher();
  11620. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11621. if (queue[i].onComplete) {
  11622. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11623. }
  11624. }
  11625. }
  11626. if (lastSent === -1) {
  11627. // We're not waiting for any sent transactions. We can clear the queue.
  11628. treeSetValue(node, undefined);
  11629. }
  11630. else {
  11631. // Remove the transactions we aborted.
  11632. queue.length = lastSent + 1;
  11633. }
  11634. // Now fire the callbacks.
  11635. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11636. for (let i = 0; i < callbacks.length; i++) {
  11637. exceptionGuard(callbacks[i]);
  11638. }
  11639. }
  11640. }
  11641. /**
  11642. * @license
  11643. * Copyright 2017 Google LLC
  11644. *
  11645. * Licensed under the Apache License, Version 2.0 (the "License");
  11646. * you may not use this file except in compliance with the License.
  11647. * You may obtain a copy of the License at
  11648. *
  11649. * http://www.apache.org/licenses/LICENSE-2.0
  11650. *
  11651. * Unless required by applicable law or agreed to in writing, software
  11652. * distributed under the License is distributed on an "AS IS" BASIS,
  11653. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11654. * See the License for the specific language governing permissions and
  11655. * limitations under the License.
  11656. */
  11657. function decodePath(pathString) {
  11658. let pathStringDecoded = '';
  11659. const pieces = pathString.split('/');
  11660. for (let i = 0; i < pieces.length; i++) {
  11661. if (pieces[i].length > 0) {
  11662. let piece = pieces[i];
  11663. try {
  11664. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11665. }
  11666. catch (e) { }
  11667. pathStringDecoded += '/' + piece;
  11668. }
  11669. }
  11670. return pathStringDecoded;
  11671. }
  11672. /**
  11673. * @returns key value hash
  11674. */
  11675. function decodeQuery(queryString) {
  11676. const results = {};
  11677. if (queryString.charAt(0) === '?') {
  11678. queryString = queryString.substring(1);
  11679. }
  11680. for (const segment of queryString.split('&')) {
  11681. if (segment.length === 0) {
  11682. continue;
  11683. }
  11684. const kv = segment.split('=');
  11685. if (kv.length === 2) {
  11686. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11687. }
  11688. else {
  11689. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11690. }
  11691. }
  11692. return results;
  11693. }
  11694. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11695. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11696. if (parsedUrl.domain === 'firebase.com') {
  11697. fatal(parsedUrl.host +
  11698. ' is no longer supported. ' +
  11699. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11700. }
  11701. // Catch common error of uninitialized namespace value.
  11702. if ((!namespace || namespace === 'undefined') &&
  11703. parsedUrl.domain !== 'localhost') {
  11704. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11705. }
  11706. if (!parsedUrl.secure) {
  11707. warnIfPageIsSecure();
  11708. }
  11709. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11710. return {
  11711. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11712. /*persistenceKey=*/ '',
  11713. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11714. path: new Path(parsedUrl.pathString)
  11715. };
  11716. };
  11717. const parseDatabaseURL = function (dataURL) {
  11718. // Default to empty strings in the event of a malformed string.
  11719. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11720. // Always default to SSL, unless otherwise specified.
  11721. let secure = true, scheme = 'https', port = 443;
  11722. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11723. if (typeof dataURL === 'string') {
  11724. // Parse scheme.
  11725. let colonInd = dataURL.indexOf('//');
  11726. if (colonInd >= 0) {
  11727. scheme = dataURL.substring(0, colonInd - 1);
  11728. dataURL = dataURL.substring(colonInd + 2);
  11729. }
  11730. // Parse host, path, and query string.
  11731. let slashInd = dataURL.indexOf('/');
  11732. if (slashInd === -1) {
  11733. slashInd = dataURL.length;
  11734. }
  11735. let questionMarkInd = dataURL.indexOf('?');
  11736. if (questionMarkInd === -1) {
  11737. questionMarkInd = dataURL.length;
  11738. }
  11739. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11740. if (slashInd < questionMarkInd) {
  11741. // For pathString, questionMarkInd will always come after slashInd
  11742. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11743. }
  11744. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11745. // If we have a port, use scheme for determining if it's secure.
  11746. colonInd = host.indexOf(':');
  11747. if (colonInd >= 0) {
  11748. secure = scheme === 'https' || scheme === 'wss';
  11749. port = parseInt(host.substring(colonInd + 1), 10);
  11750. }
  11751. else {
  11752. colonInd = host.length;
  11753. }
  11754. const hostWithoutPort = host.slice(0, colonInd);
  11755. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11756. domain = 'localhost';
  11757. }
  11758. else if (hostWithoutPort.split('.').length <= 2) {
  11759. domain = hostWithoutPort;
  11760. }
  11761. else {
  11762. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11763. const dotInd = host.indexOf('.');
  11764. subdomain = host.substring(0, dotInd).toLowerCase();
  11765. domain = host.substring(dotInd + 1);
  11766. // Normalize namespaces to lowercase to share storage / connection.
  11767. namespace = subdomain;
  11768. }
  11769. // Always treat the value of the `ns` as the namespace name if it is present.
  11770. if ('ns' in queryParams) {
  11771. namespace = queryParams['ns'];
  11772. }
  11773. }
  11774. return {
  11775. host,
  11776. port,
  11777. domain,
  11778. subdomain,
  11779. secure,
  11780. scheme,
  11781. pathString,
  11782. namespace
  11783. };
  11784. };
  11785. /**
  11786. * @license
  11787. * Copyright 2017 Google LLC
  11788. *
  11789. * Licensed under the Apache License, Version 2.0 (the "License");
  11790. * you may not use this file except in compliance with the License.
  11791. * You may obtain a copy of the License at
  11792. *
  11793. * http://www.apache.org/licenses/LICENSE-2.0
  11794. *
  11795. * Unless required by applicable law or agreed to in writing, software
  11796. * distributed under the License is distributed on an "AS IS" BASIS,
  11797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11798. * See the License for the specific language governing permissions and
  11799. * limitations under the License.
  11800. */
  11801. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11802. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11803. /**
  11804. * Fancy ID generator that creates 20-character string identifiers with the
  11805. * following properties:
  11806. *
  11807. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11808. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11809. * collide with other clients' IDs.
  11810. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11811. * that will sort properly).
  11812. * 4. They're monotonically increasing. Even if you generate more than one in
  11813. * the same timestamp, the latter ones will sort after the former ones. We do
  11814. * this by using the previous random bits but "incrementing" them by 1 (only
  11815. * in the case of a timestamp collision).
  11816. */
  11817. const nextPushId = (function () {
  11818. // Timestamp of last push, used to prevent local collisions if you push twice
  11819. // in one ms.
  11820. let lastPushTime = 0;
  11821. // We generate 72-bits of randomness which get turned into 12 characters and
  11822. // appended to the timestamp to prevent collisions with other clients. We
  11823. // store the last characters we generated because in the event of a collision,
  11824. // we'll use those same characters except "incremented" by one.
  11825. const lastRandChars = [];
  11826. return function (now) {
  11827. const duplicateTime = now === lastPushTime;
  11828. lastPushTime = now;
  11829. let i;
  11830. const timeStampChars = new Array(8);
  11831. for (i = 7; i >= 0; i--) {
  11832. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11833. // NOTE: Can't use << here because javascript will convert to int and lose
  11834. // the upper bits.
  11835. now = Math.floor(now / 64);
  11836. }
  11837. assert(now === 0, 'Cannot push at time == 0');
  11838. let id = timeStampChars.join('');
  11839. if (!duplicateTime) {
  11840. for (i = 0; i < 12; i++) {
  11841. lastRandChars[i] = Math.floor(Math.random() * 64);
  11842. }
  11843. }
  11844. else {
  11845. // If the timestamp hasn't changed since last push, use the same random
  11846. // number, except incremented by 1.
  11847. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11848. lastRandChars[i] = 0;
  11849. }
  11850. lastRandChars[i]++;
  11851. }
  11852. for (i = 0; i < 12; i++) {
  11853. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11854. }
  11855. assert(id.length === 20, 'nextPushId: Length should be 20.');
  11856. return id;
  11857. };
  11858. })();
  11859. /**
  11860. * @license
  11861. * Copyright 2017 Google LLC
  11862. *
  11863. * Licensed under the Apache License, Version 2.0 (the "License");
  11864. * you may not use this file except in compliance with the License.
  11865. * You may obtain a copy of the License at
  11866. *
  11867. * http://www.apache.org/licenses/LICENSE-2.0
  11868. *
  11869. * Unless required by applicable law or agreed to in writing, software
  11870. * distributed under the License is distributed on an "AS IS" BASIS,
  11871. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11872. * See the License for the specific language governing permissions and
  11873. * limitations under the License.
  11874. */
  11875. /**
  11876. * Encapsulates the data needed to raise an event
  11877. */
  11878. class DataEvent {
  11879. /**
  11880. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11881. * @param eventRegistration - The function to call to with the event data. User provided
  11882. * @param snapshot - The data backing the event
  11883. * @param prevName - Optional, the name of the previous child for child_* events.
  11884. */
  11885. constructor(eventType, eventRegistration, snapshot, prevName) {
  11886. this.eventType = eventType;
  11887. this.eventRegistration = eventRegistration;
  11888. this.snapshot = snapshot;
  11889. this.prevName = prevName;
  11890. }
  11891. getPath() {
  11892. const ref = this.snapshot.ref;
  11893. if (this.eventType === 'value') {
  11894. return ref._path;
  11895. }
  11896. else {
  11897. return ref.parent._path;
  11898. }
  11899. }
  11900. getEventType() {
  11901. return this.eventType;
  11902. }
  11903. getEventRunner() {
  11904. return this.eventRegistration.getEventRunner(this);
  11905. }
  11906. toString() {
  11907. return (this.getPath().toString() +
  11908. ':' +
  11909. this.eventType +
  11910. ':' +
  11911. stringify(this.snapshot.exportVal()));
  11912. }
  11913. }
  11914. class CancelEvent {
  11915. constructor(eventRegistration, error, path) {
  11916. this.eventRegistration = eventRegistration;
  11917. this.error = error;
  11918. this.path = path;
  11919. }
  11920. getPath() {
  11921. return this.path;
  11922. }
  11923. getEventType() {
  11924. return 'cancel';
  11925. }
  11926. getEventRunner() {
  11927. return this.eventRegistration.getEventRunner(this);
  11928. }
  11929. toString() {
  11930. return this.path.toString() + ':cancel';
  11931. }
  11932. }
  11933. /**
  11934. * @license
  11935. * Copyright 2017 Google LLC
  11936. *
  11937. * Licensed under the Apache License, Version 2.0 (the "License");
  11938. * you may not use this file except in compliance with the License.
  11939. * You may obtain a copy of the License at
  11940. *
  11941. * http://www.apache.org/licenses/LICENSE-2.0
  11942. *
  11943. * Unless required by applicable law or agreed to in writing, software
  11944. * distributed under the License is distributed on an "AS IS" BASIS,
  11945. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11946. * See the License for the specific language governing permissions and
  11947. * limitations under the License.
  11948. */
  11949. /**
  11950. * A wrapper class that converts events from the database@exp SDK to the legacy
  11951. * Database SDK. Events are not converted directly as event registration relies
  11952. * on reference comparison of the original user callback (see `matches()`) and
  11953. * relies on equality of the legacy SDK's `context` object.
  11954. */
  11955. class CallbackContext {
  11956. constructor(snapshotCallback, cancelCallback) {
  11957. this.snapshotCallback = snapshotCallback;
  11958. this.cancelCallback = cancelCallback;
  11959. }
  11960. onValue(expDataSnapshot, previousChildName) {
  11961. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11962. }
  11963. onCancel(error) {
  11964. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11965. return this.cancelCallback.call(null, error);
  11966. }
  11967. get hasCancelCallback() {
  11968. return !!this.cancelCallback;
  11969. }
  11970. matches(other) {
  11971. return (this.snapshotCallback === other.snapshotCallback ||
  11972. (this.snapshotCallback.userCallback !== undefined &&
  11973. this.snapshotCallback.userCallback ===
  11974. other.snapshotCallback.userCallback &&
  11975. this.snapshotCallback.context === other.snapshotCallback.context));
  11976. }
  11977. }
  11978. /**
  11979. * @license
  11980. * Copyright 2021 Google LLC
  11981. *
  11982. * Licensed under the Apache License, Version 2.0 (the "License");
  11983. * you may not use this file except in compliance with the License.
  11984. * You may obtain a copy of the License at
  11985. *
  11986. * http://www.apache.org/licenses/LICENSE-2.0
  11987. *
  11988. * Unless required by applicable law or agreed to in writing, software
  11989. * distributed under the License is distributed on an "AS IS" BASIS,
  11990. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11991. * See the License for the specific language governing permissions and
  11992. * limitations under the License.
  11993. */
  11994. /**
  11995. * The `onDisconnect` class allows you to write or clear data when your client
  11996. * disconnects from the Database server. These updates occur whether your
  11997. * client disconnects cleanly or not, so you can rely on them to clean up data
  11998. * even if a connection is dropped or a client crashes.
  11999. *
  12000. * The `onDisconnect` class is most commonly used to manage presence in
  12001. * applications where it is useful to detect how many clients are connected and
  12002. * when other clients disconnect. See
  12003. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12004. * for more information.
  12005. *
  12006. * To avoid problems when a connection is dropped before the requests can be
  12007. * transferred to the Database server, these functions should be called before
  12008. * writing any data.
  12009. *
  12010. * Note that `onDisconnect` operations are only triggered once. If you want an
  12011. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12012. * the `onDisconnect` operations each time you reconnect.
  12013. */
  12014. class OnDisconnect {
  12015. /** @hideconstructor */
  12016. constructor(_repo, _path) {
  12017. this._repo = _repo;
  12018. this._path = _path;
  12019. }
  12020. /**
  12021. * Cancels all previously queued `onDisconnect()` set or update events for this
  12022. * location and all children.
  12023. *
  12024. * If a write has been queued for this location via a `set()` or `update()` at a
  12025. * parent location, the write at this location will be canceled, though writes
  12026. * to sibling locations will still occur.
  12027. *
  12028. * @returns Resolves when synchronization to the server is complete.
  12029. */
  12030. cancel() {
  12031. const deferred = new Deferred();
  12032. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12033. return deferred.promise;
  12034. }
  12035. /**
  12036. * Ensures the data at this location is deleted when the client is disconnected
  12037. * (due to closing the browser, navigating to a new page, or network issues).
  12038. *
  12039. * @returns Resolves when synchronization to the server is complete.
  12040. */
  12041. remove() {
  12042. validateWritablePath('OnDisconnect.remove', this._path);
  12043. const deferred = new Deferred();
  12044. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12045. return deferred.promise;
  12046. }
  12047. /**
  12048. * Ensures the data at this location is set to the specified value when the
  12049. * client is disconnected (due to closing the browser, navigating to a new page,
  12050. * or network issues).
  12051. *
  12052. * `set()` is especially useful for implementing "presence" systems, where a
  12053. * value should be changed or cleared when a user disconnects so that they
  12054. * appear "offline" to other users. See
  12055. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12056. * for more information.
  12057. *
  12058. * Note that `onDisconnect` operations are only triggered once. If you want an
  12059. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12060. * the `onDisconnect` operations each time.
  12061. *
  12062. * @param value - The value to be written to this location on disconnect (can
  12063. * be an object, array, string, number, boolean, or null).
  12064. * @returns Resolves when synchronization to the Database is complete.
  12065. */
  12066. set(value) {
  12067. validateWritablePath('OnDisconnect.set', this._path);
  12068. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12069. const deferred = new Deferred();
  12070. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12071. return deferred.promise;
  12072. }
  12073. /**
  12074. * Ensures the data at this location is set to the specified value and priority
  12075. * when the client is disconnected (due to closing the browser, navigating to a
  12076. * new page, or network issues).
  12077. *
  12078. * @param value - The value to be written to this location on disconnect (can
  12079. * be an object, array, string, number, boolean, or null).
  12080. * @param priority - The priority to be written (string, number, or null).
  12081. * @returns Resolves when synchronization to the Database is complete.
  12082. */
  12083. setWithPriority(value, priority) {
  12084. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12085. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12086. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12087. const deferred = new Deferred();
  12088. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12089. return deferred.promise;
  12090. }
  12091. /**
  12092. * Writes multiple values at this location when the client is disconnected (due
  12093. * to closing the browser, navigating to a new page, or network issues).
  12094. *
  12095. * The `values` argument contains multiple property-value pairs that will be
  12096. * written to the Database together. Each child property can either be a simple
  12097. * property (for example, "name") or a relative path (for example, "name/first")
  12098. * from the current location to the data to update.
  12099. *
  12100. * As opposed to the `set()` method, `update()` can be use to selectively update
  12101. * only the referenced properties at the current location (instead of replacing
  12102. * all the child properties at the current location).
  12103. *
  12104. * @param values - Object containing multiple values.
  12105. * @returns Resolves when synchronization to the Database is complete.
  12106. */
  12107. update(values) {
  12108. validateWritablePath('OnDisconnect.update', this._path);
  12109. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12110. const deferred = new Deferred();
  12111. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12112. return deferred.promise;
  12113. }
  12114. }
  12115. /**
  12116. * @license
  12117. * Copyright 2020 Google LLC
  12118. *
  12119. * Licensed under the Apache License, Version 2.0 (the "License");
  12120. * you may not use this file except in compliance with the License.
  12121. * You may obtain a copy of the License at
  12122. *
  12123. * http://www.apache.org/licenses/LICENSE-2.0
  12124. *
  12125. * Unless required by applicable law or agreed to in writing, software
  12126. * distributed under the License is distributed on an "AS IS" BASIS,
  12127. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12128. * See the License for the specific language governing permissions and
  12129. * limitations under the License.
  12130. */
  12131. /**
  12132. * @internal
  12133. */
  12134. class QueryImpl {
  12135. /**
  12136. * @hideconstructor
  12137. */
  12138. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12139. this._repo = _repo;
  12140. this._path = _path;
  12141. this._queryParams = _queryParams;
  12142. this._orderByCalled = _orderByCalled;
  12143. }
  12144. get key() {
  12145. if (pathIsEmpty(this._path)) {
  12146. return null;
  12147. }
  12148. else {
  12149. return pathGetBack(this._path);
  12150. }
  12151. }
  12152. get ref() {
  12153. return new ReferenceImpl(this._repo, this._path);
  12154. }
  12155. get _queryIdentifier() {
  12156. const obj = queryParamsGetQueryObject(this._queryParams);
  12157. const id = ObjectToUniqueKey(obj);
  12158. return id === '{}' ? 'default' : id;
  12159. }
  12160. /**
  12161. * An object representation of the query parameters used by this Query.
  12162. */
  12163. get _queryObject() {
  12164. return queryParamsGetQueryObject(this._queryParams);
  12165. }
  12166. isEqual(other) {
  12167. other = getModularInstance(other);
  12168. if (!(other instanceof QueryImpl)) {
  12169. return false;
  12170. }
  12171. const sameRepo = this._repo === other._repo;
  12172. const samePath = pathEquals(this._path, other._path);
  12173. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12174. return sameRepo && samePath && sameQueryIdentifier;
  12175. }
  12176. toJSON() {
  12177. return this.toString();
  12178. }
  12179. toString() {
  12180. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12181. }
  12182. }
  12183. /**
  12184. * Validates that no other order by call has been made
  12185. */
  12186. function validateNoPreviousOrderByCall(query, fnName) {
  12187. if (query._orderByCalled === true) {
  12188. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12189. }
  12190. }
  12191. /**
  12192. * Validates start/end values for queries.
  12193. */
  12194. function validateQueryEndpoints(params) {
  12195. let startNode = null;
  12196. let endNode = null;
  12197. if (params.hasStart()) {
  12198. startNode = params.getIndexStartValue();
  12199. }
  12200. if (params.hasEnd()) {
  12201. endNode = params.getIndexEndValue();
  12202. }
  12203. if (params.getIndex() === KEY_INDEX) {
  12204. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12205. 'startAt(), endAt(), or equalTo().';
  12206. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12207. 'endAt(), endBefore(), or equalTo() must be a string.';
  12208. if (params.hasStart()) {
  12209. const startName = params.getIndexStartName();
  12210. if (startName !== MIN_NAME) {
  12211. throw new Error(tooManyArgsError);
  12212. }
  12213. else if (typeof startNode !== 'string') {
  12214. throw new Error(wrongArgTypeError);
  12215. }
  12216. }
  12217. if (params.hasEnd()) {
  12218. const endName = params.getIndexEndName();
  12219. if (endName !== MAX_NAME) {
  12220. throw new Error(tooManyArgsError);
  12221. }
  12222. else if (typeof endNode !== 'string') {
  12223. throw new Error(wrongArgTypeError);
  12224. }
  12225. }
  12226. }
  12227. else if (params.getIndex() === PRIORITY_INDEX) {
  12228. if ((startNode != null && !isValidPriority(startNode)) ||
  12229. (endNode != null && !isValidPriority(endNode))) {
  12230. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12231. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12232. '(null, a number, or a string).');
  12233. }
  12234. }
  12235. else {
  12236. assert(params.getIndex() instanceof PathIndex ||
  12237. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12238. if ((startNode != null && typeof startNode === 'object') ||
  12239. (endNode != null && typeof endNode === 'object')) {
  12240. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12241. 'equalTo() cannot be an object.');
  12242. }
  12243. }
  12244. }
  12245. /**
  12246. * Validates that limit* has been called with the correct combination of parameters
  12247. */
  12248. function validateLimit(params) {
  12249. if (params.hasStart() &&
  12250. params.hasEnd() &&
  12251. params.hasLimit() &&
  12252. !params.hasAnchoredLimit()) {
  12253. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12254. 'limitToFirst() or limitToLast() instead.');
  12255. }
  12256. }
  12257. /**
  12258. * @internal
  12259. */
  12260. class ReferenceImpl extends QueryImpl {
  12261. /** @hideconstructor */
  12262. constructor(repo, path) {
  12263. super(repo, path, new QueryParams(), false);
  12264. }
  12265. get parent() {
  12266. const parentPath = pathParent(this._path);
  12267. return parentPath === null
  12268. ? null
  12269. : new ReferenceImpl(this._repo, parentPath);
  12270. }
  12271. get root() {
  12272. let ref = this;
  12273. while (ref.parent !== null) {
  12274. ref = ref.parent;
  12275. }
  12276. return ref;
  12277. }
  12278. }
  12279. /**
  12280. * A `DataSnapshot` contains data from a Database location.
  12281. *
  12282. * Any time you read data from the Database, you receive the data as a
  12283. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12284. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12285. * JavaScript object by calling the `val()` method. Alternatively, you can
  12286. * traverse into the snapshot by calling `child()` to return child snapshots
  12287. * (which you could then call `val()` on).
  12288. *
  12289. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12290. * a Database location. It cannot be modified and will never change (to modify
  12291. * data, you always call the `set()` method on a `Reference` directly).
  12292. */
  12293. class DataSnapshot {
  12294. /**
  12295. * @param _node - A SnapshotNode to wrap.
  12296. * @param ref - The location this snapshot came from.
  12297. * @param _index - The iteration order for this snapshot
  12298. * @hideconstructor
  12299. */
  12300. constructor(_node,
  12301. /**
  12302. * The location of this DataSnapshot.
  12303. */
  12304. ref, _index) {
  12305. this._node = _node;
  12306. this.ref = ref;
  12307. this._index = _index;
  12308. }
  12309. /**
  12310. * Gets the priority value of the data in this `DataSnapshot`.
  12311. *
  12312. * Applications need not use priority but can order collections by
  12313. * ordinary properties (see
  12314. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12315. * ).
  12316. */
  12317. get priority() {
  12318. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12319. return this._node.getPriority().val();
  12320. }
  12321. /**
  12322. * The key (last part of the path) of the location of this `DataSnapshot`.
  12323. *
  12324. * The last token in a Database location is considered its key. For example,
  12325. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12326. * `DataSnapshot` will return the key for the location that generated it.
  12327. * However, accessing the key on the root URL of a Database will return
  12328. * `null`.
  12329. */
  12330. get key() {
  12331. return this.ref.key;
  12332. }
  12333. /** Returns the number of child properties of this `DataSnapshot`. */
  12334. get size() {
  12335. return this._node.numChildren();
  12336. }
  12337. /**
  12338. * Gets another `DataSnapshot` for the location at the specified relative path.
  12339. *
  12340. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12341. * another `DataSnapshot` for the location at the specified relative path. The
  12342. * relative path can either be a simple child name (for example, "ada") or a
  12343. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12344. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12345. * whose value is `null`) is returned.
  12346. *
  12347. * @param path - A relative path to the location of child data.
  12348. */
  12349. child(path) {
  12350. const childPath = new Path(path);
  12351. const childRef = child(this.ref, path);
  12352. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12353. }
  12354. /**
  12355. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12356. * efficient than using `snapshot.val() !== null`.
  12357. */
  12358. exists() {
  12359. return !this._node.isEmpty();
  12360. }
  12361. /**
  12362. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12363. *
  12364. * The `exportVal()` method is similar to `val()`, except priority information
  12365. * is included (if available), making it suitable for backing up your data.
  12366. *
  12367. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12368. * Array, string, number, boolean, or `null`).
  12369. */
  12370. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12371. exportVal() {
  12372. return this._node.val(true);
  12373. }
  12374. /**
  12375. * Enumerates the top-level children in the `IteratedDataSnapshot`.
  12376. *
  12377. * Because of the way JavaScript objects work, the ordering of data in the
  12378. * JavaScript object returned by `val()` is not guaranteed to match the
  12379. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12380. * where `forEach()` comes in handy. It guarantees the children of a
  12381. * `DataSnapshot` will be iterated in their query order.
  12382. *
  12383. * If no explicit `orderBy*()` method is used, results are returned
  12384. * ordered by key (unless priorities are used, in which case, results are
  12385. * returned by priority).
  12386. *
  12387. * @param action - A function that will be called for each child DataSnapshot.
  12388. * The callback can return true to cancel further enumeration.
  12389. * @returns true if enumeration was canceled due to your callback returning
  12390. * true.
  12391. */
  12392. forEach(action) {
  12393. if (this._node.isLeafNode()) {
  12394. return false;
  12395. }
  12396. const childrenNode = this._node;
  12397. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12398. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12399. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12400. });
  12401. }
  12402. /**
  12403. * Returns true if the specified child path has (non-null) data.
  12404. *
  12405. * @param path - A relative path to the location of a potential child.
  12406. * @returns `true` if data exists at the specified child path; else
  12407. * `false`.
  12408. */
  12409. hasChild(path) {
  12410. const childPath = new Path(path);
  12411. return !this._node.getChild(childPath).isEmpty();
  12412. }
  12413. /**
  12414. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12415. * properties.
  12416. *
  12417. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12418. * children. If it does, you can enumerate them using `forEach()`. If it
  12419. * doesn't, then either this snapshot contains a primitive value (which can be
  12420. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12421. * `null`).
  12422. *
  12423. * @returns true if this snapshot has any children; else false.
  12424. */
  12425. hasChildren() {
  12426. if (this._node.isLeafNode()) {
  12427. return false;
  12428. }
  12429. else {
  12430. return !this._node.isEmpty();
  12431. }
  12432. }
  12433. /**
  12434. * Returns a JSON-serializable representation of this object.
  12435. */
  12436. toJSON() {
  12437. return this.exportVal();
  12438. }
  12439. /**
  12440. * Extracts a JavaScript value from a `DataSnapshot`.
  12441. *
  12442. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12443. * scalar type (string, number, or boolean), an array, or an object. It may
  12444. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12445. * data).
  12446. *
  12447. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12448. * Array, string, number, boolean, or `null`).
  12449. */
  12450. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12451. val() {
  12452. return this._node.val();
  12453. }
  12454. }
  12455. /**
  12456. *
  12457. * Returns a `Reference` representing the location in the Database
  12458. * corresponding to the provided path. If no path is provided, the `Reference`
  12459. * will point to the root of the Database.
  12460. *
  12461. * @param db - The database instance to obtain a reference for.
  12462. * @param path - Optional path representing the location the returned
  12463. * `Reference` will point. If not provided, the returned `Reference` will
  12464. * point to the root of the Database.
  12465. * @returns If a path is provided, a `Reference`
  12466. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12467. * root of the Database.
  12468. */
  12469. function ref(db, path) {
  12470. db = getModularInstance(db);
  12471. db._checkNotDeleted('ref');
  12472. return path !== undefined ? child(db._root, path) : db._root;
  12473. }
  12474. /**
  12475. * Returns a `Reference` representing the location in the Database
  12476. * corresponding to the provided Firebase URL.
  12477. *
  12478. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12479. * has a different domain than the current `Database` instance.
  12480. *
  12481. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12482. * and are not applied to the returned `Reference`.
  12483. *
  12484. * @param db - The database instance to obtain a reference for.
  12485. * @param url - The Firebase URL at which the returned `Reference` will
  12486. * point.
  12487. * @returns A `Reference` pointing to the provided
  12488. * Firebase URL.
  12489. */
  12490. function refFromURL(db, url) {
  12491. db = getModularInstance(db);
  12492. db._checkNotDeleted('refFromURL');
  12493. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12494. validateUrl('refFromURL', parsedURL);
  12495. const repoInfo = parsedURL.repoInfo;
  12496. if (!db._repo.repoInfo_.isCustomHost() &&
  12497. repoInfo.host !== db._repo.repoInfo_.host) {
  12498. fatal('refFromURL' +
  12499. ': Host name does not match the current database: ' +
  12500. '(found ' +
  12501. repoInfo.host +
  12502. ' but expected ' +
  12503. db._repo.repoInfo_.host +
  12504. ')');
  12505. }
  12506. return ref(db, parsedURL.path.toString());
  12507. }
  12508. /**
  12509. * Gets a `Reference` for the location at the specified relative path.
  12510. *
  12511. * The relative path can either be a simple child name (for example, "ada") or
  12512. * a deeper slash-separated path (for example, "ada/name/first").
  12513. *
  12514. * @param parent - The parent location.
  12515. * @param path - A relative path from this location to the desired child
  12516. * location.
  12517. * @returns The specified child location.
  12518. */
  12519. function child(parent, path) {
  12520. parent = getModularInstance(parent);
  12521. if (pathGetFront(parent._path) === null) {
  12522. validateRootPathString('child', 'path', path, false);
  12523. }
  12524. else {
  12525. validatePathString('child', 'path', path, false);
  12526. }
  12527. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12528. }
  12529. /**
  12530. * Returns an `OnDisconnect` object - see
  12531. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12532. * for more information on how to use it.
  12533. *
  12534. * @param ref - The reference to add OnDisconnect triggers for.
  12535. */
  12536. function onDisconnect(ref) {
  12537. ref = getModularInstance(ref);
  12538. return new OnDisconnect(ref._repo, ref._path);
  12539. }
  12540. /**
  12541. * Generates a new child location using a unique key and returns its
  12542. * `Reference`.
  12543. *
  12544. * This is the most common pattern for adding data to a collection of items.
  12545. *
  12546. * If you provide a value to `push()`, the value is written to the
  12547. * generated location. If you don't pass a value, nothing is written to the
  12548. * database and the child remains empty (but you can use the `Reference`
  12549. * elsewhere).
  12550. *
  12551. * The unique keys generated by `push()` are ordered by the current time, so the
  12552. * resulting list of items is chronologically sorted. The keys are also
  12553. * designed to be unguessable (they contain 72 random bits of entropy).
  12554. *
  12555. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12556. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12557. *
  12558. * @param parent - The parent location.
  12559. * @param value - Optional value to be written at the generated location.
  12560. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12561. * but can be used immediately as the `Reference` to the child location.
  12562. */
  12563. function push(parent, value) {
  12564. parent = getModularInstance(parent);
  12565. validateWritablePath('push', parent._path);
  12566. validateFirebaseDataArg('push', value, parent._path, true);
  12567. const now = repoServerTime(parent._repo);
  12568. const name = nextPushId(now);
  12569. // push() returns a ThennableReference whose promise is fulfilled with a
  12570. // regular Reference. We use child() to create handles to two different
  12571. // references. The first is turned into a ThennableReference below by adding
  12572. // then() and catch() methods and is used as the return value of push(). The
  12573. // second remains a regular Reference and is used as the fulfilled value of
  12574. // the first ThennableReference.
  12575. const thenablePushRef = child(parent, name);
  12576. const pushRef = child(parent, name);
  12577. let promise;
  12578. if (value != null) {
  12579. promise = set(pushRef, value).then(() => pushRef);
  12580. }
  12581. else {
  12582. promise = Promise.resolve(pushRef);
  12583. }
  12584. thenablePushRef.then = promise.then.bind(promise);
  12585. thenablePushRef.catch = promise.then.bind(promise, undefined);
  12586. return thenablePushRef;
  12587. }
  12588. /**
  12589. * Removes the data at this Database location.
  12590. *
  12591. * Any data at child locations will also be deleted.
  12592. *
  12593. * The effect of the remove will be visible immediately and the corresponding
  12594. * event 'value' will be triggered. Synchronization of the remove to the
  12595. * Firebase servers will also be started, and the returned Promise will resolve
  12596. * when complete. If provided, the onComplete callback will be called
  12597. * asynchronously after synchronization has finished.
  12598. *
  12599. * @param ref - The location to remove.
  12600. * @returns Resolves when remove on server is complete.
  12601. */
  12602. function remove(ref) {
  12603. validateWritablePath('remove', ref._path);
  12604. return set(ref, null);
  12605. }
  12606. /**
  12607. * Writes data to this Database location.
  12608. *
  12609. * This will overwrite any data at this location and all child locations.
  12610. *
  12611. * The effect of the write will be visible immediately, and the corresponding
  12612. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12613. * the data to the Firebase servers will also be started, and the returned
  12614. * Promise will resolve when complete. If provided, the `onComplete` callback
  12615. * will be called asynchronously after synchronization has finished.
  12616. *
  12617. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12618. * all data at this location and all child locations will be deleted.
  12619. *
  12620. * `set()` will remove any priority stored at this location, so if priority is
  12621. * meant to be preserved, you need to use `setWithPriority()` instead.
  12622. *
  12623. * Note that modifying data with `set()` will cancel any pending transactions
  12624. * at that location, so extreme care should be taken if mixing `set()` and
  12625. * `transaction()` to modify the same data.
  12626. *
  12627. * A single `set()` will generate a single "value" event at the location where
  12628. * the `set()` was performed.
  12629. *
  12630. * @param ref - The location to write to.
  12631. * @param value - The value to be written (string, number, boolean, object,
  12632. * array, or null).
  12633. * @returns Resolves when write to server is complete.
  12634. */
  12635. function set(ref, value) {
  12636. ref = getModularInstance(ref);
  12637. validateWritablePath('set', ref._path);
  12638. validateFirebaseDataArg('set', value, ref._path, false);
  12639. const deferred = new Deferred();
  12640. repoSetWithPriority(ref._repo, ref._path, value,
  12641. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12642. return deferred.promise;
  12643. }
  12644. /**
  12645. * Sets a priority for the data at this Database location.
  12646. *
  12647. * Applications need not use priority but can order collections by
  12648. * ordinary properties (see
  12649. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12650. * ).
  12651. *
  12652. * @param ref - The location to write to.
  12653. * @param priority - The priority to be written (string, number, or null).
  12654. * @returns Resolves when write to server is complete.
  12655. */
  12656. function setPriority(ref, priority) {
  12657. ref = getModularInstance(ref);
  12658. validateWritablePath('setPriority', ref._path);
  12659. validatePriority('setPriority', priority, false);
  12660. const deferred = new Deferred();
  12661. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12662. return deferred.promise;
  12663. }
  12664. /**
  12665. * Writes data the Database location. Like `set()` but also specifies the
  12666. * priority for that data.
  12667. *
  12668. * Applications need not use priority but can order collections by
  12669. * ordinary properties (see
  12670. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12671. * ).
  12672. *
  12673. * @param ref - The location to write to.
  12674. * @param value - The value to be written (string, number, boolean, object,
  12675. * array, or null).
  12676. * @param priority - The priority to be written (string, number, or null).
  12677. * @returns Resolves when write to server is complete.
  12678. */
  12679. function setWithPriority(ref, value, priority) {
  12680. validateWritablePath('setWithPriority', ref._path);
  12681. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12682. validatePriority('setWithPriority', priority, false);
  12683. if (ref.key === '.length' || ref.key === '.keys') {
  12684. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12685. }
  12686. const deferred = new Deferred();
  12687. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12688. return deferred.promise;
  12689. }
  12690. /**
  12691. * Writes multiple values to the Database at once.
  12692. *
  12693. * The `values` argument contains multiple property-value pairs that will be
  12694. * written to the Database together. Each child property can either be a simple
  12695. * property (for example, "name") or a relative path (for example,
  12696. * "name/first") from the current location to the data to update.
  12697. *
  12698. * As opposed to the `set()` method, `update()` can be use to selectively update
  12699. * only the referenced properties at the current location (instead of replacing
  12700. * all the child properties at the current location).
  12701. *
  12702. * The effect of the write will be visible immediately, and the corresponding
  12703. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12704. * the data to the Firebase servers will also be started, and the returned
  12705. * Promise will resolve when complete. If provided, the `onComplete` callback
  12706. * will be called asynchronously after synchronization has finished.
  12707. *
  12708. * A single `update()` will generate a single "value" event at the location
  12709. * where the `update()` was performed, regardless of how many children were
  12710. * modified.
  12711. *
  12712. * Note that modifying data with `update()` will cancel any pending
  12713. * transactions at that location, so extreme care should be taken if mixing
  12714. * `update()` and `transaction()` to modify the same data.
  12715. *
  12716. * Passing `null` to `update()` will remove the data at this location.
  12717. *
  12718. * See
  12719. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12720. *
  12721. * @param ref - The location to write to.
  12722. * @param values - Object containing multiple values.
  12723. * @returns Resolves when update on server is complete.
  12724. */
  12725. function update(ref, values) {
  12726. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12727. const deferred = new Deferred();
  12728. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12729. return deferred.promise;
  12730. }
  12731. /**
  12732. * Gets the most up-to-date result for this query.
  12733. *
  12734. * @param query - The query to run.
  12735. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12736. * available, or rejects if the client is unable to return a value (e.g., if the
  12737. * server is unreachable and there is nothing cached).
  12738. */
  12739. function get(query) {
  12740. query = getModularInstance(query);
  12741. const callbackContext = new CallbackContext(() => { });
  12742. const container = new ValueEventRegistration(callbackContext);
  12743. return repoGetValue(query._repo, query, container).then(node => {
  12744. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12745. });
  12746. }
  12747. /**
  12748. * Represents registration for 'value' events.
  12749. */
  12750. class ValueEventRegistration {
  12751. constructor(callbackContext) {
  12752. this.callbackContext = callbackContext;
  12753. }
  12754. respondsTo(eventType) {
  12755. return eventType === 'value';
  12756. }
  12757. createEvent(change, query) {
  12758. const index = query._queryParams.getIndex();
  12759. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12760. }
  12761. getEventRunner(eventData) {
  12762. if (eventData.getEventType() === 'cancel') {
  12763. return () => this.callbackContext.onCancel(eventData.error);
  12764. }
  12765. else {
  12766. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12767. }
  12768. }
  12769. createCancelEvent(error, path) {
  12770. if (this.callbackContext.hasCancelCallback) {
  12771. return new CancelEvent(this, error, path);
  12772. }
  12773. else {
  12774. return null;
  12775. }
  12776. }
  12777. matches(other) {
  12778. if (!(other instanceof ValueEventRegistration)) {
  12779. return false;
  12780. }
  12781. else if (!other.callbackContext || !this.callbackContext) {
  12782. // If no callback specified, we consider it to match any callback.
  12783. return true;
  12784. }
  12785. else {
  12786. return other.callbackContext.matches(this.callbackContext);
  12787. }
  12788. }
  12789. hasAnyCallback() {
  12790. return this.callbackContext !== null;
  12791. }
  12792. }
  12793. /**
  12794. * Represents the registration of a child_x event.
  12795. */
  12796. class ChildEventRegistration {
  12797. constructor(eventType, callbackContext) {
  12798. this.eventType = eventType;
  12799. this.callbackContext = callbackContext;
  12800. }
  12801. respondsTo(eventType) {
  12802. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12803. eventToCheck =
  12804. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12805. return this.eventType === eventToCheck;
  12806. }
  12807. createCancelEvent(error, path) {
  12808. if (this.callbackContext.hasCancelCallback) {
  12809. return new CancelEvent(this, error, path);
  12810. }
  12811. else {
  12812. return null;
  12813. }
  12814. }
  12815. createEvent(change, query) {
  12816. assert(change.childName != null, 'Child events should have a childName.');
  12817. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12818. const index = query._queryParams.getIndex();
  12819. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12820. }
  12821. getEventRunner(eventData) {
  12822. if (eventData.getEventType() === 'cancel') {
  12823. return () => this.callbackContext.onCancel(eventData.error);
  12824. }
  12825. else {
  12826. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12827. }
  12828. }
  12829. matches(other) {
  12830. if (other instanceof ChildEventRegistration) {
  12831. return (this.eventType === other.eventType &&
  12832. (!this.callbackContext ||
  12833. !other.callbackContext ||
  12834. this.callbackContext.matches(other.callbackContext)));
  12835. }
  12836. return false;
  12837. }
  12838. hasAnyCallback() {
  12839. return !!this.callbackContext;
  12840. }
  12841. }
  12842. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12843. let cancelCallback;
  12844. if (typeof cancelCallbackOrListenOptions === 'object') {
  12845. cancelCallback = undefined;
  12846. options = cancelCallbackOrListenOptions;
  12847. }
  12848. if (typeof cancelCallbackOrListenOptions === 'function') {
  12849. cancelCallback = cancelCallbackOrListenOptions;
  12850. }
  12851. if (options && options.onlyOnce) {
  12852. const userCallback = callback;
  12853. const onceCallback = (dataSnapshot, previousChildName) => {
  12854. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12855. userCallback(dataSnapshot, previousChildName);
  12856. };
  12857. onceCallback.userCallback = callback.userCallback;
  12858. onceCallback.context = callback.context;
  12859. callback = onceCallback;
  12860. }
  12861. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12862. const container = eventType === 'value'
  12863. ? new ValueEventRegistration(callbackContext)
  12864. : new ChildEventRegistration(eventType, callbackContext);
  12865. repoAddEventCallbackForQuery(query._repo, query, container);
  12866. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12867. }
  12868. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12869. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12870. }
  12871. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12872. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12873. }
  12874. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12875. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12876. }
  12877. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12878. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12879. }
  12880. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12881. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12882. }
  12883. /**
  12884. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12885. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12886. * the respective `on*` callbacks.
  12887. *
  12888. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12889. * will not automatically remove listeners registered on child nodes, `off()`
  12890. * must also be called on any child listeners to remove the callback.
  12891. *
  12892. * If a callback is not specified, all callbacks for the specified eventType
  12893. * will be removed. Similarly, if no eventType is specified, all callbacks
  12894. * for the `Reference` will be removed.
  12895. *
  12896. * Individual listeners can also be removed by invoking their unsubscribe
  12897. * callbacks.
  12898. *
  12899. * @param query - The query that the listener was registered with.
  12900. * @param eventType - One of the following strings: "value", "child_added",
  12901. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12902. * for the `Reference` will be removed.
  12903. * @param callback - The callback function that was passed to `on()` or
  12904. * `undefined` to remove all callbacks.
  12905. */
  12906. function off(query, eventType, callback) {
  12907. let container = null;
  12908. const expCallback = callback ? new CallbackContext(callback) : null;
  12909. if (eventType === 'value') {
  12910. container = new ValueEventRegistration(expCallback);
  12911. }
  12912. else if (eventType) {
  12913. container = new ChildEventRegistration(eventType, expCallback);
  12914. }
  12915. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12916. }
  12917. /**
  12918. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12919. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12920. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12921. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12922. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12923. * {@link orderByValue} or {@link equalTo} and
  12924. * can then be passed to {@link query} to create a new query instance that
  12925. * also contains this `QueryConstraint`.
  12926. */
  12927. class QueryConstraint {
  12928. }
  12929. class QueryEndAtConstraint extends QueryConstraint {
  12930. constructor(_value, _key) {
  12931. super();
  12932. this._value = _value;
  12933. this._key = _key;
  12934. this.type = 'endAt';
  12935. }
  12936. _apply(query) {
  12937. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12938. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12939. validateLimit(newParams);
  12940. validateQueryEndpoints(newParams);
  12941. if (query._queryParams.hasEnd()) {
  12942. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12943. 'endBefore or equalTo).');
  12944. }
  12945. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12946. }
  12947. }
  12948. /**
  12949. * Creates a `QueryConstraint` with the specified ending point.
  12950. *
  12951. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12952. * allows you to choose arbitrary starting and ending points for your queries.
  12953. *
  12954. * The ending point is inclusive, so children with exactly the specified value
  12955. * will be included in the query. The optional key argument can be used to
  12956. * further limit the range of the query. If it is specified, then children that
  12957. * have exactly the specified value must also have a key name less than or equal
  12958. * to the specified key.
  12959. *
  12960. * You can read more about `endAt()` in
  12961. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12962. *
  12963. * @param value - The value to end at. The argument type depends on which
  12964. * `orderBy*()` function was used in this query. Specify a value that matches
  12965. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12966. * value must be a string.
  12967. * @param key - The child key to end at, among the children with the previously
  12968. * specified priority. This argument is only allowed if ordering by child,
  12969. * value, or priority.
  12970. */
  12971. function endAt(value, key) {
  12972. validateKey('endAt', 'key', key, true);
  12973. return new QueryEndAtConstraint(value, key);
  12974. }
  12975. class QueryEndBeforeConstraint extends QueryConstraint {
  12976. constructor(_value, _key) {
  12977. super();
  12978. this._value = _value;
  12979. this._key = _key;
  12980. this.type = 'endBefore';
  12981. }
  12982. _apply(query) {
  12983. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12984. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12985. validateLimit(newParams);
  12986. validateQueryEndpoints(newParams);
  12987. if (query._queryParams.hasEnd()) {
  12988. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12989. 'endBefore or equalTo).');
  12990. }
  12991. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12992. }
  12993. }
  12994. /**
  12995. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12996. *
  12997. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12998. * allows you to choose arbitrary starting and ending points for your queries.
  12999. *
  13000. * The ending point is exclusive. If only a value is provided, children
  13001. * with a value less than the specified value will be included in the query.
  13002. * If a key is specified, then children must have a value less than or equal
  13003. * to the specified value and a key name less than the specified key.
  13004. *
  13005. * @param value - The value to end before. The argument type depends on which
  13006. * `orderBy*()` function was used in this query. Specify a value that matches
  13007. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13008. * value must be a string.
  13009. * @param key - The child key to end before, among the children with the
  13010. * previously specified priority. This argument is only allowed if ordering by
  13011. * child, value, or priority.
  13012. */
  13013. function endBefore(value, key) {
  13014. validateKey('endBefore', 'key', key, true);
  13015. return new QueryEndBeforeConstraint(value, key);
  13016. }
  13017. class QueryStartAtConstraint extends QueryConstraint {
  13018. constructor(_value, _key) {
  13019. super();
  13020. this._value = _value;
  13021. this._key = _key;
  13022. this.type = 'startAt';
  13023. }
  13024. _apply(query) {
  13025. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13026. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13027. validateLimit(newParams);
  13028. validateQueryEndpoints(newParams);
  13029. if (query._queryParams.hasStart()) {
  13030. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13031. 'startBefore or equalTo).');
  13032. }
  13033. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13034. }
  13035. }
  13036. /**
  13037. * Creates a `QueryConstraint` with the specified starting point.
  13038. *
  13039. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13040. * allows you to choose arbitrary starting and ending points for your queries.
  13041. *
  13042. * The starting point is inclusive, so children with exactly the specified value
  13043. * will be included in the query. The optional key argument can be used to
  13044. * further limit the range of the query. If it is specified, then children that
  13045. * have exactly the specified value must also have a key name greater than or
  13046. * equal to the specified key.
  13047. *
  13048. * You can read more about `startAt()` in
  13049. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13050. *
  13051. * @param value - The value to start at. The argument type depends on which
  13052. * `orderBy*()` function was used in this query. Specify a value that matches
  13053. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13054. * value must be a string.
  13055. * @param key - The child key to start at. This argument is only allowed if
  13056. * ordering by child, value, or priority.
  13057. */
  13058. function startAt(value = null, key) {
  13059. validateKey('startAt', 'key', key, true);
  13060. return new QueryStartAtConstraint(value, key);
  13061. }
  13062. class QueryStartAfterConstraint extends QueryConstraint {
  13063. constructor(_value, _key) {
  13064. super();
  13065. this._value = _value;
  13066. this._key = _key;
  13067. this.type = 'startAfter';
  13068. }
  13069. _apply(query) {
  13070. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13071. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13072. validateLimit(newParams);
  13073. validateQueryEndpoints(newParams);
  13074. if (query._queryParams.hasStart()) {
  13075. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13076. 'startAfter, or equalTo).');
  13077. }
  13078. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13079. }
  13080. }
  13081. /**
  13082. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13083. *
  13084. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13085. * allows you to choose arbitrary starting and ending points for your queries.
  13086. *
  13087. * The starting point is exclusive. If only a value is provided, children
  13088. * with a value greater than the specified value will be included in the query.
  13089. * If a key is specified, then children must have a value greater than or equal
  13090. * to the specified value and a a key name greater than the specified key.
  13091. *
  13092. * @param value - The value to start after. The argument type depends on which
  13093. * `orderBy*()` function was used in this query. Specify a value that matches
  13094. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13095. * value must be a string.
  13096. * @param key - The child key to start after. This argument is only allowed if
  13097. * ordering by child, value, or priority.
  13098. */
  13099. function startAfter(value, key) {
  13100. validateKey('startAfter', 'key', key, true);
  13101. return new QueryStartAfterConstraint(value, key);
  13102. }
  13103. class QueryLimitToFirstConstraint extends QueryConstraint {
  13104. constructor(_limit) {
  13105. super();
  13106. this._limit = _limit;
  13107. this.type = 'limitToFirst';
  13108. }
  13109. _apply(query) {
  13110. if (query._queryParams.hasLimit()) {
  13111. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13112. 'or limitToLast).');
  13113. }
  13114. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13115. }
  13116. }
  13117. /**
  13118. * Creates a new `QueryConstraint` that if limited to the first specific number
  13119. * of children.
  13120. *
  13121. * The `limitToFirst()` method is used to set a maximum number of children to be
  13122. * synced for a given callback. If we set a limit of 100, we will initially only
  13123. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13124. * stored in our Database, a `child_added` event will fire for each message.
  13125. * However, if we have over 100 messages, we will only receive a `child_added`
  13126. * event for the first 100 ordered messages. As items change, we will receive
  13127. * `child_removed` events for each item that drops out of the active list so
  13128. * that the total number stays at 100.
  13129. *
  13130. * You can read more about `limitToFirst()` in
  13131. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13132. *
  13133. * @param limit - The maximum number of nodes to include in this query.
  13134. */
  13135. function limitToFirst(limit) {
  13136. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13137. throw new Error('limitToFirst: First argument must be a positive integer.');
  13138. }
  13139. return new QueryLimitToFirstConstraint(limit);
  13140. }
  13141. class QueryLimitToLastConstraint extends QueryConstraint {
  13142. constructor(_limit) {
  13143. super();
  13144. this._limit = _limit;
  13145. this.type = 'limitToLast';
  13146. }
  13147. _apply(query) {
  13148. if (query._queryParams.hasLimit()) {
  13149. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13150. 'or limitToLast).');
  13151. }
  13152. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13153. }
  13154. }
  13155. /**
  13156. * Creates a new `QueryConstraint` that is limited to return only the last
  13157. * specified number of children.
  13158. *
  13159. * The `limitToLast()` method is used to set a maximum number of children to be
  13160. * synced for a given callback. If we set a limit of 100, we will initially only
  13161. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13162. * stored in our Database, a `child_added` event will fire for each message.
  13163. * However, if we have over 100 messages, we will only receive a `child_added`
  13164. * event for the last 100 ordered messages. As items change, we will receive
  13165. * `child_removed` events for each item that drops out of the active list so
  13166. * that the total number stays at 100.
  13167. *
  13168. * You can read more about `limitToLast()` in
  13169. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13170. *
  13171. * @param limit - The maximum number of nodes to include in this query.
  13172. */
  13173. function limitToLast(limit) {
  13174. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13175. throw new Error('limitToLast: First argument must be a positive integer.');
  13176. }
  13177. return new QueryLimitToLastConstraint(limit);
  13178. }
  13179. class QueryOrderByChildConstraint extends QueryConstraint {
  13180. constructor(_path) {
  13181. super();
  13182. this._path = _path;
  13183. this.type = 'orderByChild';
  13184. }
  13185. _apply(query) {
  13186. validateNoPreviousOrderByCall(query, 'orderByChild');
  13187. const parsedPath = new Path(this._path);
  13188. if (pathIsEmpty(parsedPath)) {
  13189. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13190. }
  13191. const index = new PathIndex(parsedPath);
  13192. const newParams = queryParamsOrderBy(query._queryParams, index);
  13193. validateQueryEndpoints(newParams);
  13194. return new QueryImpl(query._repo, query._path, newParams,
  13195. /*orderByCalled=*/ true);
  13196. }
  13197. }
  13198. /**
  13199. * Creates a new `QueryConstraint` that orders by the specified child key.
  13200. *
  13201. * Queries can only order by one key at a time. Calling `orderByChild()`
  13202. * multiple times on the same query is an error.
  13203. *
  13204. * Firebase queries allow you to order your data by any child key on the fly.
  13205. * However, if you know in advance what your indexes will be, you can define
  13206. * them via the .indexOn rule in your Security Rules for better performance. See
  13207. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13208. * rule for more information.
  13209. *
  13210. * You can read more about `orderByChild()` in
  13211. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13212. *
  13213. * @param path - The path to order by.
  13214. */
  13215. function orderByChild(path) {
  13216. if (path === '$key') {
  13217. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13218. }
  13219. else if (path === '$priority') {
  13220. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13221. }
  13222. else if (path === '$value') {
  13223. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13224. }
  13225. validatePathString('orderByChild', 'path', path, false);
  13226. return new QueryOrderByChildConstraint(path);
  13227. }
  13228. class QueryOrderByKeyConstraint extends QueryConstraint {
  13229. constructor() {
  13230. super(...arguments);
  13231. this.type = 'orderByKey';
  13232. }
  13233. _apply(query) {
  13234. validateNoPreviousOrderByCall(query, 'orderByKey');
  13235. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13236. validateQueryEndpoints(newParams);
  13237. return new QueryImpl(query._repo, query._path, newParams,
  13238. /*orderByCalled=*/ true);
  13239. }
  13240. }
  13241. /**
  13242. * Creates a new `QueryConstraint` that orders by the key.
  13243. *
  13244. * Sorts the results of a query by their (ascending) key values.
  13245. *
  13246. * You can read more about `orderByKey()` in
  13247. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13248. */
  13249. function orderByKey() {
  13250. return new QueryOrderByKeyConstraint();
  13251. }
  13252. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13253. constructor() {
  13254. super(...arguments);
  13255. this.type = 'orderByPriority';
  13256. }
  13257. _apply(query) {
  13258. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13259. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13260. validateQueryEndpoints(newParams);
  13261. return new QueryImpl(query._repo, query._path, newParams,
  13262. /*orderByCalled=*/ true);
  13263. }
  13264. }
  13265. /**
  13266. * Creates a new `QueryConstraint` that orders by priority.
  13267. *
  13268. * Applications need not use priority but can order collections by
  13269. * ordinary properties (see
  13270. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13271. * for alternatives to priority.
  13272. */
  13273. function orderByPriority() {
  13274. return new QueryOrderByPriorityConstraint();
  13275. }
  13276. class QueryOrderByValueConstraint extends QueryConstraint {
  13277. constructor() {
  13278. super(...arguments);
  13279. this.type = 'orderByValue';
  13280. }
  13281. _apply(query) {
  13282. validateNoPreviousOrderByCall(query, 'orderByValue');
  13283. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13284. validateQueryEndpoints(newParams);
  13285. return new QueryImpl(query._repo, query._path, newParams,
  13286. /*orderByCalled=*/ true);
  13287. }
  13288. }
  13289. /**
  13290. * Creates a new `QueryConstraint` that orders by value.
  13291. *
  13292. * If the children of a query are all scalar values (string, number, or
  13293. * boolean), you can order the results by their (ascending) values.
  13294. *
  13295. * You can read more about `orderByValue()` in
  13296. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13297. */
  13298. function orderByValue() {
  13299. return new QueryOrderByValueConstraint();
  13300. }
  13301. class QueryEqualToValueConstraint extends QueryConstraint {
  13302. constructor(_value, _key) {
  13303. super();
  13304. this._value = _value;
  13305. this._key = _key;
  13306. this.type = 'equalTo';
  13307. }
  13308. _apply(query) {
  13309. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13310. if (query._queryParams.hasStart()) {
  13311. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13312. 'equalTo).');
  13313. }
  13314. if (query._queryParams.hasEnd()) {
  13315. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13316. 'equalTo).');
  13317. }
  13318. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13319. }
  13320. }
  13321. /**
  13322. * Creates a `QueryConstraint` that includes children that match the specified
  13323. * value.
  13324. *
  13325. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13326. * allows you to choose arbitrary starting and ending points for your queries.
  13327. *
  13328. * The optional key argument can be used to further limit the range of the
  13329. * query. If it is specified, then children that have exactly the specified
  13330. * value must also have exactly the specified key as their key name. This can be
  13331. * used to filter result sets with many matches for the same value.
  13332. *
  13333. * You can read more about `equalTo()` in
  13334. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13335. *
  13336. * @param value - The value to match for. The argument type depends on which
  13337. * `orderBy*()` function was used in this query. Specify a value that matches
  13338. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13339. * value must be a string.
  13340. * @param key - The child key to start at, among the children with the
  13341. * previously specified priority. This argument is only allowed if ordering by
  13342. * child, value, or priority.
  13343. */
  13344. function equalTo(value, key) {
  13345. validateKey('equalTo', 'key', key, true);
  13346. return new QueryEqualToValueConstraint(value, key);
  13347. }
  13348. /**
  13349. * Creates a new immutable instance of `Query` that is extended to also include
  13350. * additional query constraints.
  13351. *
  13352. * @param query - The Query instance to use as a base for the new constraints.
  13353. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13354. * @throws if any of the provided query constraints cannot be combined with the
  13355. * existing or new constraints.
  13356. */
  13357. function query(query, ...queryConstraints) {
  13358. let queryImpl = getModularInstance(query);
  13359. for (const constraint of queryConstraints) {
  13360. queryImpl = constraint._apply(queryImpl);
  13361. }
  13362. return queryImpl;
  13363. }
  13364. /**
  13365. * Define reference constructor in various modules
  13366. *
  13367. * We are doing this here to avoid several circular
  13368. * dependency issues
  13369. */
  13370. syncPointSetReferenceConstructor(ReferenceImpl);
  13371. syncTreeSetReferenceConstructor(ReferenceImpl);
  13372. /**
  13373. * @license
  13374. * Copyright 2020 Google LLC
  13375. *
  13376. * Licensed under the Apache License, Version 2.0 (the "License");
  13377. * you may not use this file except in compliance with the License.
  13378. * You may obtain a copy of the License at
  13379. *
  13380. * http://www.apache.org/licenses/LICENSE-2.0
  13381. *
  13382. * Unless required by applicable law or agreed to in writing, software
  13383. * distributed under the License is distributed on an "AS IS" BASIS,
  13384. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13385. * See the License for the specific language governing permissions and
  13386. * limitations under the License.
  13387. */
  13388. /**
  13389. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13390. * modifying this definition, consult the definition in:
  13391. *
  13392. * https://github.com/firebase/firebase-admin-node
  13393. *
  13394. * and make sure the two are consistent.
  13395. */
  13396. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13397. /**
  13398. * Creates and caches `Repo` instances.
  13399. */
  13400. const repos = {};
  13401. /**
  13402. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13403. */
  13404. let useRestClient = false;
  13405. /**
  13406. * Update an existing `Repo` in place to point to a new host/port.
  13407. */
  13408. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13409. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13410. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
  13411. /*isUsingEmulator=*/ true);
  13412. if (tokenProvider) {
  13413. repo.authTokenProvider_ = tokenProvider;
  13414. }
  13415. }
  13416. /**
  13417. * This function should only ever be called to CREATE a new database instance.
  13418. * @internal
  13419. */
  13420. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13421. let dbUrl = url || app.options.databaseURL;
  13422. if (dbUrl === undefined) {
  13423. if (!app.options.projectId) {
  13424. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13425. ' a Project ID when calling firebase.initializeApp().');
  13426. }
  13427. log('Using default host for project ', app.options.projectId);
  13428. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13429. }
  13430. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13431. let repoInfo = parsedUrl.repoInfo;
  13432. let isEmulator;
  13433. let dbEmulatorHost = undefined;
  13434. if (typeof process !== 'undefined' && process.env) {
  13435. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13436. }
  13437. if (dbEmulatorHost) {
  13438. isEmulator = true;
  13439. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13440. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13441. repoInfo = parsedUrl.repoInfo;
  13442. }
  13443. else {
  13444. isEmulator = !parsedUrl.repoInfo.secure;
  13445. }
  13446. const authTokenProvider = nodeAdmin && isEmulator
  13447. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13448. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13449. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13450. if (!pathIsEmpty(parsedUrl.path)) {
  13451. fatal('Database URL must point to the root of a Firebase Database ' +
  13452. '(not including a child path).');
  13453. }
  13454. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13455. return new Database(repo, app);
  13456. }
  13457. /**
  13458. * Remove the repo and make sure it is disconnected.
  13459. *
  13460. */
  13461. function repoManagerDeleteRepo(repo, appName) {
  13462. const appRepos = repos[appName];
  13463. // This should never happen...
  13464. if (!appRepos || appRepos[repo.key] !== repo) {
  13465. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13466. }
  13467. repoInterrupt(repo);
  13468. delete appRepos[repo.key];
  13469. }
  13470. /**
  13471. * Ensures a repo doesn't already exist and then creates one using the
  13472. * provided app.
  13473. *
  13474. * @param repoInfo - The metadata about the Repo
  13475. * @returns The Repo object for the specified server / repoName.
  13476. */
  13477. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13478. let appRepos = repos[app.name];
  13479. if (!appRepos) {
  13480. appRepos = {};
  13481. repos[app.name] = appRepos;
  13482. }
  13483. let repo = appRepos[repoInfo.toURLString()];
  13484. if (repo) {
  13485. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13486. }
  13487. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13488. appRepos[repoInfo.toURLString()] = repo;
  13489. return repo;
  13490. }
  13491. /**
  13492. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13493. */
  13494. function repoManagerForceRestClient(forceRestClient) {
  13495. useRestClient = forceRestClient;
  13496. }
  13497. /**
  13498. * Class representing a Firebase Realtime Database.
  13499. */
  13500. class Database {
  13501. /** @hideconstructor */
  13502. constructor(_repoInternal,
  13503. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13504. app) {
  13505. this._repoInternal = _repoInternal;
  13506. this.app = app;
  13507. /** Represents a `Database` instance. */
  13508. this['type'] = 'database';
  13509. /** Track if the instance has been used (root or repo accessed) */
  13510. this._instanceStarted = false;
  13511. }
  13512. get _repo() {
  13513. if (!this._instanceStarted) {
  13514. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13515. this._instanceStarted = true;
  13516. }
  13517. return this._repoInternal;
  13518. }
  13519. get _root() {
  13520. if (!this._rootInternal) {
  13521. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13522. }
  13523. return this._rootInternal;
  13524. }
  13525. _delete() {
  13526. if (this._rootInternal !== null) {
  13527. repoManagerDeleteRepo(this._repo, this.app.name);
  13528. this._repoInternal = null;
  13529. this._rootInternal = null;
  13530. }
  13531. return Promise.resolve();
  13532. }
  13533. _checkNotDeleted(apiName) {
  13534. if (this._rootInternal === null) {
  13535. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13536. }
  13537. }
  13538. }
  13539. function checkTransportInit() {
  13540. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13541. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13542. }
  13543. }
  13544. /**
  13545. * Force the use of websockets instead of longPolling.
  13546. */
  13547. function forceWebSockets() {
  13548. checkTransportInit();
  13549. BrowserPollConnection.forceDisallow();
  13550. }
  13551. /**
  13552. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13553. */
  13554. function forceLongPolling() {
  13555. checkTransportInit();
  13556. WebSocketConnection.forceDisallow();
  13557. BrowserPollConnection.forceAllow();
  13558. }
  13559. /**
  13560. * Returns the instance of the Realtime Database SDK that is associated with the provided
  13561. * {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if
  13562. * no instance exists or if the existing instance uses a custom database URL.
  13563. *
  13564. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13565. * Database instance is associated with.
  13566. * @param url - The URL of the Realtime Database instance to connect to. If not
  13567. * provided, the SDK connects to the default instance of the Firebase App.
  13568. * @returns The `Database` instance of the provided app.
  13569. */
  13570. function getDatabase(app = getApp(), url) {
  13571. const db = _getProvider(app, 'database').getImmediate({
  13572. identifier: url
  13573. });
  13574. if (!db._instanceStarted) {
  13575. const emulator = getDefaultEmulatorHostnameAndPort('database');
  13576. if (emulator) {
  13577. connectDatabaseEmulator(db, ...emulator);
  13578. }
  13579. }
  13580. return db;
  13581. }
  13582. /**
  13583. * Modify the provided instance to communicate with the Realtime Database
  13584. * emulator.
  13585. *
  13586. * <p>Note: This method must be called before performing any other operation.
  13587. *
  13588. * @param db - The instance to modify.
  13589. * @param host - The emulator host (ex: localhost)
  13590. * @param port - The emulator port (ex: 8080)
  13591. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13592. */
  13593. function connectDatabaseEmulator(db, host, port, options = {}) {
  13594. db = getModularInstance(db);
  13595. db._checkNotDeleted('useEmulator');
  13596. if (db._instanceStarted) {
  13597. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13598. }
  13599. const repo = db._repoInternal;
  13600. let tokenProvider = undefined;
  13601. if (repo.repoInfo_.nodeAdmin) {
  13602. if (options.mockUserToken) {
  13603. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13604. }
  13605. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13606. }
  13607. else if (options.mockUserToken) {
  13608. const token = typeof options.mockUserToken === 'string'
  13609. ? options.mockUserToken
  13610. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13611. tokenProvider = new EmulatorTokenProvider(token);
  13612. }
  13613. // Modify the repo to apply emulator settings
  13614. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13615. }
  13616. /**
  13617. * Disconnects from the server (all Database operations will be completed
  13618. * offline).
  13619. *
  13620. * The client automatically maintains a persistent connection to the Database
  13621. * server, which will remain active indefinitely and reconnect when
  13622. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13623. * to control the client connection in cases where a persistent connection is
  13624. * undesirable.
  13625. *
  13626. * While offline, the client will no longer receive data updates from the
  13627. * Database. However, all Database operations performed locally will continue to
  13628. * immediately fire events, allowing your application to continue behaving
  13629. * normally. Additionally, each operation performed locally will automatically
  13630. * be queued and retried upon reconnection to the Database server.
  13631. *
  13632. * To reconnect to the Database and begin receiving remote events, see
  13633. * `goOnline()`.
  13634. *
  13635. * @param db - The instance to disconnect.
  13636. */
  13637. function goOffline(db) {
  13638. db = getModularInstance(db);
  13639. db._checkNotDeleted('goOffline');
  13640. repoInterrupt(db._repo);
  13641. }
  13642. /**
  13643. * Reconnects to the server and synchronizes the offline Database state
  13644. * with the server state.
  13645. *
  13646. * This method should be used after disabling the active connection with
  13647. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13648. * and fire the appropriate events so that your client "catches up"
  13649. * automatically.
  13650. *
  13651. * @param db - The instance to reconnect.
  13652. */
  13653. function goOnline(db) {
  13654. db = getModularInstance(db);
  13655. db._checkNotDeleted('goOnline');
  13656. repoResume(db._repo);
  13657. }
  13658. function enableLogging(logger, persistent) {
  13659. enableLogging$1(logger, persistent);
  13660. }
  13661. /**
  13662. * @license
  13663. * Copyright 2021 Google LLC
  13664. *
  13665. * Licensed under the Apache License, Version 2.0 (the "License");
  13666. * you may not use this file except in compliance with the License.
  13667. * You may obtain a copy of the License at
  13668. *
  13669. * http://www.apache.org/licenses/LICENSE-2.0
  13670. *
  13671. * Unless required by applicable law or agreed to in writing, software
  13672. * distributed under the License is distributed on an "AS IS" BASIS,
  13673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13674. * See the License for the specific language governing permissions and
  13675. * limitations under the License.
  13676. */
  13677. function registerDatabase(variant) {
  13678. setSDKVersion(SDK_VERSION$1);
  13679. _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
  13680. const app = container.getProvider('app').getImmediate();
  13681. const authProvider = container.getProvider('auth-internal');
  13682. const appCheckProvider = container.getProvider('app-check-internal');
  13683. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13684. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13685. registerVersion(name, version, variant);
  13686. // BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
  13687. registerVersion(name, version, 'esm2017');
  13688. }
  13689. /**
  13690. * @license
  13691. * Copyright 2020 Google LLC
  13692. *
  13693. * Licensed under the Apache License, Version 2.0 (the "License");
  13694. * you may not use this file except in compliance with the License.
  13695. * You may obtain a copy of the License at
  13696. *
  13697. * http://www.apache.org/licenses/LICENSE-2.0
  13698. *
  13699. * Unless required by applicable law or agreed to in writing, software
  13700. * distributed under the License is distributed on an "AS IS" BASIS,
  13701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13702. * See the License for the specific language governing permissions and
  13703. * limitations under the License.
  13704. */
  13705. const SERVER_TIMESTAMP = {
  13706. '.sv': 'timestamp'
  13707. };
  13708. /**
  13709. * Returns a placeholder value for auto-populating the current timestamp (time
  13710. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13711. * servers.
  13712. */
  13713. function serverTimestamp() {
  13714. return SERVER_TIMESTAMP;
  13715. }
  13716. /**
  13717. * Returns a placeholder value that can be used to atomically increment the
  13718. * current database value by the provided delta.
  13719. *
  13720. * @param delta - the amount to modify the current value atomically.
  13721. * @returns A placeholder value for modifying data atomically server-side.
  13722. */
  13723. function increment(delta) {
  13724. return {
  13725. '.sv': {
  13726. 'increment': delta
  13727. }
  13728. };
  13729. }
  13730. /**
  13731. * @license
  13732. * Copyright 2020 Google LLC
  13733. *
  13734. * Licensed under the Apache License, Version 2.0 (the "License");
  13735. * you may not use this file except in compliance with the License.
  13736. * You may obtain a copy of the License at
  13737. *
  13738. * http://www.apache.org/licenses/LICENSE-2.0
  13739. *
  13740. * Unless required by applicable law or agreed to in writing, software
  13741. * distributed under the License is distributed on an "AS IS" BASIS,
  13742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13743. * See the License for the specific language governing permissions and
  13744. * limitations under the License.
  13745. */
  13746. /**
  13747. * A type for the resolve value of {@link runTransaction}.
  13748. */
  13749. class TransactionResult {
  13750. /** @hideconstructor */
  13751. constructor(
  13752. /** Whether the transaction was successfully committed. */
  13753. committed,
  13754. /** The resulting data snapshot. */
  13755. snapshot) {
  13756. this.committed = committed;
  13757. this.snapshot = snapshot;
  13758. }
  13759. /** Returns a JSON-serializable representation of this object. */
  13760. toJSON() {
  13761. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13762. }
  13763. }
  13764. /**
  13765. * Atomically modifies the data at this location.
  13766. *
  13767. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13768. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13769. * used to modify the existing value to a new value, ensuring there are no
  13770. * conflicts with other clients writing to the same location at the same time.
  13771. *
  13772. * To accomplish this, you pass `runTransaction()` an update function which is
  13773. * used to transform the current value into a new value. If another client
  13774. * writes to the location before your new value is successfully written, your
  13775. * update function will be called again with the new current value, and the
  13776. * write will be retried. This will happen repeatedly until your write succeeds
  13777. * without conflict or you abort the transaction by not returning a value from
  13778. * your update function.
  13779. *
  13780. * Note: Modifying data with `set()` will cancel any pending transactions at
  13781. * that location, so extreme care should be taken if mixing `set()` and
  13782. * `runTransaction()` to update the same data.
  13783. *
  13784. * Note: When using transactions with Security and Firebase Rules in place, be
  13785. * aware that a client needs `.read` access in addition to `.write` access in
  13786. * order to perform a transaction. This is because the client-side nature of
  13787. * transactions requires the client to read the data in order to transactionally
  13788. * update it.
  13789. *
  13790. * @param ref - The location to atomically modify.
  13791. * @param transactionUpdate - A developer-supplied function which will be passed
  13792. * the current data stored at this location (as a JavaScript object). The
  13793. * function should return the new value it would like written (as a JavaScript
  13794. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13795. * transaction will be aborted and the data at this location will not be
  13796. * modified.
  13797. * @param options - An options object to configure transactions.
  13798. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13799. * callback to handle success and failure.
  13800. */
  13801. function runTransaction(ref,
  13802. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13803. transactionUpdate, options) {
  13804. var _a;
  13805. ref = getModularInstance(ref);
  13806. validateWritablePath('Reference.transaction', ref._path);
  13807. if (ref.key === '.length' || ref.key === '.keys') {
  13808. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13809. }
  13810. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13811. const deferred = new Deferred();
  13812. const promiseComplete = (error, committed, node) => {
  13813. let dataSnapshot = null;
  13814. if (error) {
  13815. deferred.reject(error);
  13816. }
  13817. else {
  13818. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13819. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13820. }
  13821. };
  13822. // Add a watch to make sure we get server updates.
  13823. const unwatcher = onValue(ref, () => { });
  13824. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13825. return deferred.promise;
  13826. }
  13827. /**
  13828. * @license
  13829. * Copyright 2017 Google LLC
  13830. *
  13831. * Licensed under the Apache License, Version 2.0 (the "License");
  13832. * you may not use this file except in compliance with the License.
  13833. * You may obtain a copy of the License at
  13834. *
  13835. * http://www.apache.org/licenses/LICENSE-2.0
  13836. *
  13837. * Unless required by applicable law or agreed to in writing, software
  13838. * distributed under the License is distributed on an "AS IS" BASIS,
  13839. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13840. * See the License for the specific language governing permissions and
  13841. * limitations under the License.
  13842. */
  13843. PersistentConnection;
  13844. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13845. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13846. this.sendRequest('q', { p: pathString }, onComplete);
  13847. };
  13848. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13849. PersistentConnection.prototype.echo = function (data, onEcho) {
  13850. this.sendRequest('echo', { d: data }, onEcho);
  13851. };
  13852. // RealTimeConnection properties that we use in tests.
  13853. Connection;
  13854. /**
  13855. * @internal
  13856. */
  13857. const hijackHash = function (newHash) {
  13858. const oldPut = PersistentConnection.prototype.put;
  13859. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13860. if (hash !== undefined) {
  13861. hash = newHash();
  13862. }
  13863. oldPut.call(this, pathString, data, onComplete, hash);
  13864. };
  13865. return function () {
  13866. PersistentConnection.prototype.put = oldPut;
  13867. };
  13868. };
  13869. RepoInfo;
  13870. /**
  13871. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13872. * @internal
  13873. */
  13874. const forceRestClient = function (forceRestClient) {
  13875. repoManagerForceRestClient(forceRestClient);
  13876. };
  13877. /**
  13878. * @license
  13879. * Copyright 2023 Google LLC
  13880. *
  13881. * Licensed under the Apache License, Version 2.0 (the "License");
  13882. * you may not use this file except in compliance with the License.
  13883. * You may obtain a copy of the License at
  13884. *
  13885. * http://www.apache.org/licenses/LICENSE-2.0
  13886. *
  13887. * Unless required by applicable law or agreed to in writing, software
  13888. * distributed under the License is distributed on an "AS IS" BASIS,
  13889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13890. * See the License for the specific language governing permissions and
  13891. * limitations under the License.
  13892. */
  13893. /**
  13894. * Used by console to create a database based on the app,
  13895. * passed database URL and a custom auth implementation.
  13896. * @internal
  13897. * @param app - A valid FirebaseApp-like object
  13898. * @param url - A valid Firebase databaseURL
  13899. * @param version - custom version e.g. firebase-admin version
  13900. * @param customAppCheckImpl - custom app check implementation
  13901. * @param customAuthImpl - custom auth implementation
  13902. */
  13903. function _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {
  13904. setSDKVersion(version);
  13905. /**
  13906. * ComponentContainer('database-standalone') is just a placeholder that doesn't perform
  13907. * any actual function.
  13908. */
  13909. const componentContainer = new ComponentContainer('database-standalone');
  13910. const authProvider = new Provider('auth-internal', componentContainer);
  13911. let appCheckProvider;
  13912. if (customAppCheckImpl) {
  13913. appCheckProvider = new Provider('app-check-internal', componentContainer);
  13914. appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13915. }
  13916. authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, "PRIVATE" /* ComponentType.PRIVATE */));
  13917. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);
  13918. }
  13919. /**
  13920. * @license
  13921. * Copyright 2021 Google LLC
  13922. *
  13923. * Licensed under the Apache License, Version 2.0 (the "License");
  13924. * you may not use this file except in compliance with the License.
  13925. * You may obtain a copy of the License at
  13926. *
  13927. * http://www.apache.org/licenses/LICENSE-2.0
  13928. *
  13929. * Unless required by applicable law or agreed to in writing, software
  13930. * distributed under the License is distributed on an "AS IS" BASIS,
  13931. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13932. * See the License for the specific language governing permissions and
  13933. * limitations under the License.
  13934. */
  13935. setWebSocketImpl(Websocket.Client);
  13936. registerDatabase('node');
  13937. 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, _initStandalone, 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 };
  13938. //# sourceMappingURL=index.node.esm.js.map