Ingen beskrivning
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.esm5.js 571KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408
  1. import { getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { __spreadArray, __read, __values, __extends, __awaiter, __generator, __assign } from 'tslib';
  4. 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';
  5. import { Logger, LogLevel } from '@firebase/logger';
  6. var name = "@firebase/database";
  7. var version = "0.14.1";
  8. /**
  9. * @license
  10. * Copyright 2019 Google LLC
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. /** The semver (www.semver.org) version of the SDK. */
  25. var SDK_VERSION = '';
  26. /**
  27. * SDK_VERSION should be set before any database instance is created
  28. * @internal
  29. */
  30. function setSDKVersion(version) {
  31. SDK_VERSION = version;
  32. }
  33. /**
  34. * @license
  35. * Copyright 2017 Google LLC
  36. *
  37. * Licensed under the Apache License, Version 2.0 (the "License");
  38. * you may not use this file except in compliance with the License.
  39. * You may obtain a copy of the License at
  40. *
  41. * http://www.apache.org/licenses/LICENSE-2.0
  42. *
  43. * Unless required by applicable law or agreed to in writing, software
  44. * distributed under the License is distributed on an "AS IS" BASIS,
  45. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  46. * See the License for the specific language governing permissions and
  47. * limitations under the License.
  48. */
  49. /**
  50. * Wraps a DOM Storage object and:
  51. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  52. * - prefixes names with "firebase:" to avoid collisions with app data.
  53. *
  54. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  55. * and one for localStorage.
  56. *
  57. */
  58. var DOMStorageWrapper = /** @class */ (function () {
  59. /**
  60. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  61. */
  62. function DOMStorageWrapper(domStorage_) {
  63. this.domStorage_ = domStorage_;
  64. // Use a prefix to avoid collisions with other stuff saved by the app.
  65. this.prefix_ = 'firebase:';
  66. }
  67. /**
  68. * @param key - The key to save the value under
  69. * @param value - The value being stored, or null to remove the key.
  70. */
  71. DOMStorageWrapper.prototype.set = function (key, value) {
  72. if (value == null) {
  73. this.domStorage_.removeItem(this.prefixedName_(key));
  74. }
  75. else {
  76. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  77. }
  78. };
  79. /**
  80. * @returns The value that was stored under this key, or null
  81. */
  82. DOMStorageWrapper.prototype.get = function (key) {
  83. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  84. if (storedVal == null) {
  85. return null;
  86. }
  87. else {
  88. return jsonEval(storedVal);
  89. }
  90. };
  91. DOMStorageWrapper.prototype.remove = function (key) {
  92. this.domStorage_.removeItem(this.prefixedName_(key));
  93. };
  94. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  95. return this.prefix_ + name;
  96. };
  97. DOMStorageWrapper.prototype.toString = function () {
  98. return this.domStorage_.toString();
  99. };
  100. return DOMStorageWrapper;
  101. }());
  102. /**
  103. * @license
  104. * Copyright 2017 Google LLC
  105. *
  106. * Licensed under the Apache License, Version 2.0 (the "License");
  107. * you may not use this file except in compliance with the License.
  108. * You may obtain a copy of the License at
  109. *
  110. * http://www.apache.org/licenses/LICENSE-2.0
  111. *
  112. * Unless required by applicable law or agreed to in writing, software
  113. * distributed under the License is distributed on an "AS IS" BASIS,
  114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  115. * See the License for the specific language governing permissions and
  116. * limitations under the License.
  117. */
  118. /**
  119. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  120. * (TODO: create interface for both to implement).
  121. */
  122. var MemoryStorage = /** @class */ (function () {
  123. function MemoryStorage() {
  124. this.cache_ = {};
  125. this.isInMemoryStorage = true;
  126. }
  127. MemoryStorage.prototype.set = function (key, value) {
  128. if (value == null) {
  129. delete this.cache_[key];
  130. }
  131. else {
  132. this.cache_[key] = value;
  133. }
  134. };
  135. MemoryStorage.prototype.get = function (key) {
  136. if (contains(this.cache_, key)) {
  137. return this.cache_[key];
  138. }
  139. return null;
  140. };
  141. MemoryStorage.prototype.remove = function (key) {
  142. delete this.cache_[key];
  143. };
  144. return MemoryStorage;
  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. var 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. var 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. var PersistentStorage = createStoragefor('localStorage');
  191. /** A storage object that only lasts one session */
  192. var 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. var 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. var LUIDGenerator = (function () {
  214. var 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. var sha1 = function (str) {
  225. var utf8Bytes = stringToByteArray(str);
  226. var sha1 = new Sha1();
  227. sha1.update(utf8Bytes);
  228. var sha1Bytes = sha1.digest();
  229. return base64.encodeByteArray(sha1Bytes);
  230. };
  231. var buildLogMessage_ = function () {
  232. var varArgs = [];
  233. for (var _i = 0; _i < arguments.length; _i++) {
  234. varArgs[_i] = arguments[_i];
  235. }
  236. var message = '';
  237. for (var i = 0; i < varArgs.length; i++) {
  238. var arg = varArgs[i];
  239. if (Array.isArray(arg) ||
  240. (arg &&
  241. typeof arg === 'object' &&
  242. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  243. typeof arg.length === 'number')) {
  244. message += buildLogMessage_.apply(null, arg);
  245. }
  246. else if (typeof arg === 'object') {
  247. message += stringify(arg);
  248. }
  249. else {
  250. message += arg;
  251. }
  252. message += ' ';
  253. }
  254. return message;
  255. };
  256. /**
  257. * Use this for all debug messages in Firebase.
  258. */
  259. var logger = null;
  260. /**
  261. * Flag to check for log availability on first log message
  262. */
  263. var firstLog_ = true;
  264. /**
  265. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  266. * @param logger_ - A flag to turn on logging, or a custom logger
  267. * @param persistent - Whether or not to persist logging settings across refreshes
  268. */
  269. var enableLogging$1 = function (logger_, persistent) {
  270. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  271. if (logger_ === true) {
  272. logClient.logLevel = LogLevel.VERBOSE;
  273. logger = logClient.log.bind(logClient);
  274. if (persistent) {
  275. SessionStorage.set('logging_enabled', true);
  276. }
  277. }
  278. else if (typeof logger_ === 'function') {
  279. logger = logger_;
  280. }
  281. else {
  282. logger = null;
  283. SessionStorage.remove('logging_enabled');
  284. }
  285. };
  286. var log = function () {
  287. var varArgs = [];
  288. for (var _i = 0; _i < arguments.length; _i++) {
  289. varArgs[_i] = arguments[_i];
  290. }
  291. if (firstLog_ === true) {
  292. firstLog_ = false;
  293. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  294. enableLogging$1(true);
  295. }
  296. }
  297. if (logger) {
  298. var message = buildLogMessage_.apply(null, varArgs);
  299. logger(message);
  300. }
  301. };
  302. var logWrapper = function (prefix) {
  303. return function () {
  304. var varArgs = [];
  305. for (var _i = 0; _i < arguments.length; _i++) {
  306. varArgs[_i] = arguments[_i];
  307. }
  308. log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
  309. };
  310. };
  311. var error = function () {
  312. var varArgs = [];
  313. for (var _i = 0; _i < arguments.length; _i++) {
  314. varArgs[_i] = arguments[_i];
  315. }
  316. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
  317. logClient.error(message);
  318. };
  319. var fatal = function () {
  320. var varArgs = [];
  321. for (var _i = 0; _i < arguments.length; _i++) {
  322. varArgs[_i] = arguments[_i];
  323. }
  324. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false)));
  325. logClient.error(message);
  326. throw new Error(message);
  327. };
  328. var warn = function () {
  329. var varArgs = [];
  330. for (var _i = 0; _i < arguments.length; _i++) {
  331. varArgs[_i] = arguments[_i];
  332. }
  333. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, __spreadArray([], __read(varArgs), false));
  334. logClient.warn(message);
  335. };
  336. /**
  337. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  338. * does not use https.
  339. */
  340. var warnIfPageIsSecure = function () {
  341. // Be very careful accessing browser globals. Who knows what may or may not exist.
  342. if (typeof window !== 'undefined' &&
  343. window.location &&
  344. window.location.protocol &&
  345. window.location.protocol.indexOf('https:') !== -1) {
  346. warn('Insecure Firebase access from a secure page. ' +
  347. 'Please use https in calls to new Firebase().');
  348. }
  349. };
  350. /**
  351. * Returns true if data is NaN, or +/- Infinity.
  352. */
  353. var isInvalidJSONNumber = function (data) {
  354. return (typeof data === 'number' &&
  355. (data !== data || // NaN
  356. data === Number.POSITIVE_INFINITY ||
  357. data === Number.NEGATIVE_INFINITY));
  358. };
  359. var executeWhenDOMReady = function (fn) {
  360. if (isNodeSdk() || document.readyState === 'complete') {
  361. fn();
  362. }
  363. else {
  364. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  365. // fire before onload), but fall back to onload.
  366. var called_1 = false;
  367. var wrappedFn_1 = function () {
  368. if (!document.body) {
  369. setTimeout(wrappedFn_1, Math.floor(10));
  370. return;
  371. }
  372. if (!called_1) {
  373. called_1 = true;
  374. fn();
  375. }
  376. };
  377. if (document.addEventListener) {
  378. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  379. // fallback to onload.
  380. window.addEventListener('load', wrappedFn_1, false);
  381. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  382. }
  383. else if (document.attachEvent) {
  384. // IE.
  385. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  386. document.attachEvent('onreadystatechange', function () {
  387. if (document.readyState === 'complete') {
  388. wrappedFn_1();
  389. }
  390. });
  391. // fallback to onload.
  392. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  393. window.attachEvent('onload', wrappedFn_1);
  394. // jQuery has an extra hack for IE that we could employ (based on
  395. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  396. // I'm hoping we don't need it.
  397. }
  398. }
  399. };
  400. /**
  401. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  402. */
  403. var MIN_NAME = '[MIN_NAME]';
  404. /**
  405. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  406. */
  407. var MAX_NAME = '[MAX_NAME]';
  408. /**
  409. * Compares valid Firebase key names, plus min and max name
  410. */
  411. var nameCompare = function (a, b) {
  412. if (a === b) {
  413. return 0;
  414. }
  415. else if (a === MIN_NAME || b === MAX_NAME) {
  416. return -1;
  417. }
  418. else if (b === MIN_NAME || a === MAX_NAME) {
  419. return 1;
  420. }
  421. else {
  422. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  423. if (aAsInt !== null) {
  424. if (bAsInt !== null) {
  425. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  426. }
  427. else {
  428. return -1;
  429. }
  430. }
  431. else if (bAsInt !== null) {
  432. return 1;
  433. }
  434. else {
  435. return a < b ? -1 : 1;
  436. }
  437. }
  438. };
  439. /**
  440. * @returns {!number} comparison result.
  441. */
  442. var stringCompare = function (a, b) {
  443. if (a === b) {
  444. return 0;
  445. }
  446. else if (a < b) {
  447. return -1;
  448. }
  449. else {
  450. return 1;
  451. }
  452. };
  453. var requireKey = function (key, obj) {
  454. if (obj && key in obj) {
  455. return obj[key];
  456. }
  457. else {
  458. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  459. }
  460. };
  461. var ObjectToUniqueKey = function (obj) {
  462. if (typeof obj !== 'object' || obj === null) {
  463. return stringify(obj);
  464. }
  465. var keys = [];
  466. // eslint-disable-next-line guard-for-in
  467. for (var k in obj) {
  468. keys.push(k);
  469. }
  470. // Export as json, but with the keys sorted.
  471. keys.sort();
  472. var key = '{';
  473. for (var i = 0; i < keys.length; i++) {
  474. if (i !== 0) {
  475. key += ',';
  476. }
  477. key += stringify(keys[i]);
  478. key += ':';
  479. key += ObjectToUniqueKey(obj[keys[i]]);
  480. }
  481. key += '}';
  482. return key;
  483. };
  484. /**
  485. * Splits a string into a number of smaller segments of maximum size
  486. * @param str - The string
  487. * @param segsize - The maximum number of chars in the string.
  488. * @returns The string, split into appropriately-sized chunks
  489. */
  490. var splitStringBySize = function (str, segsize) {
  491. var len = str.length;
  492. if (len <= segsize) {
  493. return [str];
  494. }
  495. var dataSegs = [];
  496. for (var c = 0; c < len; c += segsize) {
  497. if (c + segsize > len) {
  498. dataSegs.push(str.substring(c, len));
  499. }
  500. else {
  501. dataSegs.push(str.substring(c, c + segsize));
  502. }
  503. }
  504. return dataSegs;
  505. };
  506. /**
  507. * Apply a function to each (key, value) pair in an object or
  508. * apply a function to each (index, value) pair in an array
  509. * @param obj - The object or array to iterate over
  510. * @param fn - The function to apply
  511. */
  512. function each(obj, fn) {
  513. for (var key in obj) {
  514. if (obj.hasOwnProperty(key)) {
  515. fn(key, obj[key]);
  516. }
  517. }
  518. }
  519. /**
  520. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  521. * I made one modification at the end and removed the NaN / Infinity
  522. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  523. * @param v - A double
  524. *
  525. */
  526. var doubleToIEEE754String = function (v) {
  527. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  528. var ebits = 11, fbits = 52;
  529. var bias = (1 << (ebits - 1)) - 1;
  530. var s, e, f, ln, i;
  531. // Compute sign, exponent, fraction
  532. // Skip NaN / Infinity handling --MJL.
  533. if (v === 0) {
  534. e = 0;
  535. f = 0;
  536. s = 1 / v === -Infinity ? 1 : 0;
  537. }
  538. else {
  539. s = v < 0;
  540. v = Math.abs(v);
  541. if (v >= Math.pow(2, 1 - bias)) {
  542. // Normalized
  543. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  544. e = ln + bias;
  545. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  546. }
  547. else {
  548. // Denormalized
  549. e = 0;
  550. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  551. }
  552. }
  553. // Pack sign, exponent, fraction
  554. var bits = [];
  555. for (i = fbits; i; i -= 1) {
  556. bits.push(f % 2 ? 1 : 0);
  557. f = Math.floor(f / 2);
  558. }
  559. for (i = ebits; i; i -= 1) {
  560. bits.push(e % 2 ? 1 : 0);
  561. e = Math.floor(e / 2);
  562. }
  563. bits.push(s ? 1 : 0);
  564. bits.reverse();
  565. var str = bits.join('');
  566. // Return the data as a hex string. --MJL
  567. var hexByteString = '';
  568. for (i = 0; i < 64; i += 8) {
  569. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  570. if (hexByte.length === 1) {
  571. hexByte = '0' + hexByte;
  572. }
  573. hexByteString = hexByteString + hexByte;
  574. }
  575. return hexByteString.toLowerCase();
  576. };
  577. /**
  578. * Used to detect if we're in a Chrome content script (which executes in an
  579. * isolated environment where long-polling doesn't work).
  580. */
  581. var isChromeExtensionContentScript = function () {
  582. return !!(typeof window === 'object' &&
  583. window['chrome'] &&
  584. window['chrome']['extension'] &&
  585. !/^chrome/.test(window.location.href));
  586. };
  587. /**
  588. * Used to detect if we're in a Windows 8 Store app.
  589. */
  590. var isWindowsStoreApp = function () {
  591. // Check for the presence of a couple WinRT globals
  592. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  593. };
  594. /**
  595. * Converts a server error code to a Javascript Error
  596. */
  597. function errorForServerCode(code, query) {
  598. var reason = 'Unknown Error';
  599. if (code === 'too_big') {
  600. reason =
  601. 'The data requested exceeds the maximum size ' +
  602. 'that can be accessed with a single request.';
  603. }
  604. else if (code === 'permission_denied') {
  605. reason = "Client doesn't have permission to access the desired data.";
  606. }
  607. else if (code === 'unavailable') {
  608. reason = 'The service is unavailable';
  609. }
  610. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  611. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  612. error.code = code.toUpperCase();
  613. return error;
  614. }
  615. /**
  616. * Used to test for integer-looking strings
  617. */
  618. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  619. /**
  620. * For use in keys, the minimum possible 32-bit integer.
  621. */
  622. var INTEGER_32_MIN = -2147483648;
  623. /**
  624. * For use in kyes, the maximum possible 32-bit integer.
  625. */
  626. var INTEGER_32_MAX = 2147483647;
  627. /**
  628. * If the string contains a 32-bit integer, return it. Else return null.
  629. */
  630. var tryParseInt = function (str) {
  631. if (INTEGER_REGEXP_.test(str)) {
  632. var intVal = Number(str);
  633. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  634. return intVal;
  635. }
  636. }
  637. return null;
  638. };
  639. /**
  640. * Helper to run some code but catch any exceptions and re-throw them later.
  641. * Useful for preventing user callbacks from breaking internal code.
  642. *
  643. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  644. * convenient (we don't have to try to figure out when is a safe point to
  645. * re-throw it), and the behavior seems reasonable:
  646. *
  647. * * If you aren't pausing on exceptions, you get an error in the console with
  648. * the correct stack trace.
  649. * * If you're pausing on all exceptions, the debugger will pause on your
  650. * exception and then again when we rethrow it.
  651. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  652. * on us re-throwing it.
  653. *
  654. * @param fn - The code to guard.
  655. */
  656. var exceptionGuard = function (fn) {
  657. try {
  658. fn();
  659. }
  660. catch (e) {
  661. // Re-throw exception when it's safe.
  662. setTimeout(function () {
  663. // It used to be that "throw e" would result in a good console error with
  664. // relevant context, but as of Chrome 39, you just get the firebase.js
  665. // file/line number where we re-throw it, which is useless. So we log
  666. // e.stack explicitly.
  667. var stack = e.stack || '';
  668. warn('Exception was thrown by user callback.', stack);
  669. throw e;
  670. }, Math.floor(0));
  671. }
  672. };
  673. /**
  674. * @returns {boolean} true if we think we're currently being crawled.
  675. */
  676. var beingCrawled = function () {
  677. var userAgent = (typeof window === 'object' &&
  678. window['navigator'] &&
  679. window['navigator']['userAgent']) ||
  680. '';
  681. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  682. // believe to support JavaScript/AJAX rendering.
  683. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  684. // would have seen the page" is flaky if we don't treat it as a crawler.
  685. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  686. };
  687. /**
  688. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  689. *
  690. * It is removed with clearTimeout() as normal.
  691. *
  692. * @param fn - Function to run.
  693. * @param time - Milliseconds to wait before running.
  694. * @returns The setTimeout() return value.
  695. */
  696. var setTimeoutNonBlocking = function (fn, time) {
  697. var timeout = setTimeout(fn, time);
  698. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  699. if (typeof timeout === 'number' &&
  700. // @ts-ignore Is only defined in Deno environments.
  701. typeof Deno !== 'undefined' &&
  702. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  703. Deno['unrefTimer']) {
  704. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  705. Deno.unrefTimer(timeout);
  706. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  707. }
  708. else if (typeof timeout === 'object' && timeout['unref']) {
  709. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  710. timeout['unref']();
  711. }
  712. return timeout;
  713. };
  714. /**
  715. * @license
  716. * Copyright 2021 Google LLC
  717. *
  718. * Licensed under the Apache License, Version 2.0 (the "License");
  719. * you may not use this file except in compliance with the License.
  720. * You may obtain a copy of the License at
  721. *
  722. * http://www.apache.org/licenses/LICENSE-2.0
  723. *
  724. * Unless required by applicable law or agreed to in writing, software
  725. * distributed under the License is distributed on an "AS IS" BASIS,
  726. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  727. * See the License for the specific language governing permissions and
  728. * limitations under the License.
  729. */
  730. /**
  731. * Abstraction around AppCheck's token fetching capabilities.
  732. */
  733. var AppCheckTokenProvider = /** @class */ (function () {
  734. function AppCheckTokenProvider(appName_, appCheckProvider) {
  735. var _this = this;
  736. this.appName_ = appName_;
  737. this.appCheckProvider = appCheckProvider;
  738. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  739. if (!this.appCheck) {
  740. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  741. }
  742. }
  743. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  744. var _this = this;
  745. if (!this.appCheck) {
  746. return new Promise(function (resolve, reject) {
  747. // Support delayed initialization of FirebaseAppCheck. This allows our
  748. // customers to initialize the RTDB SDK before initializing Firebase
  749. // AppCheck and ensures that all requests are authenticated if a token
  750. // becomes available before the timoeout below expires.
  751. setTimeout(function () {
  752. if (_this.appCheck) {
  753. _this.getToken(forceRefresh).then(resolve, reject);
  754. }
  755. else {
  756. resolve(null);
  757. }
  758. }, 0);
  759. });
  760. }
  761. return this.appCheck.getToken(forceRefresh);
  762. };
  763. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  764. var _a;
  765. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  766. };
  767. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  768. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  769. 'are invalid. This usually indicates your app was not initialized correctly.');
  770. };
  771. return AppCheckTokenProvider;
  772. }());
  773. /**
  774. * @license
  775. * Copyright 2017 Google LLC
  776. *
  777. * Licensed under the Apache License, Version 2.0 (the "License");
  778. * you may not use this file except in compliance with the License.
  779. * You may obtain a copy of the License at
  780. *
  781. * http://www.apache.org/licenses/LICENSE-2.0
  782. *
  783. * Unless required by applicable law or agreed to in writing, software
  784. * distributed under the License is distributed on an "AS IS" BASIS,
  785. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  786. * See the License for the specific language governing permissions and
  787. * limitations under the License.
  788. */
  789. /**
  790. * Abstraction around FirebaseApp's token fetching capabilities.
  791. */
  792. var FirebaseAuthTokenProvider = /** @class */ (function () {
  793. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  794. var _this = this;
  795. this.appName_ = appName_;
  796. this.firebaseOptions_ = firebaseOptions_;
  797. this.authProvider_ = authProvider_;
  798. this.auth_ = null;
  799. this.auth_ = authProvider_.getImmediate({ optional: true });
  800. if (!this.auth_) {
  801. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  802. }
  803. }
  804. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  805. var _this = this;
  806. if (!this.auth_) {
  807. return new Promise(function (resolve, reject) {
  808. // Support delayed initialization of FirebaseAuth. This allows our
  809. // customers to initialize the RTDB SDK before initializing Firebase
  810. // Auth and ensures that all requests are authenticated if a token
  811. // becomes available before the timoeout below expires.
  812. setTimeout(function () {
  813. if (_this.auth_) {
  814. _this.getToken(forceRefresh).then(resolve, reject);
  815. }
  816. else {
  817. resolve(null);
  818. }
  819. }, 0);
  820. });
  821. }
  822. return this.auth_.getToken(forceRefresh).catch(function (error) {
  823. // TODO: Need to figure out all the cases this is raised and whether
  824. // this makes sense.
  825. if (error && error.code === 'auth/token-not-initialized') {
  826. log('Got auth/token-not-initialized error. Treating as null token.');
  827. return null;
  828. }
  829. else {
  830. return Promise.reject(error);
  831. }
  832. });
  833. };
  834. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  835. // TODO: We might want to wrap the listener and call it with no args to
  836. // avoid a leaky abstraction, but that makes removing the listener harder.
  837. if (this.auth_) {
  838. this.auth_.addAuthTokenListener(listener);
  839. }
  840. else {
  841. this.authProvider_
  842. .get()
  843. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  844. }
  845. };
  846. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  847. this.authProvider_
  848. .get()
  849. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  850. };
  851. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  852. var errorMessage = 'Provided authentication credentials for the app named "' +
  853. this.appName_ +
  854. '" are invalid. This usually indicates your app was not ' +
  855. 'initialized correctly. ';
  856. if ('credential' in this.firebaseOptions_) {
  857. errorMessage +=
  858. 'Make sure the "credential" property provided to initializeApp() ' +
  859. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  860. 'project.';
  861. }
  862. else if ('serviceAccount' in this.firebaseOptions_) {
  863. errorMessage +=
  864. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  865. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  866. 'project.';
  867. }
  868. else {
  869. errorMessage +=
  870. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  871. 'initializeApp() match the values provided for your app at ' +
  872. 'https://console.firebase.google.com/.';
  873. }
  874. warn(errorMessage);
  875. };
  876. return FirebaseAuthTokenProvider;
  877. }());
  878. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  879. var EmulatorTokenProvider = /** @class */ (function () {
  880. function EmulatorTokenProvider(accessToken) {
  881. this.accessToken = accessToken;
  882. }
  883. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  884. return Promise.resolve({
  885. accessToken: this.accessToken
  886. });
  887. };
  888. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  889. // Invoke the listener immediately to match the behavior in Firebase Auth
  890. // (see packages/auth/src/auth.js#L1807)
  891. listener(this.accessToken);
  892. };
  893. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  894. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  895. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  896. EmulatorTokenProvider.OWNER = 'owner';
  897. return EmulatorTokenProvider;
  898. }());
  899. /**
  900. * @license
  901. * Copyright 2017 Google LLC
  902. *
  903. * Licensed under the Apache License, Version 2.0 (the "License");
  904. * you may not use this file except in compliance with the License.
  905. * You may obtain a copy of the License at
  906. *
  907. * http://www.apache.org/licenses/LICENSE-2.0
  908. *
  909. * Unless required by applicable law or agreed to in writing, software
  910. * distributed under the License is distributed on an "AS IS" BASIS,
  911. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  912. * See the License for the specific language governing permissions and
  913. * limitations under the License.
  914. */
  915. var PROTOCOL_VERSION = '5';
  916. var VERSION_PARAM = 'v';
  917. var TRANSPORT_SESSION_PARAM = 's';
  918. var REFERER_PARAM = 'r';
  919. var FORGE_REF = 'f';
  920. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  921. // firebase.corp.google.com
  922. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  923. var LAST_SESSION_PARAM = 'ls';
  924. var APPLICATION_ID_PARAM = 'p';
  925. var APP_CHECK_TOKEN_PARAM = 'ac';
  926. var WEBSOCKET = 'websocket';
  927. var LONG_POLLING = 'long_polling';
  928. /**
  929. * @license
  930. * Copyright 2017 Google LLC
  931. *
  932. * Licensed under the Apache License, Version 2.0 (the "License");
  933. * you may not use this file except in compliance with the License.
  934. * You may obtain a copy of the License at
  935. *
  936. * http://www.apache.org/licenses/LICENSE-2.0
  937. *
  938. * Unless required by applicable law or agreed to in writing, software
  939. * distributed under the License is distributed on an "AS IS" BASIS,
  940. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  941. * See the License for the specific language governing permissions and
  942. * limitations under the License.
  943. */
  944. /**
  945. * A class that holds metadata about a Repo object
  946. */
  947. var RepoInfo = /** @class */ (function () {
  948. /**
  949. * @param host - Hostname portion of the url for the repo
  950. * @param secure - Whether or not this repo is accessed over ssl
  951. * @param namespace - The namespace represented by the repo
  952. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  953. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  954. * @param persistenceKey - Override the default session persistence storage key
  955. */
  956. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) {
  957. if (nodeAdmin === void 0) { nodeAdmin = false; }
  958. if (persistenceKey === void 0) { persistenceKey = ''; }
  959. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  960. this.secure = secure;
  961. this.namespace = namespace;
  962. this.webSocketOnly = webSocketOnly;
  963. this.nodeAdmin = nodeAdmin;
  964. this.persistenceKey = persistenceKey;
  965. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  966. this._host = host.toLowerCase();
  967. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  968. this.internalHost =
  969. PersistentStorage.get('host:' + host) || this._host;
  970. }
  971. RepoInfo.prototype.isCacheableHost = function () {
  972. return this.internalHost.substr(0, 2) === 's-';
  973. };
  974. RepoInfo.prototype.isCustomHost = function () {
  975. return (this._domain !== 'firebaseio.com' &&
  976. this._domain !== 'firebaseio-demo.com');
  977. };
  978. Object.defineProperty(RepoInfo.prototype, "host", {
  979. get: function () {
  980. return this._host;
  981. },
  982. set: function (newHost) {
  983. if (newHost !== this.internalHost) {
  984. this.internalHost = newHost;
  985. if (this.isCacheableHost()) {
  986. PersistentStorage.set('host:' + this._host, this.internalHost);
  987. }
  988. }
  989. },
  990. enumerable: false,
  991. configurable: true
  992. });
  993. RepoInfo.prototype.toString = function () {
  994. var str = this.toURLString();
  995. if (this.persistenceKey) {
  996. str += '<' + this.persistenceKey + '>';
  997. }
  998. return str;
  999. };
  1000. RepoInfo.prototype.toURLString = function () {
  1001. var protocol = this.secure ? 'https://' : 'http://';
  1002. var query = this.includeNamespaceInQueryParams
  1003. ? "?ns=".concat(this.namespace)
  1004. : '';
  1005. return "".concat(protocol).concat(this.host, "/").concat(query);
  1006. };
  1007. return RepoInfo;
  1008. }());
  1009. function repoInfoNeedsQueryParam(repoInfo) {
  1010. return (repoInfo.host !== repoInfo.internalHost ||
  1011. repoInfo.isCustomHost() ||
  1012. repoInfo.includeNamespaceInQueryParams);
  1013. }
  1014. /**
  1015. * Returns the websocket URL for this repo
  1016. * @param repoInfo - RepoInfo object
  1017. * @param type - of connection
  1018. * @param params - list
  1019. * @returns The URL for this repo
  1020. */
  1021. function repoInfoConnectionURL(repoInfo, type, params) {
  1022. assert(typeof type === 'string', 'typeof type must == string');
  1023. assert(typeof params === 'object', 'typeof params must == object');
  1024. var connURL;
  1025. if (type === WEBSOCKET) {
  1026. connURL =
  1027. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  1028. }
  1029. else if (type === LONG_POLLING) {
  1030. connURL =
  1031. (repoInfo.secure ? 'https://' : 'http://') +
  1032. repoInfo.internalHost +
  1033. '/.lp?';
  1034. }
  1035. else {
  1036. throw new Error('Unknown connection type: ' + type);
  1037. }
  1038. if (repoInfoNeedsQueryParam(repoInfo)) {
  1039. params['ns'] = repoInfo.namespace;
  1040. }
  1041. var pairs = [];
  1042. each(params, function (key, value) {
  1043. pairs.push(key + '=' + value);
  1044. });
  1045. return connURL + pairs.join('&');
  1046. }
  1047. /**
  1048. * @license
  1049. * Copyright 2017 Google LLC
  1050. *
  1051. * Licensed under the Apache License, Version 2.0 (the "License");
  1052. * you may not use this file except in compliance with the License.
  1053. * You may obtain a copy of the License at
  1054. *
  1055. * http://www.apache.org/licenses/LICENSE-2.0
  1056. *
  1057. * Unless required by applicable law or agreed to in writing, software
  1058. * distributed under the License is distributed on an "AS IS" BASIS,
  1059. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1060. * See the License for the specific language governing permissions and
  1061. * limitations under the License.
  1062. */
  1063. /**
  1064. * Tracks a collection of stats.
  1065. */
  1066. var StatsCollection = /** @class */ (function () {
  1067. function StatsCollection() {
  1068. this.counters_ = {};
  1069. }
  1070. StatsCollection.prototype.incrementCounter = function (name, amount) {
  1071. if (amount === void 0) { amount = 1; }
  1072. if (!contains(this.counters_, name)) {
  1073. this.counters_[name] = 0;
  1074. }
  1075. this.counters_[name] += amount;
  1076. };
  1077. StatsCollection.prototype.get = function () {
  1078. return deepCopy(this.counters_);
  1079. };
  1080. return StatsCollection;
  1081. }());
  1082. /**
  1083. * @license
  1084. * Copyright 2017 Google LLC
  1085. *
  1086. * Licensed under the Apache License, Version 2.0 (the "License");
  1087. * you may not use this file except in compliance with the License.
  1088. * You may obtain a copy of the License at
  1089. *
  1090. * http://www.apache.org/licenses/LICENSE-2.0
  1091. *
  1092. * Unless required by applicable law or agreed to in writing, software
  1093. * distributed under the License is distributed on an "AS IS" BASIS,
  1094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1095. * See the License for the specific language governing permissions and
  1096. * limitations under the License.
  1097. */
  1098. var collections = {};
  1099. var reporters = {};
  1100. function statsManagerGetCollection(repoInfo) {
  1101. var hashString = repoInfo.toString();
  1102. if (!collections[hashString]) {
  1103. collections[hashString] = new StatsCollection();
  1104. }
  1105. return collections[hashString];
  1106. }
  1107. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  1108. var hashString = repoInfo.toString();
  1109. if (!reporters[hashString]) {
  1110. reporters[hashString] = creatorFunction();
  1111. }
  1112. return reporters[hashString];
  1113. }
  1114. /**
  1115. * @license
  1116. * Copyright 2017 Google LLC
  1117. *
  1118. * Licensed under the Apache License, Version 2.0 (the "License");
  1119. * you may not use this file except in compliance with the License.
  1120. * You may obtain a copy of the License at
  1121. *
  1122. * http://www.apache.org/licenses/LICENSE-2.0
  1123. *
  1124. * Unless required by applicable law or agreed to in writing, software
  1125. * distributed under the License is distributed on an "AS IS" BASIS,
  1126. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1127. * See the License for the specific language governing permissions and
  1128. * limitations under the License.
  1129. */
  1130. /**
  1131. * This class ensures the packets from the server arrive in order
  1132. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1133. */
  1134. var PacketReceiver = /** @class */ (function () {
  1135. /**
  1136. * @param onMessage_
  1137. */
  1138. function PacketReceiver(onMessage_) {
  1139. this.onMessage_ = onMessage_;
  1140. this.pendingResponses = [];
  1141. this.currentResponseNum = 0;
  1142. this.closeAfterResponse = -1;
  1143. this.onClose = null;
  1144. }
  1145. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1146. this.closeAfterResponse = responseNum;
  1147. this.onClose = callback;
  1148. if (this.closeAfterResponse < this.currentResponseNum) {
  1149. this.onClose();
  1150. this.onClose = null;
  1151. }
  1152. };
  1153. /**
  1154. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1155. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1156. * browsers will respond in the same order as the requests we sent
  1157. */
  1158. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1159. var _this = this;
  1160. this.pendingResponses[requestNum] = data;
  1161. var _loop_1 = function () {
  1162. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1163. delete this_1.pendingResponses[this_1.currentResponseNum];
  1164. var _loop_2 = function (i) {
  1165. if (toProcess[i]) {
  1166. exceptionGuard(function () {
  1167. _this.onMessage_(toProcess[i]);
  1168. });
  1169. }
  1170. };
  1171. for (var i = 0; i < toProcess.length; ++i) {
  1172. _loop_2(i);
  1173. }
  1174. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1175. if (this_1.onClose) {
  1176. this_1.onClose();
  1177. this_1.onClose = null;
  1178. }
  1179. return "break";
  1180. }
  1181. this_1.currentResponseNum++;
  1182. };
  1183. var this_1 = this;
  1184. while (this.pendingResponses[this.currentResponseNum]) {
  1185. var state_1 = _loop_1();
  1186. if (state_1 === "break")
  1187. break;
  1188. }
  1189. };
  1190. return PacketReceiver;
  1191. }());
  1192. /**
  1193. * @license
  1194. * Copyright 2017 Google LLC
  1195. *
  1196. * Licensed under the Apache License, Version 2.0 (the "License");
  1197. * you may not use this file except in compliance with the License.
  1198. * You may obtain a copy of the License at
  1199. *
  1200. * http://www.apache.org/licenses/LICENSE-2.0
  1201. *
  1202. * Unless required by applicable law or agreed to in writing, software
  1203. * distributed under the License is distributed on an "AS IS" BASIS,
  1204. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1205. * See the License for the specific language governing permissions and
  1206. * limitations under the License.
  1207. */
  1208. // URL query parameters associated with longpolling
  1209. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1210. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1211. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1212. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1213. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1214. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1215. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1216. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1217. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1218. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1219. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1220. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1221. //Data size constants.
  1222. //TODO: Perf: the maximum length actually differs from browser to browser.
  1223. // We should check what browser we're on and set accordingly.
  1224. var MAX_URL_DATA_SIZE = 1870;
  1225. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1226. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1227. /**
  1228. * Keepalive period
  1229. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1230. * length of 30 seconds that we can't exceed.
  1231. */
  1232. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1233. /**
  1234. * How long to wait before aborting a long-polling connection attempt.
  1235. */
  1236. var LP_CONNECT_TIMEOUT = 30000;
  1237. /**
  1238. * This class manages a single long-polling connection.
  1239. */
  1240. var BrowserPollConnection = /** @class */ (function () {
  1241. /**
  1242. * @param connId An identifier for this connection, used for logging
  1243. * @param repoInfo The info for the endpoint to send data to.
  1244. * @param applicationId The Firebase App ID for this project.
  1245. * @param appCheckToken The AppCheck token for this client.
  1246. * @param authToken The AuthToken to use for this connection.
  1247. * @param transportSessionId Optional transportSessionid if we are
  1248. * reconnecting for an existing transport session
  1249. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1250. * already created a connection previously
  1251. */
  1252. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1253. var _this = this;
  1254. this.connId = connId;
  1255. this.repoInfo = repoInfo;
  1256. this.applicationId = applicationId;
  1257. this.appCheckToken = appCheckToken;
  1258. this.authToken = authToken;
  1259. this.transportSessionId = transportSessionId;
  1260. this.lastSessionId = lastSessionId;
  1261. this.bytesSent = 0;
  1262. this.bytesReceived = 0;
  1263. this.everConnected_ = false;
  1264. this.log_ = logWrapper(connId);
  1265. this.stats_ = statsManagerGetCollection(repoInfo);
  1266. this.urlFn = function (params) {
  1267. // Always add the token if we have one.
  1268. if (_this.appCheckToken) {
  1269. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1270. }
  1271. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1272. };
  1273. }
  1274. /**
  1275. * @param onMessage - Callback when messages arrive
  1276. * @param onDisconnect - Callback with connection lost.
  1277. */
  1278. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1279. var _this = this;
  1280. this.curSegmentNum = 0;
  1281. this.onDisconnect_ = onDisconnect;
  1282. this.myPacketOrderer = new PacketReceiver(onMessage);
  1283. this.isClosed_ = false;
  1284. this.connectTimeoutTimer_ = setTimeout(function () {
  1285. _this.log_('Timed out trying to connect.');
  1286. // Make sure we clear the host cache
  1287. _this.onClosed_();
  1288. _this.connectTimeoutTimer_ = null;
  1289. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1290. }, Math.floor(LP_CONNECT_TIMEOUT));
  1291. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1292. executeWhenDOMReady(function () {
  1293. if (_this.isClosed_) {
  1294. return;
  1295. }
  1296. //Set up a callback that gets triggered once a connection is set up.
  1297. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1298. var args = [];
  1299. for (var _i = 0; _i < arguments.length; _i++) {
  1300. args[_i] = arguments[_i];
  1301. }
  1302. var _a = __read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1303. _this.incrementIncomingBytes_(args);
  1304. if (!_this.scriptTagHolder) {
  1305. return; // we closed the connection.
  1306. }
  1307. if (_this.connectTimeoutTimer_) {
  1308. clearTimeout(_this.connectTimeoutTimer_);
  1309. _this.connectTimeoutTimer_ = null;
  1310. }
  1311. _this.everConnected_ = true;
  1312. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1313. _this.id = arg1;
  1314. _this.password = arg2;
  1315. }
  1316. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1317. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1318. if (arg1) {
  1319. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1320. // through our already open polls), so don't send any more.
  1321. _this.scriptTagHolder.sendNewPolls = false;
  1322. // arg1 in this case is the last response number sent by the server. We should try to receive
  1323. // all of the responses up to this one before closing
  1324. _this.myPacketOrderer.closeAfter(arg1, function () {
  1325. _this.onClosed_();
  1326. });
  1327. }
  1328. else {
  1329. _this.onClosed_();
  1330. }
  1331. }
  1332. else {
  1333. throw new Error('Unrecognized command received: ' + command);
  1334. }
  1335. }, function () {
  1336. var args = [];
  1337. for (var _i = 0; _i < arguments.length; _i++) {
  1338. args[_i] = arguments[_i];
  1339. }
  1340. var _a = __read(args, 2), pN = _a[0], data = _a[1];
  1341. _this.incrementIncomingBytes_(args);
  1342. _this.myPacketOrderer.handleResponse(pN, data);
  1343. }, function () {
  1344. _this.onClosed_();
  1345. }, _this.urlFn);
  1346. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1347. //from cache.
  1348. var urlParams = {};
  1349. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1350. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1351. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1352. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1353. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1354. }
  1355. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1356. if (_this.transportSessionId) {
  1357. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1358. }
  1359. if (_this.lastSessionId) {
  1360. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1361. }
  1362. if (_this.applicationId) {
  1363. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1364. }
  1365. if (_this.appCheckToken) {
  1366. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1367. }
  1368. if (typeof location !== 'undefined' &&
  1369. location.hostname &&
  1370. FORGE_DOMAIN_RE.test(location.hostname)) {
  1371. urlParams[REFERER_PARAM] = FORGE_REF;
  1372. }
  1373. var connectURL = _this.urlFn(urlParams);
  1374. _this.log_('Connecting via long-poll to ' + connectURL);
  1375. _this.scriptTagHolder.addTag(connectURL, function () {
  1376. /* do nothing */
  1377. });
  1378. });
  1379. };
  1380. /**
  1381. * Call this when a handshake has completed successfully and we want to consider the connection established
  1382. */
  1383. BrowserPollConnection.prototype.start = function () {
  1384. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1385. this.addDisconnectPingFrame(this.id, this.password);
  1386. };
  1387. /**
  1388. * Forces long polling to be considered as a potential transport
  1389. */
  1390. BrowserPollConnection.forceAllow = function () {
  1391. BrowserPollConnection.forceAllow_ = true;
  1392. };
  1393. /**
  1394. * Forces longpolling to not be considered as a potential transport
  1395. */
  1396. BrowserPollConnection.forceDisallow = function () {
  1397. BrowserPollConnection.forceDisallow_ = true;
  1398. };
  1399. // Static method, use string literal so it can be accessed in a generic way
  1400. BrowserPollConnection.isAvailable = function () {
  1401. if (isNodeSdk()) {
  1402. return false;
  1403. }
  1404. else if (BrowserPollConnection.forceAllow_) {
  1405. return true;
  1406. }
  1407. else {
  1408. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1409. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1410. return (!BrowserPollConnection.forceDisallow_ &&
  1411. typeof document !== 'undefined' &&
  1412. document.createElement != null &&
  1413. !isChromeExtensionContentScript() &&
  1414. !isWindowsStoreApp());
  1415. }
  1416. };
  1417. /**
  1418. * No-op for polling
  1419. */
  1420. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1421. /**
  1422. * Stops polling and cleans up the iframe
  1423. */
  1424. BrowserPollConnection.prototype.shutdown_ = function () {
  1425. this.isClosed_ = true;
  1426. if (this.scriptTagHolder) {
  1427. this.scriptTagHolder.close();
  1428. this.scriptTagHolder = null;
  1429. }
  1430. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1431. if (this.myDisconnFrame) {
  1432. document.body.removeChild(this.myDisconnFrame);
  1433. this.myDisconnFrame = null;
  1434. }
  1435. if (this.connectTimeoutTimer_) {
  1436. clearTimeout(this.connectTimeoutTimer_);
  1437. this.connectTimeoutTimer_ = null;
  1438. }
  1439. };
  1440. /**
  1441. * Triggered when this transport is closed
  1442. */
  1443. BrowserPollConnection.prototype.onClosed_ = function () {
  1444. if (!this.isClosed_) {
  1445. this.log_('Longpoll is closing itself');
  1446. this.shutdown_();
  1447. if (this.onDisconnect_) {
  1448. this.onDisconnect_(this.everConnected_);
  1449. this.onDisconnect_ = null;
  1450. }
  1451. }
  1452. };
  1453. /**
  1454. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1455. * that we've left.
  1456. */
  1457. BrowserPollConnection.prototype.close = function () {
  1458. if (!this.isClosed_) {
  1459. this.log_('Longpoll is being closed.');
  1460. this.shutdown_();
  1461. }
  1462. };
  1463. /**
  1464. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1465. * broken into chunks (since URLs have a small maximum length).
  1466. * @param data - The JSON data to transmit.
  1467. */
  1468. BrowserPollConnection.prototype.send = function (data) {
  1469. var dataStr = stringify(data);
  1470. this.bytesSent += dataStr.length;
  1471. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1472. //first, lets get the base64-encoded data
  1473. var base64data = base64Encode(dataStr);
  1474. //We can only fit a certain amount in each URL, so we need to split this request
  1475. //up into multiple pieces if it doesn't fit in one request.
  1476. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1477. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1478. //of segments so that we can reassemble the packet on the server.
  1479. for (var i = 0; i < dataSegs.length; i++) {
  1480. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1481. this.curSegmentNum++;
  1482. }
  1483. };
  1484. /**
  1485. * This is how we notify the server that we're leaving.
  1486. * We aren't able to send requests with DHTML on a window close event, but we can
  1487. * trigger XHR requests in some browsers (everything but Opera basically).
  1488. */
  1489. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1490. if (isNodeSdk()) {
  1491. return;
  1492. }
  1493. this.myDisconnFrame = document.createElement('iframe');
  1494. var urlParams = {};
  1495. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1496. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1497. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1498. this.myDisconnFrame.src = this.urlFn(urlParams);
  1499. this.myDisconnFrame.style.display = 'none';
  1500. document.body.appendChild(this.myDisconnFrame);
  1501. };
  1502. /**
  1503. * Used to track the bytes received by this client
  1504. */
  1505. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1506. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1507. var bytesReceived = stringify(args).length;
  1508. this.bytesReceived += bytesReceived;
  1509. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1510. };
  1511. return BrowserPollConnection;
  1512. }());
  1513. /*********************************************************************************************
  1514. * A wrapper around an iframe that is used as a long-polling script holder.
  1515. *********************************************************************************************/
  1516. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1517. /**
  1518. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1519. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1520. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1521. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1522. */
  1523. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1524. this.onDisconnect = onDisconnect;
  1525. this.urlFn = urlFn;
  1526. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1527. //problems in some browsers.
  1528. this.outstandingRequests = new Set();
  1529. //A queue of the pending segments waiting for transmission to the server.
  1530. this.pendingSegs = [];
  1531. //A serial number. We use this for two things:
  1532. // 1) A way to ensure the browser doesn't cache responses to polls
  1533. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1534. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1535. // JSONP code in the order it was added to the iframe.
  1536. this.currentSerial = Math.floor(Math.random() * 100000000);
  1537. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1538. // incoming data from the server that we're waiting for).
  1539. this.sendNewPolls = true;
  1540. if (!isNodeSdk()) {
  1541. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1542. //iframes where we put the long-polling script tags. We have two callbacks:
  1543. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1544. // 2) Message Callback - Triggered when new data arrives.
  1545. this.uniqueCallbackIdentifier = LUIDGenerator();
  1546. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1547. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1548. onMessageCB;
  1549. //Create an iframe for us to add script tags to.
  1550. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1551. // Set the iframe's contents.
  1552. var script = '';
  1553. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1554. // for ie9, but ie8 needs to do it again in the document itself.
  1555. if (this.myIFrame.src &&
  1556. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1557. var currentDomain = document.domain;
  1558. script = '<script>document.domain="' + currentDomain + '";</script>';
  1559. }
  1560. var iframeContents = '<html><body>' + script + '</body></html>';
  1561. try {
  1562. this.myIFrame.doc.open();
  1563. this.myIFrame.doc.write(iframeContents);
  1564. this.myIFrame.doc.close();
  1565. }
  1566. catch (e) {
  1567. log('frame writing exception');
  1568. if (e.stack) {
  1569. log(e.stack);
  1570. }
  1571. log(e);
  1572. }
  1573. }
  1574. else {
  1575. this.commandCB = commandCB;
  1576. this.onMessageCB = onMessageCB;
  1577. }
  1578. }
  1579. /**
  1580. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1581. * actually use.
  1582. */
  1583. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1584. var iframe = document.createElement('iframe');
  1585. iframe.style.display = 'none';
  1586. // This is necessary in order to initialize the document inside the iframe
  1587. if (document.body) {
  1588. document.body.appendChild(iframe);
  1589. try {
  1590. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1591. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1592. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1593. var a = iframe.contentWindow.document;
  1594. if (!a) {
  1595. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1596. log('No IE domain setting required');
  1597. }
  1598. }
  1599. catch (e) {
  1600. var domain = document.domain;
  1601. iframe.src =
  1602. "javascript:void((function(){document.open();document.domain='" +
  1603. domain +
  1604. "';document.close();})())";
  1605. }
  1606. }
  1607. else {
  1608. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1609. // never gets hit.
  1610. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1611. }
  1612. // Get the document of the iframe in a browser-specific way.
  1613. if (iframe.contentDocument) {
  1614. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1615. }
  1616. else if (iframe.contentWindow) {
  1617. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1618. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1619. }
  1620. else if (iframe.document) {
  1621. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1622. iframe.doc = iframe.document; //others?
  1623. }
  1624. return iframe;
  1625. };
  1626. /**
  1627. * Cancel all outstanding queries and remove the frame.
  1628. */
  1629. FirebaseIFrameScriptHolder.prototype.close = function () {
  1630. var _this = this;
  1631. //Mark this iframe as dead, so no new requests are sent.
  1632. this.alive = false;
  1633. if (this.myIFrame) {
  1634. //We have to actually remove all of the html inside this iframe before removing it from the
  1635. //window, or IE will continue loading and executing the script tags we've already added, which
  1636. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1637. this.myIFrame.doc.body.textContent = '';
  1638. setTimeout(function () {
  1639. if (_this.myIFrame !== null) {
  1640. document.body.removeChild(_this.myIFrame);
  1641. _this.myIFrame = null;
  1642. }
  1643. }, Math.floor(0));
  1644. }
  1645. // Protect from being called recursively.
  1646. var onDisconnect = this.onDisconnect;
  1647. if (onDisconnect) {
  1648. this.onDisconnect = null;
  1649. onDisconnect();
  1650. }
  1651. };
  1652. /**
  1653. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1654. * @param id - The ID of this connection
  1655. * @param pw - The password for this connection
  1656. */
  1657. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  1658. this.myID = id;
  1659. this.myPW = pw;
  1660. this.alive = true;
  1661. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1662. while (this.newRequest_()) { }
  1663. };
  1664. /**
  1665. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1666. * too many outstanding requests and we are still alive.
  1667. *
  1668. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1669. * needed.
  1670. */
  1671. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  1672. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1673. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1674. // close the old request.
  1675. if (this.alive &&
  1676. this.sendNewPolls &&
  1677. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1678. //construct our url
  1679. this.currentSerial++;
  1680. var urlParams = {};
  1681. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1682. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1683. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1684. var theURL = this.urlFn(urlParams);
  1685. //Now add as much data as we can.
  1686. var curDataString = '';
  1687. var i = 0;
  1688. while (this.pendingSegs.length > 0) {
  1689. //first, lets see if the next segment will fit.
  1690. var nextSeg = this.pendingSegs[0];
  1691. if (nextSeg.d.length +
  1692. SEG_HEADER_SIZE +
  1693. curDataString.length <=
  1694. MAX_URL_DATA_SIZE) {
  1695. //great, the segment will fit. Lets append it.
  1696. var theSeg = this.pendingSegs.shift();
  1697. curDataString =
  1698. curDataString +
  1699. '&' +
  1700. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1701. i +
  1702. '=' +
  1703. theSeg.seg +
  1704. '&' +
  1705. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1706. i +
  1707. '=' +
  1708. theSeg.ts +
  1709. '&' +
  1710. FIREBASE_LONGPOLL_DATA_PARAM +
  1711. i +
  1712. '=' +
  1713. theSeg.d;
  1714. i++;
  1715. }
  1716. else {
  1717. break;
  1718. }
  1719. }
  1720. theURL = theURL + curDataString;
  1721. this.addLongPollTag_(theURL, this.currentSerial);
  1722. return true;
  1723. }
  1724. else {
  1725. return false;
  1726. }
  1727. };
  1728. /**
  1729. * Queue a packet for transmission to the server.
  1730. * @param segnum - A sequential id for this packet segment used for reassembly
  1731. * @param totalsegs - The total number of segments in this packet
  1732. * @param data - The data for this segment.
  1733. */
  1734. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  1735. //add this to the queue of segments to send.
  1736. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  1737. //send the data immediately if there isn't already data being transmitted, unless
  1738. //startLongPoll hasn't been called yet.
  1739. if (this.alive) {
  1740. this.newRequest_();
  1741. }
  1742. };
  1743. /**
  1744. * Add a script tag for a regular long-poll request.
  1745. * @param url - The URL of the script tag.
  1746. * @param serial - The serial number of the request.
  1747. */
  1748. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  1749. var _this = this;
  1750. //remember that we sent this request.
  1751. this.outstandingRequests.add(serial);
  1752. var doNewRequest = function () {
  1753. _this.outstandingRequests.delete(serial);
  1754. _this.newRequest_();
  1755. };
  1756. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  1757. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  1758. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  1759. var readyStateCB = function () {
  1760. // Request completed. Cancel the keepalive.
  1761. clearTimeout(keepaliveTimeout);
  1762. // Trigger a new request so we can continue receiving data.
  1763. doNewRequest();
  1764. };
  1765. this.addTag(url, readyStateCB);
  1766. };
  1767. /**
  1768. * Add an arbitrary script tag to the iframe.
  1769. * @param url - The URL for the script tag source.
  1770. * @param loadCB - A callback to be triggered once the script has loaded.
  1771. */
  1772. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  1773. var _this = this;
  1774. if (isNodeSdk()) {
  1775. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1776. this.doNodeLongPoll(url, loadCB);
  1777. }
  1778. else {
  1779. setTimeout(function () {
  1780. try {
  1781. // if we're already closed, don't add this poll
  1782. if (!_this.sendNewPolls) {
  1783. return;
  1784. }
  1785. var newScript_1 = _this.myIFrame.doc.createElement('script');
  1786. newScript_1.type = 'text/javascript';
  1787. newScript_1.async = true;
  1788. newScript_1.src = url;
  1789. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1790. newScript_1.onload = newScript_1.onreadystatechange =
  1791. function () {
  1792. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1793. var rstate = newScript_1.readyState;
  1794. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  1795. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1796. newScript_1.onload = newScript_1.onreadystatechange = null;
  1797. if (newScript_1.parentNode) {
  1798. newScript_1.parentNode.removeChild(newScript_1);
  1799. }
  1800. loadCB();
  1801. }
  1802. };
  1803. newScript_1.onerror = function () {
  1804. log('Long-poll script failed to load: ' + url);
  1805. _this.sendNewPolls = false;
  1806. _this.close();
  1807. };
  1808. _this.myIFrame.doc.body.appendChild(newScript_1);
  1809. }
  1810. catch (e) {
  1811. // TODO: we should make this error visible somehow
  1812. }
  1813. }, Math.floor(1));
  1814. }
  1815. };
  1816. return FirebaseIFrameScriptHolder;
  1817. }());
  1818. /**
  1819. * @license
  1820. * Copyright 2017 Google LLC
  1821. *
  1822. * Licensed under the Apache License, Version 2.0 (the "License");
  1823. * you may not use this file except in compliance with the License.
  1824. * You may obtain a copy of the License at
  1825. *
  1826. * http://www.apache.org/licenses/LICENSE-2.0
  1827. *
  1828. * Unless required by applicable law or agreed to in writing, software
  1829. * distributed under the License is distributed on an "AS IS" BASIS,
  1830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1831. * See the License for the specific language governing permissions and
  1832. * limitations under the License.
  1833. */
  1834. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  1835. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  1836. var WebSocketImpl = null;
  1837. if (typeof MozWebSocket !== 'undefined') {
  1838. WebSocketImpl = MozWebSocket;
  1839. }
  1840. else if (typeof WebSocket !== 'undefined') {
  1841. WebSocketImpl = WebSocket;
  1842. }
  1843. /**
  1844. * Create a new websocket connection with the given callbacks.
  1845. */
  1846. var WebSocketConnection = /** @class */ (function () {
  1847. /**
  1848. * @param connId identifier for this transport
  1849. * @param repoInfo The info for the websocket endpoint.
  1850. * @param applicationId The Firebase App ID for this project.
  1851. * @param appCheckToken The App Check Token for this client.
  1852. * @param authToken The Auth Token for this client.
  1853. * @param transportSessionId Optional transportSessionId if this is connecting
  1854. * to an existing transport session
  1855. * @param lastSessionId Optional lastSessionId if there was a previous
  1856. * connection
  1857. */
  1858. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1859. this.connId = connId;
  1860. this.applicationId = applicationId;
  1861. this.appCheckToken = appCheckToken;
  1862. this.authToken = authToken;
  1863. this.keepaliveTimer = null;
  1864. this.frames = null;
  1865. this.totalFrames = 0;
  1866. this.bytesSent = 0;
  1867. this.bytesReceived = 0;
  1868. this.log_ = logWrapper(this.connId);
  1869. this.stats_ = statsManagerGetCollection(repoInfo);
  1870. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  1871. this.nodeAdmin = repoInfo.nodeAdmin;
  1872. }
  1873. /**
  1874. * @param repoInfo - The info for the websocket endpoint.
  1875. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  1876. * session
  1877. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  1878. * @returns connection url
  1879. */
  1880. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  1881. var urlParams = {};
  1882. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1883. if (!isNodeSdk() &&
  1884. typeof location !== 'undefined' &&
  1885. location.hostname &&
  1886. FORGE_DOMAIN_RE.test(location.hostname)) {
  1887. urlParams[REFERER_PARAM] = FORGE_REF;
  1888. }
  1889. if (transportSessionId) {
  1890. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1891. }
  1892. if (lastSessionId) {
  1893. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1894. }
  1895. if (appCheckToken) {
  1896. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1897. }
  1898. if (applicationId) {
  1899. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1900. }
  1901. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1902. };
  1903. /**
  1904. * @param onMessage - Callback when messages arrive
  1905. * @param onDisconnect - Callback with connection lost.
  1906. */
  1907. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1908. var _this = this;
  1909. this.onDisconnect = onDisconnect;
  1910. this.onMessage = onMessage;
  1911. this.log_('Websocket connecting to ' + this.connURL);
  1912. this.everConnected_ = false;
  1913. // Assume failure until proven otherwise.
  1914. PersistentStorage.set('previous_websocket_failure', true);
  1915. try {
  1916. var options = void 0;
  1917. if (isNodeSdk()) {
  1918. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1919. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1920. options = {
  1921. headers: {
  1922. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1923. 'X-Firebase-GMPID': this.applicationId || ''
  1924. }
  1925. };
  1926. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1927. // Note that we send the credentials here even if they aren't admin credentials, which is
  1928. // not a problem.
  1929. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1930. // through the websocket connection once it is established.
  1931. if (this.authToken) {
  1932. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1933. }
  1934. if (this.appCheckToken) {
  1935. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1936. }
  1937. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1938. var env = process['env'];
  1939. var proxy = this.connURL.indexOf('wss://') === 0
  1940. ? env['HTTPS_PROXY'] || env['https_proxy']
  1941. : env['HTTP_PROXY'] || env['http_proxy'];
  1942. if (proxy) {
  1943. options['proxy'] = { origin: proxy };
  1944. }
  1945. }
  1946. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1947. }
  1948. catch (e) {
  1949. this.log_('Error instantiating WebSocket.');
  1950. var error = e.message || e.data;
  1951. if (error) {
  1952. this.log_(error);
  1953. }
  1954. this.onClosed_();
  1955. return;
  1956. }
  1957. this.mySock.onopen = function () {
  1958. _this.log_('Websocket connected.');
  1959. _this.everConnected_ = true;
  1960. };
  1961. this.mySock.onclose = function () {
  1962. _this.log_('Websocket connection was disconnected.');
  1963. _this.mySock = null;
  1964. _this.onClosed_();
  1965. };
  1966. this.mySock.onmessage = function (m) {
  1967. _this.handleIncomingFrame(m);
  1968. };
  1969. this.mySock.onerror = function (e) {
  1970. _this.log_('WebSocket error. Closing connection.');
  1971. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1972. var error = e.message || e.data;
  1973. if (error) {
  1974. _this.log_(error);
  1975. }
  1976. _this.onClosed_();
  1977. };
  1978. };
  1979. /**
  1980. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1981. */
  1982. WebSocketConnection.prototype.start = function () { };
  1983. WebSocketConnection.forceDisallow = function () {
  1984. WebSocketConnection.forceDisallow_ = true;
  1985. };
  1986. WebSocketConnection.isAvailable = function () {
  1987. var isOldAndroid = false;
  1988. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1989. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1990. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1991. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1992. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1993. isOldAndroid = true;
  1994. }
  1995. }
  1996. }
  1997. return (!isOldAndroid &&
  1998. WebSocketImpl !== null &&
  1999. !WebSocketConnection.forceDisallow_);
  2000. };
  2001. /**
  2002. * Returns true if we previously failed to connect with this transport.
  2003. */
  2004. WebSocketConnection.previouslyFailed = function () {
  2005. // If our persistent storage is actually only in-memory storage,
  2006. // we default to assuming that it previously failed to be safe.
  2007. return (PersistentStorage.isInMemoryStorage ||
  2008. PersistentStorage.get('previous_websocket_failure') === true);
  2009. };
  2010. WebSocketConnection.prototype.markConnectionHealthy = function () {
  2011. PersistentStorage.remove('previous_websocket_failure');
  2012. };
  2013. WebSocketConnection.prototype.appendFrame_ = function (data) {
  2014. this.frames.push(data);
  2015. if (this.frames.length === this.totalFrames) {
  2016. var fullMess = this.frames.join('');
  2017. this.frames = null;
  2018. var jsonMess = jsonEval(fullMess);
  2019. //handle the message
  2020. this.onMessage(jsonMess);
  2021. }
  2022. };
  2023. /**
  2024. * @param frameCount - The number of frames we are expecting from the server
  2025. */
  2026. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  2027. this.totalFrames = frameCount;
  2028. this.frames = [];
  2029. };
  2030. /**
  2031. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  2032. * @returns Any remaining data to be process, or null if there is none
  2033. */
  2034. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  2035. assert(this.frames === null, 'We already have a frame buffer');
  2036. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  2037. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  2038. if (data.length <= 6) {
  2039. var frameCount = Number(data);
  2040. if (!isNaN(frameCount)) {
  2041. this.handleNewFrameCount_(frameCount);
  2042. return null;
  2043. }
  2044. }
  2045. this.handleNewFrameCount_(1);
  2046. return data;
  2047. };
  2048. /**
  2049. * Process a websocket frame that has arrived from the server.
  2050. * @param mess - The frame data
  2051. */
  2052. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  2053. if (this.mySock === null) {
  2054. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  2055. }
  2056. var data = mess['data'];
  2057. this.bytesReceived += data.length;
  2058. this.stats_.incrementCounter('bytes_received', data.length);
  2059. this.resetKeepAlive();
  2060. if (this.frames !== null) {
  2061. // we're buffering
  2062. this.appendFrame_(data);
  2063. }
  2064. else {
  2065. // try to parse out a frame count, otherwise, assume 1 and process it
  2066. var remainingData = this.extractFrameCount_(data);
  2067. if (remainingData !== null) {
  2068. this.appendFrame_(remainingData);
  2069. }
  2070. }
  2071. };
  2072. /**
  2073. * Send a message to the server
  2074. * @param data - The JSON object to transmit
  2075. */
  2076. WebSocketConnection.prototype.send = function (data) {
  2077. this.resetKeepAlive();
  2078. var dataStr = stringify(data);
  2079. this.bytesSent += dataStr.length;
  2080. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  2081. //We can only fit a certain amount in each websocket frame, so we need to split this request
  2082. //up into multiple pieces if it doesn't fit in one request.
  2083. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  2084. //Send the length header
  2085. if (dataSegs.length > 1) {
  2086. this.sendString_(String(dataSegs.length));
  2087. }
  2088. //Send the actual data in segments.
  2089. for (var i = 0; i < dataSegs.length; i++) {
  2090. this.sendString_(dataSegs[i]);
  2091. }
  2092. };
  2093. WebSocketConnection.prototype.shutdown_ = function () {
  2094. this.isClosed_ = true;
  2095. if (this.keepaliveTimer) {
  2096. clearInterval(this.keepaliveTimer);
  2097. this.keepaliveTimer = null;
  2098. }
  2099. if (this.mySock) {
  2100. this.mySock.close();
  2101. this.mySock = null;
  2102. }
  2103. };
  2104. WebSocketConnection.prototype.onClosed_ = function () {
  2105. if (!this.isClosed_) {
  2106. this.log_('WebSocket is closing itself');
  2107. this.shutdown_();
  2108. // since this is an internal close, trigger the close listener
  2109. if (this.onDisconnect) {
  2110. this.onDisconnect(this.everConnected_);
  2111. this.onDisconnect = null;
  2112. }
  2113. }
  2114. };
  2115. /**
  2116. * External-facing close handler.
  2117. * Close the websocket and kill the connection.
  2118. */
  2119. WebSocketConnection.prototype.close = function () {
  2120. if (!this.isClosed_) {
  2121. this.log_('WebSocket is being closed');
  2122. this.shutdown_();
  2123. }
  2124. };
  2125. /**
  2126. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  2127. * the last activity.
  2128. */
  2129. WebSocketConnection.prototype.resetKeepAlive = function () {
  2130. var _this = this;
  2131. clearInterval(this.keepaliveTimer);
  2132. this.keepaliveTimer = setInterval(function () {
  2133. //If there has been no websocket activity for a while, send a no-op
  2134. if (_this.mySock) {
  2135. _this.sendString_('0');
  2136. }
  2137. _this.resetKeepAlive();
  2138. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2139. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  2140. };
  2141. /**
  2142. * Send a string over the websocket.
  2143. *
  2144. * @param str - String to send.
  2145. */
  2146. WebSocketConnection.prototype.sendString_ = function (str) {
  2147. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  2148. // calls for some unknown reason. We treat these as an error and disconnect.
  2149. // See https://app.asana.com/0/58926111402292/68021340250410
  2150. try {
  2151. this.mySock.send(str);
  2152. }
  2153. catch (e) {
  2154. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  2155. setTimeout(this.onClosed_.bind(this), 0);
  2156. }
  2157. };
  2158. /**
  2159. * Number of response before we consider the connection "healthy."
  2160. */
  2161. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  2162. /**
  2163. * Time to wait for the connection te become healthy before giving up.
  2164. */
  2165. WebSocketConnection.healthyTimeout = 30000;
  2166. return WebSocketConnection;
  2167. }());
  2168. /**
  2169. * @license
  2170. * Copyright 2017 Google LLC
  2171. *
  2172. * Licensed under the Apache License, Version 2.0 (the "License");
  2173. * you may not use this file except in compliance with the License.
  2174. * You may obtain a copy of the License at
  2175. *
  2176. * http://www.apache.org/licenses/LICENSE-2.0
  2177. *
  2178. * Unless required by applicable law or agreed to in writing, software
  2179. * distributed under the License is distributed on an "AS IS" BASIS,
  2180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2181. * See the License for the specific language governing permissions and
  2182. * limitations under the License.
  2183. */
  2184. /**
  2185. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2186. * lifecycle.
  2187. *
  2188. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2189. * they are available.
  2190. */
  2191. var TransportManager = /** @class */ (function () {
  2192. /**
  2193. * @param repoInfo - Metadata around the namespace we're connecting to
  2194. */
  2195. function TransportManager(repoInfo) {
  2196. this.initTransports_(repoInfo);
  2197. }
  2198. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2199. get: function () {
  2200. return [BrowserPollConnection, WebSocketConnection];
  2201. },
  2202. enumerable: false,
  2203. configurable: true
  2204. });
  2205. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2206. /**
  2207. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2208. * TransportManager has already set up transports_
  2209. */
  2210. get: function () {
  2211. return this.globalTransportInitialized_;
  2212. },
  2213. enumerable: false,
  2214. configurable: true
  2215. });
  2216. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2217. var e_1, _a;
  2218. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2219. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2220. if (repoInfo.webSocketOnly) {
  2221. if (!isWebSocketsAvailable) {
  2222. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2223. }
  2224. isSkipPollConnection = true;
  2225. }
  2226. if (isSkipPollConnection) {
  2227. this.transports_ = [WebSocketConnection];
  2228. }
  2229. else {
  2230. var transports = (this.transports_ = []);
  2231. try {
  2232. for (var _b = __values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2233. var transport = _c.value;
  2234. if (transport && transport['isAvailable']()) {
  2235. transports.push(transport);
  2236. }
  2237. }
  2238. }
  2239. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2240. finally {
  2241. try {
  2242. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2243. }
  2244. finally { if (e_1) throw e_1.error; }
  2245. }
  2246. TransportManager.globalTransportInitialized_ = true;
  2247. }
  2248. };
  2249. /**
  2250. * @returns The constructor for the initial transport to use
  2251. */
  2252. TransportManager.prototype.initialTransport = function () {
  2253. if (this.transports_.length > 0) {
  2254. return this.transports_[0];
  2255. }
  2256. else {
  2257. throw new Error('No transports available');
  2258. }
  2259. };
  2260. /**
  2261. * @returns The constructor for the next transport, or null
  2262. */
  2263. TransportManager.prototype.upgradeTransport = function () {
  2264. if (this.transports_.length > 1) {
  2265. return this.transports_[1];
  2266. }
  2267. else {
  2268. return null;
  2269. }
  2270. };
  2271. // Keeps track of whether the TransportManager has already chosen a transport to use
  2272. TransportManager.globalTransportInitialized_ = false;
  2273. return TransportManager;
  2274. }());
  2275. /**
  2276. * @license
  2277. * Copyright 2017 Google LLC
  2278. *
  2279. * Licensed under the Apache License, Version 2.0 (the "License");
  2280. * you may not use this file except in compliance with the License.
  2281. * You may obtain a copy of the License at
  2282. *
  2283. * http://www.apache.org/licenses/LICENSE-2.0
  2284. *
  2285. * Unless required by applicable law or agreed to in writing, software
  2286. * distributed under the License is distributed on an "AS IS" BASIS,
  2287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2288. * See the License for the specific language governing permissions and
  2289. * limitations under the License.
  2290. */
  2291. // Abort upgrade attempt if it takes longer than 60s.
  2292. var UPGRADE_TIMEOUT = 60000;
  2293. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2294. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2295. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2296. // 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)
  2297. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2298. // but we've sent/received enough bytes, we don't cancel the connection.
  2299. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2300. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2301. var MESSAGE_TYPE = 't';
  2302. var MESSAGE_DATA = 'd';
  2303. var CONTROL_SHUTDOWN = 's';
  2304. var CONTROL_RESET = 'r';
  2305. var CONTROL_ERROR = 'e';
  2306. var CONTROL_PONG = 'o';
  2307. var SWITCH_ACK = 'a';
  2308. var END_TRANSMISSION = 'n';
  2309. var PING = 'p';
  2310. var SERVER_HELLO = 'h';
  2311. /**
  2312. * Creates a new real-time connection to the server using whichever method works
  2313. * best in the current browser.
  2314. */
  2315. var Connection = /** @class */ (function () {
  2316. /**
  2317. * @param id - an id for this connection
  2318. * @param repoInfo_ - the info for the endpoint to connect to
  2319. * @param applicationId_ - the Firebase App ID for this project
  2320. * @param appCheckToken_ - The App Check Token for this device.
  2321. * @param authToken_ - The auth token for this session.
  2322. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2323. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2324. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2325. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2326. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2327. */
  2328. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2329. this.id = id;
  2330. this.repoInfo_ = repoInfo_;
  2331. this.applicationId_ = applicationId_;
  2332. this.appCheckToken_ = appCheckToken_;
  2333. this.authToken_ = authToken_;
  2334. this.onMessage_ = onMessage_;
  2335. this.onReady_ = onReady_;
  2336. this.onDisconnect_ = onDisconnect_;
  2337. this.onKill_ = onKill_;
  2338. this.lastSessionId = lastSessionId;
  2339. this.connectionCount = 0;
  2340. this.pendingDataMessages = [];
  2341. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2342. this.log_ = logWrapper('c:' + this.id + ':');
  2343. this.transportManager_ = new TransportManager(repoInfo_);
  2344. this.log_('Connection created');
  2345. this.start_();
  2346. }
  2347. /**
  2348. * Starts a connection attempt
  2349. */
  2350. Connection.prototype.start_ = function () {
  2351. var _this = this;
  2352. var conn = this.transportManager_.initialTransport();
  2353. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2354. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2355. // can consider the transport healthy.
  2356. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2357. var onMessageReceived = this.connReceiver_(this.conn_);
  2358. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2359. this.tx_ = this.conn_;
  2360. this.rx_ = this.conn_;
  2361. this.secondaryConn_ = null;
  2362. this.isHealthy_ = false;
  2363. /*
  2364. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2365. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2366. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2367. * still have the context of your originating frame.
  2368. */
  2369. setTimeout(function () {
  2370. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2371. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2372. }, Math.floor(0));
  2373. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2374. if (healthyTimeoutMS > 0) {
  2375. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2376. _this.healthyTimeout_ = null;
  2377. if (!_this.isHealthy_) {
  2378. if (_this.conn_ &&
  2379. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2380. _this.log_('Connection exceeded healthy timeout but has received ' +
  2381. _this.conn_.bytesReceived +
  2382. ' bytes. Marking connection healthy.');
  2383. _this.isHealthy_ = true;
  2384. _this.conn_.markConnectionHealthy();
  2385. }
  2386. else if (_this.conn_ &&
  2387. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2388. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2389. _this.conn_.bytesSent +
  2390. ' bytes. Leaving connection alive.');
  2391. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2392. // the server.
  2393. }
  2394. else {
  2395. _this.log_('Closing unhealthy connection after timeout.');
  2396. _this.close();
  2397. }
  2398. }
  2399. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2400. }, Math.floor(healthyTimeoutMS));
  2401. }
  2402. };
  2403. Connection.prototype.nextTransportId_ = function () {
  2404. return 'c:' + this.id + ':' + this.connectionCount++;
  2405. };
  2406. Connection.prototype.disconnReceiver_ = function (conn) {
  2407. var _this = this;
  2408. return function (everConnected) {
  2409. if (conn === _this.conn_) {
  2410. _this.onConnectionLost_(everConnected);
  2411. }
  2412. else if (conn === _this.secondaryConn_) {
  2413. _this.log_('Secondary connection lost.');
  2414. _this.onSecondaryConnectionLost_();
  2415. }
  2416. else {
  2417. _this.log_('closing an old connection');
  2418. }
  2419. };
  2420. };
  2421. Connection.prototype.connReceiver_ = function (conn) {
  2422. var _this = this;
  2423. return function (message) {
  2424. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2425. if (conn === _this.rx_) {
  2426. _this.onPrimaryMessageReceived_(message);
  2427. }
  2428. else if (conn === _this.secondaryConn_) {
  2429. _this.onSecondaryMessageReceived_(message);
  2430. }
  2431. else {
  2432. _this.log_('message on old connection');
  2433. }
  2434. }
  2435. };
  2436. };
  2437. /**
  2438. * @param dataMsg - An arbitrary data message to be sent to the server
  2439. */
  2440. Connection.prototype.sendRequest = function (dataMsg) {
  2441. // wrap in a data message envelope and send it on
  2442. var msg = { t: 'd', d: dataMsg };
  2443. this.sendData_(msg);
  2444. };
  2445. Connection.prototype.tryCleanupConnection = function () {
  2446. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2447. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2448. this.conn_ = this.secondaryConn_;
  2449. this.secondaryConn_ = null;
  2450. // the server will shutdown the old connection
  2451. }
  2452. };
  2453. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2454. if (MESSAGE_TYPE in controlData) {
  2455. var cmd = controlData[MESSAGE_TYPE];
  2456. if (cmd === SWITCH_ACK) {
  2457. this.upgradeIfSecondaryHealthy_();
  2458. }
  2459. else if (cmd === CONTROL_RESET) {
  2460. // Most likely the session wasn't valid. Abandon the switch attempt
  2461. this.log_('Got a reset on secondary, closing it');
  2462. this.secondaryConn_.close();
  2463. // If we were already using this connection for something, than we need to fully close
  2464. if (this.tx_ === this.secondaryConn_ ||
  2465. this.rx_ === this.secondaryConn_) {
  2466. this.close();
  2467. }
  2468. }
  2469. else if (cmd === CONTROL_PONG) {
  2470. this.log_('got pong on secondary.');
  2471. this.secondaryResponsesRequired_--;
  2472. this.upgradeIfSecondaryHealthy_();
  2473. }
  2474. }
  2475. };
  2476. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2477. var layer = requireKey('t', parsedData);
  2478. var data = requireKey('d', parsedData);
  2479. if (layer === 'c') {
  2480. this.onSecondaryControl_(data);
  2481. }
  2482. else if (layer === 'd') {
  2483. // got a data message, but we're still second connection. Need to buffer it up
  2484. this.pendingDataMessages.push(data);
  2485. }
  2486. else {
  2487. throw new Error('Unknown protocol layer: ' + layer);
  2488. }
  2489. };
  2490. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2491. if (this.secondaryResponsesRequired_ <= 0) {
  2492. this.log_('Secondary connection is healthy.');
  2493. this.isHealthy_ = true;
  2494. this.secondaryConn_.markConnectionHealthy();
  2495. this.proceedWithUpgrade_();
  2496. }
  2497. else {
  2498. // Send a ping to make sure the connection is healthy.
  2499. this.log_('sending ping on secondary.');
  2500. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2501. }
  2502. };
  2503. Connection.prototype.proceedWithUpgrade_ = function () {
  2504. // tell this connection to consider itself open
  2505. this.secondaryConn_.start();
  2506. // send ack
  2507. this.log_('sending client ack on secondary');
  2508. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2509. // send end packet on primary transport, switch to sending on this one
  2510. // can receive on this one, buffer responses until end received on primary transport
  2511. this.log_('Ending transmission on primary');
  2512. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2513. this.tx_ = this.secondaryConn_;
  2514. this.tryCleanupConnection();
  2515. };
  2516. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2517. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2518. var layer = requireKey('t', parsedData);
  2519. var data = requireKey('d', parsedData);
  2520. if (layer === 'c') {
  2521. this.onControl_(data);
  2522. }
  2523. else if (layer === 'd') {
  2524. this.onDataMessage_(data);
  2525. }
  2526. };
  2527. Connection.prototype.onDataMessage_ = function (message) {
  2528. this.onPrimaryResponse_();
  2529. // We don't do anything with data messages, just kick them up a level
  2530. this.onMessage_(message);
  2531. };
  2532. Connection.prototype.onPrimaryResponse_ = function () {
  2533. if (!this.isHealthy_) {
  2534. this.primaryResponsesRequired_--;
  2535. if (this.primaryResponsesRequired_ <= 0) {
  2536. this.log_('Primary connection is healthy.');
  2537. this.isHealthy_ = true;
  2538. this.conn_.markConnectionHealthy();
  2539. }
  2540. }
  2541. };
  2542. Connection.prototype.onControl_ = function (controlData) {
  2543. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2544. if (MESSAGE_DATA in controlData) {
  2545. var payload = controlData[MESSAGE_DATA];
  2546. if (cmd === SERVER_HELLO) {
  2547. this.onHandshake_(payload);
  2548. }
  2549. else if (cmd === END_TRANSMISSION) {
  2550. this.log_('recvd end transmission on primary');
  2551. this.rx_ = this.secondaryConn_;
  2552. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2553. this.onDataMessage_(this.pendingDataMessages[i]);
  2554. }
  2555. this.pendingDataMessages = [];
  2556. this.tryCleanupConnection();
  2557. }
  2558. else if (cmd === CONTROL_SHUTDOWN) {
  2559. // This was previously the 'onKill' callback passed to the lower-level connection
  2560. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2561. this.onConnectionShutdown_(payload);
  2562. }
  2563. else if (cmd === CONTROL_RESET) {
  2564. // payload in this case is the host we should contact
  2565. this.onReset_(payload);
  2566. }
  2567. else if (cmd === CONTROL_ERROR) {
  2568. error('Server Error: ' + payload);
  2569. }
  2570. else if (cmd === CONTROL_PONG) {
  2571. this.log_('got pong on primary.');
  2572. this.onPrimaryResponse_();
  2573. this.sendPingOnPrimaryIfNecessary_();
  2574. }
  2575. else {
  2576. error('Unknown control packet command: ' + cmd);
  2577. }
  2578. }
  2579. };
  2580. /**
  2581. * @param handshake - The handshake data returned from the server
  2582. */
  2583. Connection.prototype.onHandshake_ = function (handshake) {
  2584. var timestamp = handshake.ts;
  2585. var version = handshake.v;
  2586. var host = handshake.h;
  2587. this.sessionId = handshake.s;
  2588. this.repoInfo_.host = host;
  2589. // if we've already closed the connection, then don't bother trying to progress further
  2590. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2591. this.conn_.start();
  2592. this.onConnectionEstablished_(this.conn_, timestamp);
  2593. if (PROTOCOL_VERSION !== version) {
  2594. warn('Protocol version mismatch detected');
  2595. }
  2596. // TODO: do we want to upgrade? when? maybe a delay?
  2597. this.tryStartUpgrade_();
  2598. }
  2599. };
  2600. Connection.prototype.tryStartUpgrade_ = function () {
  2601. var conn = this.transportManager_.upgradeTransport();
  2602. if (conn) {
  2603. this.startUpgrade_(conn);
  2604. }
  2605. };
  2606. Connection.prototype.startUpgrade_ = function (conn) {
  2607. var _this = this;
  2608. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2609. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2610. // can consider the transport healthy.
  2611. this.secondaryResponsesRequired_ =
  2612. conn['responsesRequiredToBeHealthy'] || 0;
  2613. var onMessage = this.connReceiver_(this.secondaryConn_);
  2614. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2615. this.secondaryConn_.open(onMessage, onDisconnect);
  2616. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2617. setTimeoutNonBlocking(function () {
  2618. if (_this.secondaryConn_) {
  2619. _this.log_('Timed out trying to upgrade.');
  2620. _this.secondaryConn_.close();
  2621. }
  2622. }, Math.floor(UPGRADE_TIMEOUT));
  2623. };
  2624. Connection.prototype.onReset_ = function (host) {
  2625. this.log_('Reset packet received. New host: ' + host);
  2626. this.repoInfo_.host = host;
  2627. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2628. // We don't currently support resets after the connection has already been established
  2629. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2630. this.close();
  2631. }
  2632. else {
  2633. // Close whatever connections we have open and start again.
  2634. this.closeConnections_();
  2635. this.start_();
  2636. }
  2637. };
  2638. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2639. var _this = this;
  2640. this.log_('Realtime connection established.');
  2641. this.conn_ = conn;
  2642. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2643. if (this.onReady_) {
  2644. this.onReady_(timestamp, this.sessionId);
  2645. this.onReady_ = null;
  2646. }
  2647. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2648. // send some pings.
  2649. if (this.primaryResponsesRequired_ === 0) {
  2650. this.log_('Primary connection is healthy.');
  2651. this.isHealthy_ = true;
  2652. }
  2653. else {
  2654. setTimeoutNonBlocking(function () {
  2655. _this.sendPingOnPrimaryIfNecessary_();
  2656. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2657. }
  2658. };
  2659. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2660. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2661. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2662. this.log_('sending ping on primary.');
  2663. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2664. }
  2665. };
  2666. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2667. var conn = this.secondaryConn_;
  2668. this.secondaryConn_ = null;
  2669. if (this.tx_ === conn || this.rx_ === conn) {
  2670. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2671. this.close();
  2672. }
  2673. };
  2674. /**
  2675. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2676. * we should flush the host cache
  2677. */
  2678. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2679. this.conn_ = null;
  2680. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2681. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2682. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2683. this.log_('Realtime connection failed.');
  2684. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2685. if (this.repoInfo_.isCacheableHost()) {
  2686. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2687. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2688. this.repoInfo_.internalHost = this.repoInfo_.host;
  2689. }
  2690. }
  2691. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2692. this.log_('Realtime connection lost.');
  2693. }
  2694. this.close();
  2695. };
  2696. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2697. this.log_('Connection shutdown command received. Shutting down...');
  2698. if (this.onKill_) {
  2699. this.onKill_(reason);
  2700. this.onKill_ = null;
  2701. }
  2702. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2703. // so clear the callback.
  2704. this.onDisconnect_ = null;
  2705. this.close();
  2706. };
  2707. Connection.prototype.sendData_ = function (data) {
  2708. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2709. throw 'Connection is not connected';
  2710. }
  2711. else {
  2712. this.tx_.send(data);
  2713. }
  2714. };
  2715. /**
  2716. * Cleans up this connection, calling the appropriate callbacks
  2717. */
  2718. Connection.prototype.close = function () {
  2719. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2720. this.log_('Closing realtime connection.');
  2721. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2722. this.closeConnections_();
  2723. if (this.onDisconnect_) {
  2724. this.onDisconnect_();
  2725. this.onDisconnect_ = null;
  2726. }
  2727. }
  2728. };
  2729. Connection.prototype.closeConnections_ = function () {
  2730. this.log_('Shutting down all connections');
  2731. if (this.conn_) {
  2732. this.conn_.close();
  2733. this.conn_ = null;
  2734. }
  2735. if (this.secondaryConn_) {
  2736. this.secondaryConn_.close();
  2737. this.secondaryConn_ = null;
  2738. }
  2739. if (this.healthyTimeout_) {
  2740. clearTimeout(this.healthyTimeout_);
  2741. this.healthyTimeout_ = null;
  2742. }
  2743. };
  2744. return Connection;
  2745. }());
  2746. /**
  2747. * @license
  2748. * Copyright 2017 Google LLC
  2749. *
  2750. * Licensed under the Apache License, Version 2.0 (the "License");
  2751. * you may not use this file except in compliance with the License.
  2752. * You may obtain a copy of the License at
  2753. *
  2754. * http://www.apache.org/licenses/LICENSE-2.0
  2755. *
  2756. * Unless required by applicable law or agreed to in writing, software
  2757. * distributed under the License is distributed on an "AS IS" BASIS,
  2758. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2759. * See the License for the specific language governing permissions and
  2760. * limitations under the License.
  2761. */
  2762. /**
  2763. * Interface defining the set of actions that can be performed against the Firebase server
  2764. * (basically corresponds to our wire protocol).
  2765. *
  2766. * @interface
  2767. */
  2768. var ServerActions = /** @class */ (function () {
  2769. function ServerActions() {
  2770. }
  2771. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2772. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2773. /**
  2774. * Refreshes the auth token for the current connection.
  2775. * @param token - The authentication token
  2776. */
  2777. ServerActions.prototype.refreshAuthToken = function (token) { };
  2778. /**
  2779. * Refreshes the app check token for the current connection.
  2780. * @param token The app check token
  2781. */
  2782. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2783. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2784. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2785. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2786. ServerActions.prototype.reportStats = function (stats) { };
  2787. return ServerActions;
  2788. }());
  2789. /**
  2790. * @license
  2791. * Copyright 2017 Google LLC
  2792. *
  2793. * Licensed under the Apache License, Version 2.0 (the "License");
  2794. * you may not use this file except in compliance with the License.
  2795. * You may obtain a copy of the License at
  2796. *
  2797. * http://www.apache.org/licenses/LICENSE-2.0
  2798. *
  2799. * Unless required by applicable law or agreed to in writing, software
  2800. * distributed under the License is distributed on an "AS IS" BASIS,
  2801. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2802. * See the License for the specific language governing permissions and
  2803. * limitations under the License.
  2804. */
  2805. /**
  2806. * Base class to be used if you want to emit events. Call the constructor with
  2807. * the set of allowed event names.
  2808. */
  2809. var EventEmitter = /** @class */ (function () {
  2810. function EventEmitter(allowedEvents_) {
  2811. this.allowedEvents_ = allowedEvents_;
  2812. this.listeners_ = {};
  2813. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2814. }
  2815. /**
  2816. * To be called by derived classes to trigger events.
  2817. */
  2818. EventEmitter.prototype.trigger = function (eventType) {
  2819. var varArgs = [];
  2820. for (var _i = 1; _i < arguments.length; _i++) {
  2821. varArgs[_i - 1] = arguments[_i];
  2822. }
  2823. if (Array.isArray(this.listeners_[eventType])) {
  2824. // Clone the list, since callbacks could add/remove listeners.
  2825. var listeners = __spreadArray([], __read(this.listeners_[eventType]), false);
  2826. for (var i = 0; i < listeners.length; i++) {
  2827. listeners[i].callback.apply(listeners[i].context, varArgs);
  2828. }
  2829. }
  2830. };
  2831. EventEmitter.prototype.on = function (eventType, callback, context) {
  2832. this.validateEventType_(eventType);
  2833. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2834. this.listeners_[eventType].push({ callback: callback, context: context });
  2835. var eventData = this.getInitialEvent(eventType);
  2836. if (eventData) {
  2837. callback.apply(context, eventData);
  2838. }
  2839. };
  2840. EventEmitter.prototype.off = function (eventType, callback, context) {
  2841. this.validateEventType_(eventType);
  2842. var listeners = this.listeners_[eventType] || [];
  2843. for (var i = 0; i < listeners.length; i++) {
  2844. if (listeners[i].callback === callback &&
  2845. (!context || context === listeners[i].context)) {
  2846. listeners.splice(i, 1);
  2847. return;
  2848. }
  2849. }
  2850. };
  2851. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2852. assert(this.allowedEvents_.find(function (et) {
  2853. return et === eventType;
  2854. }), 'Unknown event: ' + eventType);
  2855. };
  2856. return EventEmitter;
  2857. }());
  2858. /**
  2859. * @license
  2860. * Copyright 2017 Google LLC
  2861. *
  2862. * Licensed under the Apache License, Version 2.0 (the "License");
  2863. * you may not use this file except in compliance with the License.
  2864. * You may obtain a copy of the License at
  2865. *
  2866. * http://www.apache.org/licenses/LICENSE-2.0
  2867. *
  2868. * Unless required by applicable law or agreed to in writing, software
  2869. * distributed under the License is distributed on an "AS IS" BASIS,
  2870. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2871. * See the License for the specific language governing permissions and
  2872. * limitations under the License.
  2873. */
  2874. /**
  2875. * Monitors online state (as reported by window.online/offline events).
  2876. *
  2877. * The expectation is that this could have many false positives (thinks we are online
  2878. * when we're not), but no false negatives. So we can safely use it to determine when
  2879. * we definitely cannot reach the internet.
  2880. */
  2881. var OnlineMonitor = /** @class */ (function (_super) {
  2882. __extends(OnlineMonitor, _super);
  2883. function OnlineMonitor() {
  2884. var _this = _super.call(this, ['online']) || this;
  2885. _this.online_ = true;
  2886. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2887. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2888. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2889. // for Cordova.
  2890. if (typeof window !== 'undefined' &&
  2891. typeof window.addEventListener !== 'undefined' &&
  2892. !isMobileCordova()) {
  2893. window.addEventListener('online', function () {
  2894. if (!_this.online_) {
  2895. _this.online_ = true;
  2896. _this.trigger('online', true);
  2897. }
  2898. }, false);
  2899. window.addEventListener('offline', function () {
  2900. if (_this.online_) {
  2901. _this.online_ = false;
  2902. _this.trigger('online', false);
  2903. }
  2904. }, false);
  2905. }
  2906. return _this;
  2907. }
  2908. OnlineMonitor.getInstance = function () {
  2909. return new OnlineMonitor();
  2910. };
  2911. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2912. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2913. return [this.online_];
  2914. };
  2915. OnlineMonitor.prototype.currentlyOnline = function () {
  2916. return this.online_;
  2917. };
  2918. return OnlineMonitor;
  2919. }(EventEmitter));
  2920. /**
  2921. * @license
  2922. * Copyright 2017 Google LLC
  2923. *
  2924. * Licensed under the Apache License, Version 2.0 (the "License");
  2925. * you may not use this file except in compliance with the License.
  2926. * You may obtain a copy of the License at
  2927. *
  2928. * http://www.apache.org/licenses/LICENSE-2.0
  2929. *
  2930. * Unless required by applicable law or agreed to in writing, software
  2931. * distributed under the License is distributed on an "AS IS" BASIS,
  2932. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2933. * See the License for the specific language governing permissions and
  2934. * limitations under the License.
  2935. */
  2936. /** Maximum key depth. */
  2937. var MAX_PATH_DEPTH = 32;
  2938. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2939. var MAX_PATH_LENGTH_BYTES = 768;
  2940. /**
  2941. * An immutable object representing a parsed path. It's immutable so that you
  2942. * can pass them around to other functions without worrying about them changing
  2943. * it.
  2944. */
  2945. var Path = /** @class */ (function () {
  2946. /**
  2947. * @param pathOrString - Path string to parse, or another path, or the raw
  2948. * tokens array
  2949. */
  2950. function Path(pathOrString, pieceNum) {
  2951. if (pieceNum === void 0) {
  2952. this.pieces_ = pathOrString.split('/');
  2953. // Remove empty pieces.
  2954. var copyTo = 0;
  2955. for (var i = 0; i < this.pieces_.length; i++) {
  2956. if (this.pieces_[i].length > 0) {
  2957. this.pieces_[copyTo] = this.pieces_[i];
  2958. copyTo++;
  2959. }
  2960. }
  2961. this.pieces_.length = copyTo;
  2962. this.pieceNum_ = 0;
  2963. }
  2964. else {
  2965. this.pieces_ = pathOrString;
  2966. this.pieceNum_ = pieceNum;
  2967. }
  2968. }
  2969. Path.prototype.toString = function () {
  2970. var pathString = '';
  2971. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2972. if (this.pieces_[i] !== '') {
  2973. pathString += '/' + this.pieces_[i];
  2974. }
  2975. }
  2976. return pathString || '/';
  2977. };
  2978. return Path;
  2979. }());
  2980. function newEmptyPath() {
  2981. return new Path('');
  2982. }
  2983. function pathGetFront(path) {
  2984. if (path.pieceNum_ >= path.pieces_.length) {
  2985. return null;
  2986. }
  2987. return path.pieces_[path.pieceNum_];
  2988. }
  2989. /**
  2990. * @returns The number of segments in this path
  2991. */
  2992. function pathGetLength(path) {
  2993. return path.pieces_.length - path.pieceNum_;
  2994. }
  2995. function pathPopFront(path) {
  2996. var pieceNum = path.pieceNum_;
  2997. if (pieceNum < path.pieces_.length) {
  2998. pieceNum++;
  2999. }
  3000. return new Path(path.pieces_, pieceNum);
  3001. }
  3002. function pathGetBack(path) {
  3003. if (path.pieceNum_ < path.pieces_.length) {
  3004. return path.pieces_[path.pieces_.length - 1];
  3005. }
  3006. return null;
  3007. }
  3008. function pathToUrlEncodedString(path) {
  3009. var pathString = '';
  3010. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3011. if (path.pieces_[i] !== '') {
  3012. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3013. }
  3014. }
  3015. return pathString || '/';
  3016. }
  3017. /**
  3018. * Shallow copy of the parts of the path.
  3019. *
  3020. */
  3021. function pathSlice(path, begin) {
  3022. if (begin === void 0) { begin = 0; }
  3023. return path.pieces_.slice(path.pieceNum_ + begin);
  3024. }
  3025. function pathParent(path) {
  3026. if (path.pieceNum_ >= path.pieces_.length) {
  3027. return null;
  3028. }
  3029. var pieces = [];
  3030. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3031. pieces.push(path.pieces_[i]);
  3032. }
  3033. return new Path(pieces, 0);
  3034. }
  3035. function pathChild(path, childPathObj) {
  3036. var pieces = [];
  3037. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3038. pieces.push(path.pieces_[i]);
  3039. }
  3040. if (childPathObj instanceof Path) {
  3041. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3042. pieces.push(childPathObj.pieces_[i]);
  3043. }
  3044. }
  3045. else {
  3046. var childPieces = childPathObj.split('/');
  3047. for (var i = 0; i < childPieces.length; i++) {
  3048. if (childPieces[i].length > 0) {
  3049. pieces.push(childPieces[i]);
  3050. }
  3051. }
  3052. }
  3053. return new Path(pieces, 0);
  3054. }
  3055. /**
  3056. * @returns True if there are no segments in this path
  3057. */
  3058. function pathIsEmpty(path) {
  3059. return path.pieceNum_ >= path.pieces_.length;
  3060. }
  3061. /**
  3062. * @returns The path from outerPath to innerPath
  3063. */
  3064. function newRelativePath(outerPath, innerPath) {
  3065. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3066. if (outer === null) {
  3067. return innerPath;
  3068. }
  3069. else if (outer === inner) {
  3070. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3071. }
  3072. else {
  3073. throw new Error('INTERNAL ERROR: innerPath (' +
  3074. innerPath +
  3075. ') is not within ' +
  3076. 'outerPath (' +
  3077. outerPath +
  3078. ')');
  3079. }
  3080. }
  3081. /**
  3082. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3083. */
  3084. function pathCompare(left, right) {
  3085. var leftKeys = pathSlice(left, 0);
  3086. var rightKeys = pathSlice(right, 0);
  3087. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3088. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3089. if (cmp !== 0) {
  3090. return cmp;
  3091. }
  3092. }
  3093. if (leftKeys.length === rightKeys.length) {
  3094. return 0;
  3095. }
  3096. return leftKeys.length < rightKeys.length ? -1 : 1;
  3097. }
  3098. /**
  3099. * @returns true if paths are the same.
  3100. */
  3101. function pathEquals(path, other) {
  3102. if (pathGetLength(path) !== pathGetLength(other)) {
  3103. return false;
  3104. }
  3105. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3106. if (path.pieces_[i] !== other.pieces_[j]) {
  3107. return false;
  3108. }
  3109. }
  3110. return true;
  3111. }
  3112. /**
  3113. * @returns True if this path is a parent of (or the same as) other
  3114. */
  3115. function pathContains(path, other) {
  3116. var i = path.pieceNum_;
  3117. var j = other.pieceNum_;
  3118. if (pathGetLength(path) > pathGetLength(other)) {
  3119. return false;
  3120. }
  3121. while (i < path.pieces_.length) {
  3122. if (path.pieces_[i] !== other.pieces_[j]) {
  3123. return false;
  3124. }
  3125. ++i;
  3126. ++j;
  3127. }
  3128. return true;
  3129. }
  3130. /**
  3131. * Dynamic (mutable) path used to count path lengths.
  3132. *
  3133. * This class is used to efficiently check paths for valid
  3134. * length (in UTF8 bytes) and depth (used in path validation).
  3135. *
  3136. * Throws Error exception if path is ever invalid.
  3137. *
  3138. * The definition of a path always begins with '/'.
  3139. */
  3140. var ValidationPath = /** @class */ (function () {
  3141. /**
  3142. * @param path - Initial Path.
  3143. * @param errorPrefix_ - Prefix for any error messages.
  3144. */
  3145. function ValidationPath(path, errorPrefix_) {
  3146. this.errorPrefix_ = errorPrefix_;
  3147. this.parts_ = pathSlice(path, 0);
  3148. /** Initialize to number of '/' chars needed in path. */
  3149. this.byteLength_ = Math.max(1, this.parts_.length);
  3150. for (var i = 0; i < this.parts_.length; i++) {
  3151. this.byteLength_ += stringLength(this.parts_[i]);
  3152. }
  3153. validationPathCheckValid(this);
  3154. }
  3155. return ValidationPath;
  3156. }());
  3157. function validationPathPush(validationPath, child) {
  3158. // Count the needed '/'
  3159. if (validationPath.parts_.length > 0) {
  3160. validationPath.byteLength_ += 1;
  3161. }
  3162. validationPath.parts_.push(child);
  3163. validationPath.byteLength_ += stringLength(child);
  3164. validationPathCheckValid(validationPath);
  3165. }
  3166. function validationPathPop(validationPath) {
  3167. var last = validationPath.parts_.pop();
  3168. validationPath.byteLength_ -= stringLength(last);
  3169. // Un-count the previous '/'
  3170. if (validationPath.parts_.length > 0) {
  3171. validationPath.byteLength_ -= 1;
  3172. }
  3173. }
  3174. function validationPathCheckValid(validationPath) {
  3175. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3176. throw new Error(validationPath.errorPrefix_ +
  3177. 'has a key path longer than ' +
  3178. MAX_PATH_LENGTH_BYTES +
  3179. ' bytes (' +
  3180. validationPath.byteLength_ +
  3181. ').');
  3182. }
  3183. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3184. throw new Error(validationPath.errorPrefix_ +
  3185. 'path specified exceeds the maximum depth that can be written (' +
  3186. MAX_PATH_DEPTH +
  3187. ') or object contains a cycle ' +
  3188. validationPathToErrorString(validationPath));
  3189. }
  3190. }
  3191. /**
  3192. * String for use in error messages - uses '.' notation for path.
  3193. */
  3194. function validationPathToErrorString(validationPath) {
  3195. if (validationPath.parts_.length === 0) {
  3196. return '';
  3197. }
  3198. return "in property '" + validationPath.parts_.join('.') + "'";
  3199. }
  3200. /**
  3201. * @license
  3202. * Copyright 2017 Google LLC
  3203. *
  3204. * Licensed under the Apache License, Version 2.0 (the "License");
  3205. * you may not use this file except in compliance with the License.
  3206. * You may obtain a copy of the License at
  3207. *
  3208. * http://www.apache.org/licenses/LICENSE-2.0
  3209. *
  3210. * Unless required by applicable law or agreed to in writing, software
  3211. * distributed under the License is distributed on an "AS IS" BASIS,
  3212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3213. * See the License for the specific language governing permissions and
  3214. * limitations under the License.
  3215. */
  3216. var VisibilityMonitor = /** @class */ (function (_super) {
  3217. __extends(VisibilityMonitor, _super);
  3218. function VisibilityMonitor() {
  3219. var _this = _super.call(this, ['visible']) || this;
  3220. var hidden;
  3221. var visibilityChange;
  3222. if (typeof document !== 'undefined' &&
  3223. typeof document.addEventListener !== 'undefined') {
  3224. if (typeof document['hidden'] !== 'undefined') {
  3225. // Opera 12.10 and Firefox 18 and later support
  3226. visibilityChange = 'visibilitychange';
  3227. hidden = 'hidden';
  3228. }
  3229. else if (typeof document['mozHidden'] !== 'undefined') {
  3230. visibilityChange = 'mozvisibilitychange';
  3231. hidden = 'mozHidden';
  3232. }
  3233. else if (typeof document['msHidden'] !== 'undefined') {
  3234. visibilityChange = 'msvisibilitychange';
  3235. hidden = 'msHidden';
  3236. }
  3237. else if (typeof document['webkitHidden'] !== 'undefined') {
  3238. visibilityChange = 'webkitvisibilitychange';
  3239. hidden = 'webkitHidden';
  3240. }
  3241. }
  3242. // Initially, we always assume we are visible. This ensures that in browsers
  3243. // without page visibility support or in cases where we are never visible
  3244. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3245. // reconnects
  3246. _this.visible_ = true;
  3247. if (visibilityChange) {
  3248. document.addEventListener(visibilityChange, function () {
  3249. var visible = !document[hidden];
  3250. if (visible !== _this.visible_) {
  3251. _this.visible_ = visible;
  3252. _this.trigger('visible', visible);
  3253. }
  3254. }, false);
  3255. }
  3256. return _this;
  3257. }
  3258. VisibilityMonitor.getInstance = function () {
  3259. return new VisibilityMonitor();
  3260. };
  3261. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3262. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3263. return [this.visible_];
  3264. };
  3265. return VisibilityMonitor;
  3266. }(EventEmitter));
  3267. /**
  3268. * @license
  3269. * Copyright 2017 Google LLC
  3270. *
  3271. * Licensed under the Apache License, Version 2.0 (the "License");
  3272. * you may not use this file except in compliance with the License.
  3273. * You may obtain a copy of the License at
  3274. *
  3275. * http://www.apache.org/licenses/LICENSE-2.0
  3276. *
  3277. * Unless required by applicable law or agreed to in writing, software
  3278. * distributed under the License is distributed on an "AS IS" BASIS,
  3279. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3280. * See the License for the specific language governing permissions and
  3281. * limitations under the License.
  3282. */
  3283. var RECONNECT_MIN_DELAY = 1000;
  3284. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3285. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3286. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3287. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3288. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3289. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3290. var INVALID_TOKEN_THRESHOLD = 3;
  3291. /**
  3292. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3293. *
  3294. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3295. * in quotes to make sure the closure compiler does not minify them.
  3296. */
  3297. var PersistentConnection = /** @class */ (function (_super) {
  3298. __extends(PersistentConnection, _super);
  3299. /**
  3300. * @param repoInfo_ - Data about the namespace we are connecting to
  3301. * @param applicationId_ - The Firebase App ID for this project
  3302. * @param onDataUpdate_ - A callback for new data from the server
  3303. */
  3304. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3305. var _this = _super.call(this) || this;
  3306. _this.repoInfo_ = repoInfo_;
  3307. _this.applicationId_ = applicationId_;
  3308. _this.onDataUpdate_ = onDataUpdate_;
  3309. _this.onConnectStatus_ = onConnectStatus_;
  3310. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3311. _this.authTokenProvider_ = authTokenProvider_;
  3312. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3313. _this.authOverride_ = authOverride_;
  3314. // Used for diagnostic logging.
  3315. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3316. _this.log_ = logWrapper('p:' + _this.id + ':');
  3317. _this.interruptReasons_ = {};
  3318. _this.listens = new Map();
  3319. _this.outstandingPuts_ = [];
  3320. _this.outstandingGets_ = [];
  3321. _this.outstandingPutCount_ = 0;
  3322. _this.outstandingGetCount_ = 0;
  3323. _this.onDisconnectRequestQueue_ = [];
  3324. _this.connected_ = false;
  3325. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3326. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3327. _this.securityDebugCallback_ = null;
  3328. _this.lastSessionId = null;
  3329. _this.establishConnectionTimer_ = null;
  3330. _this.visible_ = false;
  3331. // Before we get connected, we keep a queue of pending messages to send.
  3332. _this.requestCBHash_ = {};
  3333. _this.requestNumber_ = 0;
  3334. _this.realtime_ = null;
  3335. _this.authToken_ = null;
  3336. _this.appCheckToken_ = null;
  3337. _this.forceTokenRefresh_ = false;
  3338. _this.invalidAuthTokenCount_ = 0;
  3339. _this.invalidAppCheckTokenCount_ = 0;
  3340. _this.firstConnection_ = true;
  3341. _this.lastConnectionAttemptTime_ = null;
  3342. _this.lastConnectionEstablishedTime_ = null;
  3343. if (authOverride_ && !isNodeSdk()) {
  3344. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3345. }
  3346. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3347. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3348. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3349. }
  3350. return _this;
  3351. }
  3352. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3353. var curReqNum = ++this.requestNumber_;
  3354. var msg = { r: curReqNum, a: action, b: body };
  3355. this.log_(stringify(msg));
  3356. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3357. this.realtime_.sendRequest(msg);
  3358. if (onResponse) {
  3359. this.requestCBHash_[curReqNum] = onResponse;
  3360. }
  3361. };
  3362. PersistentConnection.prototype.get = function (query) {
  3363. this.initConnection_();
  3364. var deferred = new Deferred();
  3365. var request = {
  3366. p: query._path.toString(),
  3367. q: query._queryObject
  3368. };
  3369. var outstandingGet = {
  3370. action: 'g',
  3371. request: request,
  3372. onComplete: function (message) {
  3373. var payload = message['d'];
  3374. if (message['s'] === 'ok') {
  3375. deferred.resolve(payload);
  3376. }
  3377. else {
  3378. deferred.reject(payload);
  3379. }
  3380. }
  3381. };
  3382. this.outstandingGets_.push(outstandingGet);
  3383. this.outstandingGetCount_++;
  3384. var index = this.outstandingGets_.length - 1;
  3385. if (this.connected_) {
  3386. this.sendGet_(index);
  3387. }
  3388. return deferred.promise;
  3389. };
  3390. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3391. this.initConnection_();
  3392. var queryId = query._queryIdentifier;
  3393. var pathString = query._path.toString();
  3394. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3395. if (!this.listens.has(pathString)) {
  3396. this.listens.set(pathString, new Map());
  3397. }
  3398. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3399. assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3400. var listenSpec = {
  3401. onComplete: onComplete,
  3402. hashFn: currentHashFn,
  3403. query: query,
  3404. tag: tag
  3405. };
  3406. this.listens.get(pathString).set(queryId, listenSpec);
  3407. if (this.connected_) {
  3408. this.sendListen_(listenSpec);
  3409. }
  3410. };
  3411. PersistentConnection.prototype.sendGet_ = function (index) {
  3412. var _this = this;
  3413. var get = this.outstandingGets_[index];
  3414. this.sendRequest('g', get.request, function (message) {
  3415. delete _this.outstandingGets_[index];
  3416. _this.outstandingGetCount_--;
  3417. if (_this.outstandingGetCount_ === 0) {
  3418. _this.outstandingGets_ = [];
  3419. }
  3420. if (get.onComplete) {
  3421. get.onComplete(message);
  3422. }
  3423. });
  3424. };
  3425. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3426. var _this = this;
  3427. var query = listenSpec.query;
  3428. var pathString = query._path.toString();
  3429. var queryId = query._queryIdentifier;
  3430. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3431. var req = { /*path*/ p: pathString };
  3432. var action = 'q';
  3433. // Only bother to send query if it's non-default.
  3434. if (listenSpec.tag) {
  3435. req['q'] = query._queryObject;
  3436. req['t'] = listenSpec.tag;
  3437. }
  3438. req[ /*hash*/'h'] = listenSpec.hashFn();
  3439. this.sendRequest(action, req, function (message) {
  3440. var payload = message[ /*data*/'d'];
  3441. var status = message[ /*status*/'s'];
  3442. // print warnings in any case...
  3443. PersistentConnection.warnOnListenWarnings_(payload, query);
  3444. var currentListenSpec = _this.listens.get(pathString) &&
  3445. _this.listens.get(pathString).get(queryId);
  3446. // only trigger actions if the listen hasn't been removed and readded
  3447. if (currentListenSpec === listenSpec) {
  3448. _this.log_('listen response', message);
  3449. if (status !== 'ok') {
  3450. _this.removeListen_(pathString, queryId);
  3451. }
  3452. if (listenSpec.onComplete) {
  3453. listenSpec.onComplete(status, payload);
  3454. }
  3455. }
  3456. });
  3457. };
  3458. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3459. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3460. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3461. var warnings = safeGet(payload, 'w');
  3462. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3463. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3464. var indexPath = query._path.toString();
  3465. warn("Using an unspecified index. Your data will be downloaded and " +
  3466. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3467. "".concat(indexPath, " to your security rules for better performance."));
  3468. }
  3469. }
  3470. };
  3471. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3472. this.authToken_ = token;
  3473. this.log_('Auth token refreshed');
  3474. if (this.authToken_) {
  3475. this.tryAuth();
  3476. }
  3477. else {
  3478. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3479. //the credential so we dont become authenticated next time we connect.
  3480. if (this.connected_) {
  3481. this.sendRequest('unauth', {}, function () { });
  3482. }
  3483. }
  3484. this.reduceReconnectDelayIfAdminCredential_(token);
  3485. };
  3486. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3487. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3488. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3489. var isFirebaseSecret = credential && credential.length === 40;
  3490. if (isFirebaseSecret || isAdmin(credential)) {
  3491. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3492. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3493. }
  3494. };
  3495. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3496. this.appCheckToken_ = token;
  3497. this.log_('App check token refreshed');
  3498. if (this.appCheckToken_) {
  3499. this.tryAppCheck();
  3500. }
  3501. else {
  3502. //If we're connected we want to let the server know to unauthenticate us.
  3503. //If we're not connected, simply delete the credential so we dont become
  3504. // authenticated next time we connect.
  3505. if (this.connected_) {
  3506. this.sendRequest('unappeck', {}, function () { });
  3507. }
  3508. }
  3509. };
  3510. /**
  3511. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3512. * a auth revoked (the connection is closed).
  3513. */
  3514. PersistentConnection.prototype.tryAuth = function () {
  3515. var _this = this;
  3516. if (this.connected_ && this.authToken_) {
  3517. var token_1 = this.authToken_;
  3518. var authMethod = isValidFormat(token_1) ? 'auth' : 'gauth';
  3519. var requestData = { cred: token_1 };
  3520. if (this.authOverride_ === null) {
  3521. requestData['noauth'] = true;
  3522. }
  3523. else if (typeof this.authOverride_ === 'object') {
  3524. requestData['authvar'] = this.authOverride_;
  3525. }
  3526. this.sendRequest(authMethod, requestData, function (res) {
  3527. var status = res[ /*status*/'s'];
  3528. var data = res[ /*data*/'d'] || 'error';
  3529. if (_this.authToken_ === token_1) {
  3530. if (status === 'ok') {
  3531. _this.invalidAuthTokenCount_ = 0;
  3532. }
  3533. else {
  3534. // Triggers reconnect and force refresh for auth token
  3535. _this.onAuthRevoked_(status, data);
  3536. }
  3537. }
  3538. });
  3539. }
  3540. };
  3541. /**
  3542. * Attempts to authenticate with the given token. If the authentication
  3543. * attempt fails, it's triggered like the token was revoked (the connection is
  3544. * closed).
  3545. */
  3546. PersistentConnection.prototype.tryAppCheck = function () {
  3547. var _this = this;
  3548. if (this.connected_ && this.appCheckToken_) {
  3549. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3550. var status = res[ /*status*/'s'];
  3551. var data = res[ /*data*/'d'] || 'error';
  3552. if (status === 'ok') {
  3553. _this.invalidAppCheckTokenCount_ = 0;
  3554. }
  3555. else {
  3556. _this.onAppCheckRevoked_(status, data);
  3557. }
  3558. });
  3559. }
  3560. };
  3561. /**
  3562. * @inheritDoc
  3563. */
  3564. PersistentConnection.prototype.unlisten = function (query, tag) {
  3565. var pathString = query._path.toString();
  3566. var queryId = query._queryIdentifier;
  3567. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3568. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3569. var listen = this.removeListen_(pathString, queryId);
  3570. if (listen && this.connected_) {
  3571. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3572. }
  3573. };
  3574. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3575. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3576. var req = { /*path*/ p: pathString };
  3577. var action = 'n';
  3578. // Only bother sending queryId if it's non-default.
  3579. if (tag) {
  3580. req['q'] = queryObj;
  3581. req['t'] = tag;
  3582. }
  3583. this.sendRequest(action, req);
  3584. };
  3585. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3586. this.initConnection_();
  3587. if (this.connected_) {
  3588. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3589. }
  3590. else {
  3591. this.onDisconnectRequestQueue_.push({
  3592. pathString: pathString,
  3593. action: 'o',
  3594. data: data,
  3595. onComplete: onComplete
  3596. });
  3597. }
  3598. };
  3599. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3600. this.initConnection_();
  3601. if (this.connected_) {
  3602. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3603. }
  3604. else {
  3605. this.onDisconnectRequestQueue_.push({
  3606. pathString: pathString,
  3607. action: 'om',
  3608. data: data,
  3609. onComplete: onComplete
  3610. });
  3611. }
  3612. };
  3613. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3614. this.initConnection_();
  3615. if (this.connected_) {
  3616. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3617. }
  3618. else {
  3619. this.onDisconnectRequestQueue_.push({
  3620. pathString: pathString,
  3621. action: 'oc',
  3622. data: null,
  3623. onComplete: onComplete
  3624. });
  3625. }
  3626. };
  3627. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3628. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3629. this.log_('onDisconnect ' + action, request);
  3630. this.sendRequest(action, request, function (response) {
  3631. if (onComplete) {
  3632. setTimeout(function () {
  3633. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3634. }, Math.floor(0));
  3635. }
  3636. });
  3637. };
  3638. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3639. this.putInternal('p', pathString, data, onComplete, hash);
  3640. };
  3641. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3642. this.putInternal('m', pathString, data, onComplete, hash);
  3643. };
  3644. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3645. this.initConnection_();
  3646. var request = {
  3647. /*path*/ p: pathString,
  3648. /*data*/ d: data
  3649. };
  3650. if (hash !== undefined) {
  3651. request[ /*hash*/'h'] = hash;
  3652. }
  3653. // TODO: Only keep track of the most recent put for a given path?
  3654. this.outstandingPuts_.push({
  3655. action: action,
  3656. request: request,
  3657. onComplete: onComplete
  3658. });
  3659. this.outstandingPutCount_++;
  3660. var index = this.outstandingPuts_.length - 1;
  3661. if (this.connected_) {
  3662. this.sendPut_(index);
  3663. }
  3664. else {
  3665. this.log_('Buffering put: ' + pathString);
  3666. }
  3667. };
  3668. PersistentConnection.prototype.sendPut_ = function (index) {
  3669. var _this = this;
  3670. var action = this.outstandingPuts_[index].action;
  3671. var request = this.outstandingPuts_[index].request;
  3672. var onComplete = this.outstandingPuts_[index].onComplete;
  3673. this.outstandingPuts_[index].queued = this.connected_;
  3674. this.sendRequest(action, request, function (message) {
  3675. _this.log_(action + ' response', message);
  3676. delete _this.outstandingPuts_[index];
  3677. _this.outstandingPutCount_--;
  3678. // Clean up array occasionally.
  3679. if (_this.outstandingPutCount_ === 0) {
  3680. _this.outstandingPuts_ = [];
  3681. }
  3682. if (onComplete) {
  3683. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3684. }
  3685. });
  3686. };
  3687. PersistentConnection.prototype.reportStats = function (stats) {
  3688. var _this = this;
  3689. // If we're not connected, we just drop the stats.
  3690. if (this.connected_) {
  3691. var request = { /*counters*/ c: stats };
  3692. this.log_('reportStats', request);
  3693. this.sendRequest(/*stats*/ 's', request, function (result) {
  3694. var status = result[ /*status*/'s'];
  3695. if (status !== 'ok') {
  3696. var errorReason = result[ /* data */'d'];
  3697. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3698. }
  3699. });
  3700. }
  3701. };
  3702. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3703. if ('r' in message) {
  3704. // this is a response
  3705. this.log_('from server: ' + stringify(message));
  3706. var reqNum = message['r'];
  3707. var onResponse = this.requestCBHash_[reqNum];
  3708. if (onResponse) {
  3709. delete this.requestCBHash_[reqNum];
  3710. onResponse(message[ /*body*/'b']);
  3711. }
  3712. }
  3713. else if ('error' in message) {
  3714. throw 'A server-side error has occurred: ' + message['error'];
  3715. }
  3716. else if ('a' in message) {
  3717. // a and b are action and body, respectively
  3718. this.onDataPush_(message['a'], message['b']);
  3719. }
  3720. };
  3721. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3722. this.log_('handleServerMessage', action, body);
  3723. if (action === 'd') {
  3724. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3725. /*isMerge*/ false, body['t']);
  3726. }
  3727. else if (action === 'm') {
  3728. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3729. /*isMerge=*/ true, body['t']);
  3730. }
  3731. else if (action === 'c') {
  3732. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3733. }
  3734. else if (action === 'ac') {
  3735. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3736. }
  3737. else if (action === 'apc') {
  3738. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3739. }
  3740. else if (action === 'sd') {
  3741. this.onSecurityDebugPacket_(body);
  3742. }
  3743. else {
  3744. error('Unrecognized action received from server: ' +
  3745. stringify(action) +
  3746. '\nAre you using the latest client?');
  3747. }
  3748. };
  3749. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3750. this.log_('connection ready');
  3751. this.connected_ = true;
  3752. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3753. this.handleTimestamp_(timestamp);
  3754. this.lastSessionId = sessionId;
  3755. if (this.firstConnection_) {
  3756. this.sendConnectStats_();
  3757. }
  3758. this.restoreState_();
  3759. this.firstConnection_ = false;
  3760. this.onConnectStatus_(true);
  3761. };
  3762. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3763. var _this = this;
  3764. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3765. if (this.establishConnectionTimer_) {
  3766. clearTimeout(this.establishConnectionTimer_);
  3767. }
  3768. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3769. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3770. this.establishConnectionTimer_ = setTimeout(function () {
  3771. _this.establishConnectionTimer_ = null;
  3772. _this.establishConnection_();
  3773. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3774. }, Math.floor(timeout));
  3775. };
  3776. PersistentConnection.prototype.initConnection_ = function () {
  3777. if (!this.realtime_ && this.firstConnection_) {
  3778. this.scheduleConnect_(0);
  3779. }
  3780. };
  3781. PersistentConnection.prototype.onVisible_ = function (visible) {
  3782. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3783. if (visible &&
  3784. !this.visible_ &&
  3785. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3786. this.log_('Window became visible. Reducing delay.');
  3787. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3788. if (!this.realtime_) {
  3789. this.scheduleConnect_(0);
  3790. }
  3791. }
  3792. this.visible_ = visible;
  3793. };
  3794. PersistentConnection.prototype.onOnline_ = function (online) {
  3795. if (online) {
  3796. this.log_('Browser went online.');
  3797. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3798. if (!this.realtime_) {
  3799. this.scheduleConnect_(0);
  3800. }
  3801. }
  3802. else {
  3803. this.log_('Browser went offline. Killing connection.');
  3804. if (this.realtime_) {
  3805. this.realtime_.close();
  3806. }
  3807. }
  3808. };
  3809. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3810. this.log_('data client disconnected');
  3811. this.connected_ = false;
  3812. this.realtime_ = null;
  3813. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3814. this.cancelSentTransactions_();
  3815. // Clear out the pending requests.
  3816. this.requestCBHash_ = {};
  3817. if (this.shouldReconnect_()) {
  3818. if (!this.visible_) {
  3819. this.log_("Window isn't visible. Delaying reconnect.");
  3820. this.reconnectDelay_ = this.maxReconnectDelay_;
  3821. this.lastConnectionAttemptTime_ = new Date().getTime();
  3822. }
  3823. else if (this.lastConnectionEstablishedTime_) {
  3824. // If we've been connected long enough, reset reconnect delay to minimum.
  3825. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3826. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3827. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3828. }
  3829. this.lastConnectionEstablishedTime_ = null;
  3830. }
  3831. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3832. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3833. reconnectDelay = Math.random() * reconnectDelay;
  3834. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3835. this.scheduleConnect_(reconnectDelay);
  3836. // Adjust reconnect delay for next time.
  3837. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3838. }
  3839. this.onConnectStatus_(false);
  3840. };
  3841. PersistentConnection.prototype.establishConnection_ = function () {
  3842. return __awaiter(this, void 0, void 0, function () {
  3843. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3844. var _this = this;
  3845. return __generator(this, function (_b) {
  3846. switch (_b.label) {
  3847. case 0:
  3848. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3849. this.log_('Making a connection attempt');
  3850. this.lastConnectionAttemptTime_ = new Date().getTime();
  3851. this.lastConnectionEstablishedTime_ = null;
  3852. onDataMessage = this.onDataMessage_.bind(this);
  3853. onReady = this.onReady_.bind(this);
  3854. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3855. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3856. lastSessionId = this.lastSessionId;
  3857. canceled_1 = false;
  3858. connection_1 = null;
  3859. closeFn = function () {
  3860. if (connection_1) {
  3861. connection_1.close();
  3862. }
  3863. else {
  3864. canceled_1 = true;
  3865. onDisconnect_1();
  3866. }
  3867. };
  3868. sendRequestFn = function (msg) {
  3869. assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3870. connection_1.sendRequest(msg);
  3871. };
  3872. this.realtime_ = {
  3873. close: closeFn,
  3874. sendRequest: sendRequestFn
  3875. };
  3876. forceRefresh = this.forceTokenRefresh_;
  3877. this.forceTokenRefresh_ = false;
  3878. _b.label = 1;
  3879. case 1:
  3880. _b.trys.push([1, 3, , 4]);
  3881. return [4 /*yield*/, Promise.all([
  3882. this.authTokenProvider_.getToken(forceRefresh),
  3883. this.appCheckTokenProvider_.getToken(forceRefresh)
  3884. ])];
  3885. case 2:
  3886. _a = __read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3887. if (!canceled_1) {
  3888. log('getToken() completed. Creating connection.');
  3889. this.authToken_ = authToken && authToken.accessToken;
  3890. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3891. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3892. /* onKill= */ function (reason) {
  3893. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3894. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3895. }, lastSessionId);
  3896. }
  3897. else {
  3898. log('getToken() completed but was canceled');
  3899. }
  3900. return [3 /*break*/, 4];
  3901. case 3:
  3902. error_1 = _b.sent();
  3903. this.log_('Failed to get token: ' + error_1);
  3904. if (!canceled_1) {
  3905. if (this.repoInfo_.nodeAdmin) {
  3906. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3907. // But getToken() may also just have temporarily failed, so we still want to
  3908. // continue retrying.
  3909. warn(error_1);
  3910. }
  3911. closeFn();
  3912. }
  3913. return [3 /*break*/, 4];
  3914. case 4: return [2 /*return*/];
  3915. }
  3916. });
  3917. });
  3918. };
  3919. PersistentConnection.prototype.interrupt = function (reason) {
  3920. log('Interrupting connection for reason: ' + reason);
  3921. this.interruptReasons_[reason] = true;
  3922. if (this.realtime_) {
  3923. this.realtime_.close();
  3924. }
  3925. else {
  3926. if (this.establishConnectionTimer_) {
  3927. clearTimeout(this.establishConnectionTimer_);
  3928. this.establishConnectionTimer_ = null;
  3929. }
  3930. if (this.connected_) {
  3931. this.onRealtimeDisconnect_();
  3932. }
  3933. }
  3934. };
  3935. PersistentConnection.prototype.resume = function (reason) {
  3936. log('Resuming connection for reason: ' + reason);
  3937. delete this.interruptReasons_[reason];
  3938. if (isEmpty(this.interruptReasons_)) {
  3939. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3940. if (!this.realtime_) {
  3941. this.scheduleConnect_(0);
  3942. }
  3943. }
  3944. };
  3945. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3946. var delta = timestamp - new Date().getTime();
  3947. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3948. };
  3949. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3950. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3951. var put = this.outstandingPuts_[i];
  3952. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3953. if (put.onComplete) {
  3954. put.onComplete('disconnect');
  3955. }
  3956. delete this.outstandingPuts_[i];
  3957. this.outstandingPutCount_--;
  3958. }
  3959. }
  3960. // Clean up array occasionally.
  3961. if (this.outstandingPutCount_ === 0) {
  3962. this.outstandingPuts_ = [];
  3963. }
  3964. };
  3965. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3966. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3967. var queryId;
  3968. if (!query) {
  3969. queryId = 'default';
  3970. }
  3971. else {
  3972. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3973. }
  3974. var listen = this.removeListen_(pathString, queryId);
  3975. if (listen && listen.onComplete) {
  3976. listen.onComplete('permission_denied');
  3977. }
  3978. };
  3979. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3980. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3981. var listen;
  3982. if (this.listens.has(normalizedPathString)) {
  3983. var map = this.listens.get(normalizedPathString);
  3984. listen = map.get(queryId);
  3985. map.delete(queryId);
  3986. if (map.size === 0) {
  3987. this.listens.delete(normalizedPathString);
  3988. }
  3989. }
  3990. else {
  3991. // all listens for this path has already been removed
  3992. listen = undefined;
  3993. }
  3994. return listen;
  3995. };
  3996. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  3997. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3998. this.authToken_ = null;
  3999. this.forceTokenRefresh_ = true;
  4000. this.realtime_.close();
  4001. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4002. // We'll wait a couple times before logging the warning / increasing the
  4003. // retry period since oauth tokens will report as "invalid" if they're
  4004. // just expired. Plus there may be transient issues that resolve themselves.
  4005. this.invalidAuthTokenCount_++;
  4006. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4007. // Set a long reconnect delay because recovery is unlikely
  4008. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4009. // Notify the auth token provider that the token is invalid, which will log
  4010. // a warning
  4011. this.authTokenProvider_.notifyForInvalidToken();
  4012. }
  4013. }
  4014. };
  4015. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4016. log('App check token revoked: ' + statusCode + '/' + explanation);
  4017. this.appCheckToken_ = null;
  4018. this.forceTokenRefresh_ = true;
  4019. // Note: We don't close the connection as the developer may not have
  4020. // enforcement enabled. The backend closes connections with enforcements.
  4021. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4022. // We'll wait a couple times before logging the warning / increasing the
  4023. // retry period since oauth tokens will report as "invalid" if they're
  4024. // just expired. Plus there may be transient issues that resolve themselves.
  4025. this.invalidAppCheckTokenCount_++;
  4026. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4027. this.appCheckTokenProvider_.notifyForInvalidToken();
  4028. }
  4029. }
  4030. };
  4031. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4032. if (this.securityDebugCallback_) {
  4033. this.securityDebugCallback_(body);
  4034. }
  4035. else {
  4036. if ('msg' in body) {
  4037. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4038. }
  4039. }
  4040. };
  4041. PersistentConnection.prototype.restoreState_ = function () {
  4042. var e_1, _a, e_2, _b;
  4043. //Re-authenticate ourselves if we have a credential stored.
  4044. this.tryAuth();
  4045. this.tryAppCheck();
  4046. try {
  4047. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4048. // make sure to send listens before puts.
  4049. for (var _c = __values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4050. var queries = _d.value;
  4051. try {
  4052. for (var _e = (e_2 = void 0, __values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4053. var listenSpec = _f.value;
  4054. this.sendListen_(listenSpec);
  4055. }
  4056. }
  4057. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4058. finally {
  4059. try {
  4060. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4061. }
  4062. finally { if (e_2) throw e_2.error; }
  4063. }
  4064. }
  4065. }
  4066. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4067. finally {
  4068. try {
  4069. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4070. }
  4071. finally { if (e_1) throw e_1.error; }
  4072. }
  4073. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4074. if (this.outstandingPuts_[i]) {
  4075. this.sendPut_(i);
  4076. }
  4077. }
  4078. while (this.onDisconnectRequestQueue_.length) {
  4079. var request = this.onDisconnectRequestQueue_.shift();
  4080. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4081. }
  4082. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4083. if (this.outstandingGets_[i]) {
  4084. this.sendGet_(i);
  4085. }
  4086. }
  4087. };
  4088. /**
  4089. * Sends client stats for first connection
  4090. */
  4091. PersistentConnection.prototype.sendConnectStats_ = function () {
  4092. var stats = {};
  4093. var clientName = 'js';
  4094. if (isNodeSdk()) {
  4095. if (this.repoInfo_.nodeAdmin) {
  4096. clientName = 'admin_node';
  4097. }
  4098. else {
  4099. clientName = 'node';
  4100. }
  4101. }
  4102. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4103. if (isMobileCordova()) {
  4104. stats['framework.cordova'] = 1;
  4105. }
  4106. else if (isReactNative()) {
  4107. stats['framework.reactnative'] = 1;
  4108. }
  4109. this.reportStats(stats);
  4110. };
  4111. PersistentConnection.prototype.shouldReconnect_ = function () {
  4112. var online = OnlineMonitor.getInstance().currentlyOnline();
  4113. return isEmpty(this.interruptReasons_) && online;
  4114. };
  4115. PersistentConnection.nextPersistentConnectionId_ = 0;
  4116. /**
  4117. * Counter for number of connections created. Mainly used for tagging in the logs
  4118. */
  4119. PersistentConnection.nextConnectionId_ = 0;
  4120. return PersistentConnection;
  4121. }(ServerActions));
  4122. /**
  4123. * @license
  4124. * Copyright 2017 Google LLC
  4125. *
  4126. * Licensed under the Apache License, Version 2.0 (the "License");
  4127. * you may not use this file except in compliance with the License.
  4128. * You may obtain a copy of the License at
  4129. *
  4130. * http://www.apache.org/licenses/LICENSE-2.0
  4131. *
  4132. * Unless required by applicable law or agreed to in writing, software
  4133. * distributed under the License is distributed on an "AS IS" BASIS,
  4134. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4135. * See the License for the specific language governing permissions and
  4136. * limitations under the License.
  4137. */
  4138. var NamedNode = /** @class */ (function () {
  4139. function NamedNode(name, node) {
  4140. this.name = name;
  4141. this.node = node;
  4142. }
  4143. NamedNode.Wrap = function (name, node) {
  4144. return new NamedNode(name, node);
  4145. };
  4146. return NamedNode;
  4147. }());
  4148. /**
  4149. * @license
  4150. * Copyright 2017 Google LLC
  4151. *
  4152. * Licensed under the Apache License, Version 2.0 (the "License");
  4153. * you may not use this file except in compliance with the License.
  4154. * You may obtain a copy of the License at
  4155. *
  4156. * http://www.apache.org/licenses/LICENSE-2.0
  4157. *
  4158. * Unless required by applicable law or agreed to in writing, software
  4159. * distributed under the License is distributed on an "AS IS" BASIS,
  4160. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4161. * See the License for the specific language governing permissions and
  4162. * limitations under the License.
  4163. */
  4164. var Index = /** @class */ (function () {
  4165. function Index() {
  4166. }
  4167. /**
  4168. * @returns A standalone comparison function for
  4169. * this index
  4170. */
  4171. Index.prototype.getCompare = function () {
  4172. return this.compare.bind(this);
  4173. };
  4174. /**
  4175. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4176. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4177. *
  4178. *
  4179. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4180. */
  4181. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4182. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4183. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4184. return this.compare(oldWrapped, newWrapped) !== 0;
  4185. };
  4186. /**
  4187. * @returns a node wrapper that will sort equal to or less than
  4188. * any other node wrapper, using this index
  4189. */
  4190. Index.prototype.minPost = function () {
  4191. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4192. return NamedNode.MIN;
  4193. };
  4194. return Index;
  4195. }());
  4196. /**
  4197. * @license
  4198. * Copyright 2017 Google LLC
  4199. *
  4200. * Licensed under the Apache License, Version 2.0 (the "License");
  4201. * you may not use this file except in compliance with the License.
  4202. * You may obtain a copy of the License at
  4203. *
  4204. * http://www.apache.org/licenses/LICENSE-2.0
  4205. *
  4206. * Unless required by applicable law or agreed to in writing, software
  4207. * distributed under the License is distributed on an "AS IS" BASIS,
  4208. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4209. * See the License for the specific language governing permissions and
  4210. * limitations under the License.
  4211. */
  4212. var __EMPTY_NODE;
  4213. var KeyIndex = /** @class */ (function (_super) {
  4214. __extends(KeyIndex, _super);
  4215. function KeyIndex() {
  4216. return _super !== null && _super.apply(this, arguments) || this;
  4217. }
  4218. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4219. get: function () {
  4220. return __EMPTY_NODE;
  4221. },
  4222. set: function (val) {
  4223. __EMPTY_NODE = val;
  4224. },
  4225. enumerable: false,
  4226. configurable: true
  4227. });
  4228. KeyIndex.prototype.compare = function (a, b) {
  4229. return nameCompare(a.name, b.name);
  4230. };
  4231. KeyIndex.prototype.isDefinedOn = function (node) {
  4232. // We could probably return true here (since every node has a key), but it's never called
  4233. // so just leaving unimplemented for now.
  4234. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4235. };
  4236. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4237. return false; // The key for a node never changes.
  4238. };
  4239. KeyIndex.prototype.minPost = function () {
  4240. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4241. return NamedNode.MIN;
  4242. };
  4243. KeyIndex.prototype.maxPost = function () {
  4244. // TODO: This should really be created once and cached in a static property, but
  4245. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4246. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4247. };
  4248. KeyIndex.prototype.makePost = function (indexValue, name) {
  4249. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4250. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4251. return new NamedNode(indexValue, __EMPTY_NODE);
  4252. };
  4253. /**
  4254. * @returns String representation for inclusion in a query spec
  4255. */
  4256. KeyIndex.prototype.toString = function () {
  4257. return '.key';
  4258. };
  4259. return KeyIndex;
  4260. }(Index));
  4261. var KEY_INDEX = new KeyIndex();
  4262. /**
  4263. * @license
  4264. * Copyright 2017 Google LLC
  4265. *
  4266. * Licensed under the Apache License, Version 2.0 (the "License");
  4267. * you may not use this file except in compliance with the License.
  4268. * You may obtain a copy of the License at
  4269. *
  4270. * http://www.apache.org/licenses/LICENSE-2.0
  4271. *
  4272. * Unless required by applicable law or agreed to in writing, software
  4273. * distributed under the License is distributed on an "AS IS" BASIS,
  4274. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4275. * See the License for the specific language governing permissions and
  4276. * limitations under the License.
  4277. */
  4278. /**
  4279. * An iterator over an LLRBNode.
  4280. */
  4281. var SortedMapIterator = /** @class */ (function () {
  4282. /**
  4283. * @param node - Node to iterate.
  4284. * @param isReverse_ - Whether or not to iterate in reverse
  4285. */
  4286. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4287. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4288. this.isReverse_ = isReverse_;
  4289. this.resultGenerator_ = resultGenerator_;
  4290. this.nodeStack_ = [];
  4291. var cmp = 1;
  4292. while (!node.isEmpty()) {
  4293. node = node;
  4294. cmp = startKey ? comparator(node.key, startKey) : 1;
  4295. // flip the comparison if we're going in reverse
  4296. if (isReverse_) {
  4297. cmp *= -1;
  4298. }
  4299. if (cmp < 0) {
  4300. // This node is less than our start key. ignore it
  4301. if (this.isReverse_) {
  4302. node = node.left;
  4303. }
  4304. else {
  4305. node = node.right;
  4306. }
  4307. }
  4308. else if (cmp === 0) {
  4309. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4310. this.nodeStack_.push(node);
  4311. break;
  4312. }
  4313. else {
  4314. // This node is greater than our start key, add it to the stack and move to the next one
  4315. this.nodeStack_.push(node);
  4316. if (this.isReverse_) {
  4317. node = node.right;
  4318. }
  4319. else {
  4320. node = node.left;
  4321. }
  4322. }
  4323. }
  4324. }
  4325. SortedMapIterator.prototype.getNext = function () {
  4326. if (this.nodeStack_.length === 0) {
  4327. return null;
  4328. }
  4329. var node = this.nodeStack_.pop();
  4330. var result;
  4331. if (this.resultGenerator_) {
  4332. result = this.resultGenerator_(node.key, node.value);
  4333. }
  4334. else {
  4335. result = { key: node.key, value: node.value };
  4336. }
  4337. if (this.isReverse_) {
  4338. node = node.left;
  4339. while (!node.isEmpty()) {
  4340. this.nodeStack_.push(node);
  4341. node = node.right;
  4342. }
  4343. }
  4344. else {
  4345. node = node.right;
  4346. while (!node.isEmpty()) {
  4347. this.nodeStack_.push(node);
  4348. node = node.left;
  4349. }
  4350. }
  4351. return result;
  4352. };
  4353. SortedMapIterator.prototype.hasNext = function () {
  4354. return this.nodeStack_.length > 0;
  4355. };
  4356. SortedMapIterator.prototype.peek = function () {
  4357. if (this.nodeStack_.length === 0) {
  4358. return null;
  4359. }
  4360. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4361. if (this.resultGenerator_) {
  4362. return this.resultGenerator_(node.key, node.value);
  4363. }
  4364. else {
  4365. return { key: node.key, value: node.value };
  4366. }
  4367. };
  4368. return SortedMapIterator;
  4369. }());
  4370. /**
  4371. * Represents a node in a Left-leaning Red-Black tree.
  4372. */
  4373. var LLRBNode = /** @class */ (function () {
  4374. /**
  4375. * @param key - Key associated with this node.
  4376. * @param value - Value associated with this node.
  4377. * @param color - Whether this node is red.
  4378. * @param left - Left child.
  4379. * @param right - Right child.
  4380. */
  4381. function LLRBNode(key, value, color, left, right) {
  4382. this.key = key;
  4383. this.value = value;
  4384. this.color = color != null ? color : LLRBNode.RED;
  4385. this.left =
  4386. left != null ? left : SortedMap.EMPTY_NODE;
  4387. this.right =
  4388. right != null ? right : SortedMap.EMPTY_NODE;
  4389. }
  4390. /**
  4391. * Returns a copy of the current node, optionally replacing pieces of it.
  4392. *
  4393. * @param key - New key for the node, or null.
  4394. * @param value - New value for the node, or null.
  4395. * @param color - New color for the node, or null.
  4396. * @param left - New left child for the node, or null.
  4397. * @param right - New right child for the node, or null.
  4398. * @returns The node copy.
  4399. */
  4400. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4401. 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);
  4402. };
  4403. /**
  4404. * @returns The total number of nodes in the tree.
  4405. */
  4406. LLRBNode.prototype.count = function () {
  4407. return this.left.count() + 1 + this.right.count();
  4408. };
  4409. /**
  4410. * @returns True if the tree is empty.
  4411. */
  4412. LLRBNode.prototype.isEmpty = function () {
  4413. return false;
  4414. };
  4415. /**
  4416. * Traverses the tree in key order and calls the specified action function
  4417. * for each node.
  4418. *
  4419. * @param action - Callback function to be called for each
  4420. * node. If it returns true, traversal is aborted.
  4421. * @returns The first truthy value returned by action, or the last falsey
  4422. * value returned by action
  4423. */
  4424. LLRBNode.prototype.inorderTraversal = function (action) {
  4425. return (this.left.inorderTraversal(action) ||
  4426. !!action(this.key, this.value) ||
  4427. this.right.inorderTraversal(action));
  4428. };
  4429. /**
  4430. * Traverses the tree in reverse key order and calls the specified action function
  4431. * for each node.
  4432. *
  4433. * @param action - Callback function to be called for each
  4434. * node. If it returns true, traversal is aborted.
  4435. * @returns True if traversal was aborted.
  4436. */
  4437. LLRBNode.prototype.reverseTraversal = function (action) {
  4438. return (this.right.reverseTraversal(action) ||
  4439. action(this.key, this.value) ||
  4440. this.left.reverseTraversal(action));
  4441. };
  4442. /**
  4443. * @returns The minimum node in the tree.
  4444. */
  4445. LLRBNode.prototype.min_ = function () {
  4446. if (this.left.isEmpty()) {
  4447. return this;
  4448. }
  4449. else {
  4450. return this.left.min_();
  4451. }
  4452. };
  4453. /**
  4454. * @returns The maximum key in the tree.
  4455. */
  4456. LLRBNode.prototype.minKey = function () {
  4457. return this.min_().key;
  4458. };
  4459. /**
  4460. * @returns The maximum key in the tree.
  4461. */
  4462. LLRBNode.prototype.maxKey = function () {
  4463. if (this.right.isEmpty()) {
  4464. return this.key;
  4465. }
  4466. else {
  4467. return this.right.maxKey();
  4468. }
  4469. };
  4470. /**
  4471. * @param key - Key to insert.
  4472. * @param value - Value to insert.
  4473. * @param comparator - Comparator.
  4474. * @returns New tree, with the key/value added.
  4475. */
  4476. LLRBNode.prototype.insert = function (key, value, comparator) {
  4477. var n = this;
  4478. var cmp = comparator(key, n.key);
  4479. if (cmp < 0) {
  4480. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4481. }
  4482. else if (cmp === 0) {
  4483. n = n.copy(null, value, null, null, null);
  4484. }
  4485. else {
  4486. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4487. }
  4488. return n.fixUp_();
  4489. };
  4490. /**
  4491. * @returns New tree, with the minimum key removed.
  4492. */
  4493. LLRBNode.prototype.removeMin_ = function () {
  4494. if (this.left.isEmpty()) {
  4495. return SortedMap.EMPTY_NODE;
  4496. }
  4497. var n = this;
  4498. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4499. n = n.moveRedLeft_();
  4500. }
  4501. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4502. return n.fixUp_();
  4503. };
  4504. /**
  4505. * @param key - The key of the item to remove.
  4506. * @param comparator - Comparator.
  4507. * @returns New tree, with the specified item removed.
  4508. */
  4509. LLRBNode.prototype.remove = function (key, comparator) {
  4510. var n, smallest;
  4511. n = this;
  4512. if (comparator(key, n.key) < 0) {
  4513. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4514. n = n.moveRedLeft_();
  4515. }
  4516. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4517. }
  4518. else {
  4519. if (n.left.isRed_()) {
  4520. n = n.rotateRight_();
  4521. }
  4522. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4523. n = n.moveRedRight_();
  4524. }
  4525. if (comparator(key, n.key) === 0) {
  4526. if (n.right.isEmpty()) {
  4527. return SortedMap.EMPTY_NODE;
  4528. }
  4529. else {
  4530. smallest = n.right.min_();
  4531. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4532. }
  4533. }
  4534. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4535. }
  4536. return n.fixUp_();
  4537. };
  4538. /**
  4539. * @returns Whether this is a RED node.
  4540. */
  4541. LLRBNode.prototype.isRed_ = function () {
  4542. return this.color;
  4543. };
  4544. /**
  4545. * @returns New tree after performing any needed rotations.
  4546. */
  4547. LLRBNode.prototype.fixUp_ = function () {
  4548. var n = this;
  4549. if (n.right.isRed_() && !n.left.isRed_()) {
  4550. n = n.rotateLeft_();
  4551. }
  4552. if (n.left.isRed_() && n.left.left.isRed_()) {
  4553. n = n.rotateRight_();
  4554. }
  4555. if (n.left.isRed_() && n.right.isRed_()) {
  4556. n = n.colorFlip_();
  4557. }
  4558. return n;
  4559. };
  4560. /**
  4561. * @returns New tree, after moveRedLeft.
  4562. */
  4563. LLRBNode.prototype.moveRedLeft_ = function () {
  4564. var n = this.colorFlip_();
  4565. if (n.right.left.isRed_()) {
  4566. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4567. n = n.rotateLeft_();
  4568. n = n.colorFlip_();
  4569. }
  4570. return n;
  4571. };
  4572. /**
  4573. * @returns New tree, after moveRedRight.
  4574. */
  4575. LLRBNode.prototype.moveRedRight_ = function () {
  4576. var n = this.colorFlip_();
  4577. if (n.left.left.isRed_()) {
  4578. n = n.rotateRight_();
  4579. n = n.colorFlip_();
  4580. }
  4581. return n;
  4582. };
  4583. /**
  4584. * @returns New tree, after rotateLeft.
  4585. */
  4586. LLRBNode.prototype.rotateLeft_ = function () {
  4587. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4588. return this.right.copy(null, null, this.color, nl, null);
  4589. };
  4590. /**
  4591. * @returns New tree, after rotateRight.
  4592. */
  4593. LLRBNode.prototype.rotateRight_ = function () {
  4594. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4595. return this.left.copy(null, null, this.color, null, nr);
  4596. };
  4597. /**
  4598. * @returns Newt ree, after colorFlip.
  4599. */
  4600. LLRBNode.prototype.colorFlip_ = function () {
  4601. var left = this.left.copy(null, null, !this.left.color, null, null);
  4602. var right = this.right.copy(null, null, !this.right.color, null, null);
  4603. return this.copy(null, null, !this.color, left, right);
  4604. };
  4605. /**
  4606. * For testing.
  4607. *
  4608. * @returns True if all is well.
  4609. */
  4610. LLRBNode.prototype.checkMaxDepth_ = function () {
  4611. var blackDepth = this.check_();
  4612. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4613. };
  4614. LLRBNode.prototype.check_ = function () {
  4615. if (this.isRed_() && this.left.isRed_()) {
  4616. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4617. }
  4618. if (this.right.isRed_()) {
  4619. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4620. }
  4621. var blackDepth = this.left.check_();
  4622. if (blackDepth !== this.right.check_()) {
  4623. throw new Error('Black depths differ');
  4624. }
  4625. else {
  4626. return blackDepth + (this.isRed_() ? 0 : 1);
  4627. }
  4628. };
  4629. LLRBNode.RED = true;
  4630. LLRBNode.BLACK = false;
  4631. return LLRBNode;
  4632. }());
  4633. /**
  4634. * Represents an empty node (a leaf node in the Red-Black Tree).
  4635. */
  4636. var LLRBEmptyNode = /** @class */ (function () {
  4637. function LLRBEmptyNode() {
  4638. }
  4639. /**
  4640. * Returns a copy of the current node.
  4641. *
  4642. * @returns The node copy.
  4643. */
  4644. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4645. return this;
  4646. };
  4647. /**
  4648. * Returns a copy of the tree, with the specified key/value added.
  4649. *
  4650. * @param key - Key to be added.
  4651. * @param value - Value to be added.
  4652. * @param comparator - Comparator.
  4653. * @returns New tree, with item added.
  4654. */
  4655. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4656. return new LLRBNode(key, value, null);
  4657. };
  4658. /**
  4659. * Returns a copy of the tree, with the specified key removed.
  4660. *
  4661. * @param key - The key to remove.
  4662. * @param comparator - Comparator.
  4663. * @returns New tree, with item removed.
  4664. */
  4665. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4666. return this;
  4667. };
  4668. /**
  4669. * @returns The total number of nodes in the tree.
  4670. */
  4671. LLRBEmptyNode.prototype.count = function () {
  4672. return 0;
  4673. };
  4674. /**
  4675. * @returns True if the tree is empty.
  4676. */
  4677. LLRBEmptyNode.prototype.isEmpty = function () {
  4678. return true;
  4679. };
  4680. /**
  4681. * Traverses the tree in key order and calls the specified action function
  4682. * for each node.
  4683. *
  4684. * @param action - Callback function to be called for each
  4685. * node. If it returns true, traversal is aborted.
  4686. * @returns True if traversal was aborted.
  4687. */
  4688. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4689. return false;
  4690. };
  4691. /**
  4692. * Traverses the tree in reverse key order and calls the specified action function
  4693. * for each node.
  4694. *
  4695. * @param action - Callback function to be called for each
  4696. * node. If it returns true, traversal is aborted.
  4697. * @returns True if traversal was aborted.
  4698. */
  4699. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4700. return false;
  4701. };
  4702. LLRBEmptyNode.prototype.minKey = function () {
  4703. return null;
  4704. };
  4705. LLRBEmptyNode.prototype.maxKey = function () {
  4706. return null;
  4707. };
  4708. LLRBEmptyNode.prototype.check_ = function () {
  4709. return 0;
  4710. };
  4711. /**
  4712. * @returns Whether this node is red.
  4713. */
  4714. LLRBEmptyNode.prototype.isRed_ = function () {
  4715. return false;
  4716. };
  4717. return LLRBEmptyNode;
  4718. }());
  4719. /**
  4720. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4721. * tree.
  4722. */
  4723. var SortedMap = /** @class */ (function () {
  4724. /**
  4725. * @param comparator_ - Key comparator.
  4726. * @param root_ - Optional root node for the map.
  4727. */
  4728. function SortedMap(comparator_, root_) {
  4729. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4730. this.comparator_ = comparator_;
  4731. this.root_ = root_;
  4732. }
  4733. /**
  4734. * Returns a copy of the map, with the specified key/value added or replaced.
  4735. * (TODO: We should perhaps rename this method to 'put')
  4736. *
  4737. * @param key - Key to be added.
  4738. * @param value - Value to be added.
  4739. * @returns New map, with item added.
  4740. */
  4741. SortedMap.prototype.insert = function (key, value) {
  4742. return new SortedMap(this.comparator_, this.root_
  4743. .insert(key, value, this.comparator_)
  4744. .copy(null, null, LLRBNode.BLACK, null, null));
  4745. };
  4746. /**
  4747. * Returns a copy of the map, with the specified key removed.
  4748. *
  4749. * @param key - The key to remove.
  4750. * @returns New map, with item removed.
  4751. */
  4752. SortedMap.prototype.remove = function (key) {
  4753. return new SortedMap(this.comparator_, this.root_
  4754. .remove(key, this.comparator_)
  4755. .copy(null, null, LLRBNode.BLACK, null, null));
  4756. };
  4757. /**
  4758. * Returns the value of the node with the given key, or null.
  4759. *
  4760. * @param key - The key to look up.
  4761. * @returns The value of the node with the given key, or null if the
  4762. * key doesn't exist.
  4763. */
  4764. SortedMap.prototype.get = function (key) {
  4765. var cmp;
  4766. var node = this.root_;
  4767. while (!node.isEmpty()) {
  4768. cmp = this.comparator_(key, node.key);
  4769. if (cmp === 0) {
  4770. return node.value;
  4771. }
  4772. else if (cmp < 0) {
  4773. node = node.left;
  4774. }
  4775. else if (cmp > 0) {
  4776. node = node.right;
  4777. }
  4778. }
  4779. return null;
  4780. };
  4781. /**
  4782. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4783. * @param key - The key to find the predecessor of
  4784. * @returns The predecessor key.
  4785. */
  4786. SortedMap.prototype.getPredecessorKey = function (key) {
  4787. var cmp, node = this.root_, rightParent = null;
  4788. while (!node.isEmpty()) {
  4789. cmp = this.comparator_(key, node.key);
  4790. if (cmp === 0) {
  4791. if (!node.left.isEmpty()) {
  4792. node = node.left;
  4793. while (!node.right.isEmpty()) {
  4794. node = node.right;
  4795. }
  4796. return node.key;
  4797. }
  4798. else if (rightParent) {
  4799. return rightParent.key;
  4800. }
  4801. else {
  4802. return null; // first item.
  4803. }
  4804. }
  4805. else if (cmp < 0) {
  4806. node = node.left;
  4807. }
  4808. else if (cmp > 0) {
  4809. rightParent = node;
  4810. node = node.right;
  4811. }
  4812. }
  4813. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4814. };
  4815. /**
  4816. * @returns True if the map is empty.
  4817. */
  4818. SortedMap.prototype.isEmpty = function () {
  4819. return this.root_.isEmpty();
  4820. };
  4821. /**
  4822. * @returns The total number of nodes in the map.
  4823. */
  4824. SortedMap.prototype.count = function () {
  4825. return this.root_.count();
  4826. };
  4827. /**
  4828. * @returns The minimum key in the map.
  4829. */
  4830. SortedMap.prototype.minKey = function () {
  4831. return this.root_.minKey();
  4832. };
  4833. /**
  4834. * @returns The maximum key in the map.
  4835. */
  4836. SortedMap.prototype.maxKey = function () {
  4837. return this.root_.maxKey();
  4838. };
  4839. /**
  4840. * Traverses the map in key order and calls the specified action function
  4841. * for each key/value pair.
  4842. *
  4843. * @param action - Callback function to be called
  4844. * for each key/value pair. If action returns true, traversal is aborted.
  4845. * @returns The first truthy value returned by action, or the last falsey
  4846. * value returned by action
  4847. */
  4848. SortedMap.prototype.inorderTraversal = function (action) {
  4849. return this.root_.inorderTraversal(action);
  4850. };
  4851. /**
  4852. * Traverses the map in reverse key order and calls the specified action function
  4853. * for each key/value pair.
  4854. *
  4855. * @param action - Callback function to be called
  4856. * for each key/value pair. If action returns true, traversal is aborted.
  4857. * @returns True if the traversal was aborted.
  4858. */
  4859. SortedMap.prototype.reverseTraversal = function (action) {
  4860. return this.root_.reverseTraversal(action);
  4861. };
  4862. /**
  4863. * Returns an iterator over the SortedMap.
  4864. * @returns The iterator.
  4865. */
  4866. SortedMap.prototype.getIterator = function (resultGenerator) {
  4867. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4868. };
  4869. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4870. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4871. };
  4872. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4873. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4874. };
  4875. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4876. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4877. };
  4878. /**
  4879. * Always use the same empty node, to reduce memory.
  4880. */
  4881. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4882. return SortedMap;
  4883. }());
  4884. /**
  4885. * @license
  4886. * Copyright 2017 Google LLC
  4887. *
  4888. * Licensed under the Apache License, Version 2.0 (the "License");
  4889. * you may not use this file except in compliance with the License.
  4890. * You may obtain a copy of the License at
  4891. *
  4892. * http://www.apache.org/licenses/LICENSE-2.0
  4893. *
  4894. * Unless required by applicable law or agreed to in writing, software
  4895. * distributed under the License is distributed on an "AS IS" BASIS,
  4896. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4897. * See the License for the specific language governing permissions and
  4898. * limitations under the License.
  4899. */
  4900. function NAME_ONLY_COMPARATOR(left, right) {
  4901. return nameCompare(left.name, right.name);
  4902. }
  4903. function NAME_COMPARATOR(left, right) {
  4904. return nameCompare(left, right);
  4905. }
  4906. /**
  4907. * @license
  4908. * Copyright 2017 Google LLC
  4909. *
  4910. * Licensed under the Apache License, Version 2.0 (the "License");
  4911. * you may not use this file except in compliance with the License.
  4912. * You may obtain a copy of the License at
  4913. *
  4914. * http://www.apache.org/licenses/LICENSE-2.0
  4915. *
  4916. * Unless required by applicable law or agreed to in writing, software
  4917. * distributed under the License is distributed on an "AS IS" BASIS,
  4918. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4919. * See the License for the specific language governing permissions and
  4920. * limitations under the License.
  4921. */
  4922. var MAX_NODE$2;
  4923. function setMaxNode$1(val) {
  4924. MAX_NODE$2 = val;
  4925. }
  4926. var priorityHashText = function (priority) {
  4927. if (typeof priority === 'number') {
  4928. return 'number:' + doubleToIEEE754String(priority);
  4929. }
  4930. else {
  4931. return 'string:' + priority;
  4932. }
  4933. };
  4934. /**
  4935. * Validates that a priority snapshot Node is valid.
  4936. */
  4937. var validatePriorityNode = function (priorityNode) {
  4938. if (priorityNode.isLeafNode()) {
  4939. var val = priorityNode.val();
  4940. assert(typeof val === 'string' ||
  4941. typeof val === 'number' ||
  4942. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4943. }
  4944. else {
  4945. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4946. }
  4947. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4948. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4949. };
  4950. /**
  4951. * @license
  4952. * Copyright 2017 Google LLC
  4953. *
  4954. * Licensed under the Apache License, Version 2.0 (the "License");
  4955. * you may not use this file except in compliance with the License.
  4956. * You may obtain a copy of the License at
  4957. *
  4958. * http://www.apache.org/licenses/LICENSE-2.0
  4959. *
  4960. * Unless required by applicable law or agreed to in writing, software
  4961. * distributed under the License is distributed on an "AS IS" BASIS,
  4962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4963. * See the License for the specific language governing permissions and
  4964. * limitations under the License.
  4965. */
  4966. var __childrenNodeConstructor;
  4967. /**
  4968. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4969. * implements Node and stores the value of the node (a string,
  4970. * number, or boolean) accessible via getValue().
  4971. */
  4972. var LeafNode = /** @class */ (function () {
  4973. /**
  4974. * @param value_ - The value to store in this leaf node. The object type is
  4975. * possible in the event of a deferred value
  4976. * @param priorityNode_ - The priority of this node.
  4977. */
  4978. function LeafNode(value_, priorityNode_) {
  4979. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4980. this.value_ = value_;
  4981. this.priorityNode_ = priorityNode_;
  4982. this.lazyHash_ = null;
  4983. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4984. validatePriorityNode(this.priorityNode_);
  4985. }
  4986. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  4987. get: function () {
  4988. return __childrenNodeConstructor;
  4989. },
  4990. set: function (val) {
  4991. __childrenNodeConstructor = val;
  4992. },
  4993. enumerable: false,
  4994. configurable: true
  4995. });
  4996. /** @inheritDoc */
  4997. LeafNode.prototype.isLeafNode = function () {
  4998. return true;
  4999. };
  5000. /** @inheritDoc */
  5001. LeafNode.prototype.getPriority = function () {
  5002. return this.priorityNode_;
  5003. };
  5004. /** @inheritDoc */
  5005. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5006. return new LeafNode(this.value_, newPriorityNode);
  5007. };
  5008. /** @inheritDoc */
  5009. LeafNode.prototype.getImmediateChild = function (childName) {
  5010. // Hack to treat priority as a regular child
  5011. if (childName === '.priority') {
  5012. return this.priorityNode_;
  5013. }
  5014. else {
  5015. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5016. }
  5017. };
  5018. /** @inheritDoc */
  5019. LeafNode.prototype.getChild = function (path) {
  5020. if (pathIsEmpty(path)) {
  5021. return this;
  5022. }
  5023. else if (pathGetFront(path) === '.priority') {
  5024. return this.priorityNode_;
  5025. }
  5026. else {
  5027. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5028. }
  5029. };
  5030. LeafNode.prototype.hasChild = function () {
  5031. return false;
  5032. };
  5033. /** @inheritDoc */
  5034. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5035. return null;
  5036. };
  5037. /** @inheritDoc */
  5038. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5039. if (childName === '.priority') {
  5040. return this.updatePriority(newChildNode);
  5041. }
  5042. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5043. return this;
  5044. }
  5045. else {
  5046. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5047. }
  5048. };
  5049. /** @inheritDoc */
  5050. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5051. var front = pathGetFront(path);
  5052. if (front === null) {
  5053. return newChildNode;
  5054. }
  5055. else if (newChildNode.isEmpty() && front !== '.priority') {
  5056. return this;
  5057. }
  5058. else {
  5059. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5060. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5061. }
  5062. };
  5063. /** @inheritDoc */
  5064. LeafNode.prototype.isEmpty = function () {
  5065. return false;
  5066. };
  5067. /** @inheritDoc */
  5068. LeafNode.prototype.numChildren = function () {
  5069. return 0;
  5070. };
  5071. /** @inheritDoc */
  5072. LeafNode.prototype.forEachChild = function (index, action) {
  5073. return false;
  5074. };
  5075. LeafNode.prototype.val = function (exportFormat) {
  5076. if (exportFormat && !this.getPriority().isEmpty()) {
  5077. return {
  5078. '.value': this.getValue(),
  5079. '.priority': this.getPriority().val()
  5080. };
  5081. }
  5082. else {
  5083. return this.getValue();
  5084. }
  5085. };
  5086. /** @inheritDoc */
  5087. LeafNode.prototype.hash = function () {
  5088. if (this.lazyHash_ === null) {
  5089. var toHash = '';
  5090. if (!this.priorityNode_.isEmpty()) {
  5091. toHash +=
  5092. 'priority:' +
  5093. priorityHashText(this.priorityNode_.val()) +
  5094. ':';
  5095. }
  5096. var type = typeof this.value_;
  5097. toHash += type + ':';
  5098. if (type === 'number') {
  5099. toHash += doubleToIEEE754String(this.value_);
  5100. }
  5101. else {
  5102. toHash += this.value_;
  5103. }
  5104. this.lazyHash_ = sha1(toHash);
  5105. }
  5106. return this.lazyHash_;
  5107. };
  5108. /**
  5109. * Returns the value of the leaf node.
  5110. * @returns The value of the node.
  5111. */
  5112. LeafNode.prototype.getValue = function () {
  5113. return this.value_;
  5114. };
  5115. LeafNode.prototype.compareTo = function (other) {
  5116. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5117. return 1;
  5118. }
  5119. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5120. return -1;
  5121. }
  5122. else {
  5123. assert(other.isLeafNode(), 'Unknown node type');
  5124. return this.compareToLeafNode_(other);
  5125. }
  5126. };
  5127. /**
  5128. * Comparison specifically for two leaf nodes
  5129. */
  5130. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5131. var otherLeafType = typeof otherLeaf.value_;
  5132. var thisLeafType = typeof this.value_;
  5133. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5134. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5135. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5136. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5137. if (otherIndex === thisIndex) {
  5138. // Same type, compare values
  5139. if (thisLeafType === 'object') {
  5140. // Deferred value nodes are all equal, but we should also never get to this point...
  5141. return 0;
  5142. }
  5143. else {
  5144. // Note that this works because true > false, all others are number or string comparisons
  5145. if (this.value_ < otherLeaf.value_) {
  5146. return -1;
  5147. }
  5148. else if (this.value_ === otherLeaf.value_) {
  5149. return 0;
  5150. }
  5151. else {
  5152. return 1;
  5153. }
  5154. }
  5155. }
  5156. else {
  5157. return thisIndex - otherIndex;
  5158. }
  5159. };
  5160. LeafNode.prototype.withIndex = function () {
  5161. return this;
  5162. };
  5163. LeafNode.prototype.isIndexed = function () {
  5164. return true;
  5165. };
  5166. LeafNode.prototype.equals = function (other) {
  5167. if (other === this) {
  5168. return true;
  5169. }
  5170. else if (other.isLeafNode()) {
  5171. var otherLeaf = other;
  5172. return (this.value_ === otherLeaf.value_ &&
  5173. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5174. }
  5175. else {
  5176. return false;
  5177. }
  5178. };
  5179. /**
  5180. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5181. * the same type, the comparison falls back to their value
  5182. */
  5183. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5184. return LeafNode;
  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. var nodeFromJSON$1;
  5203. var MAX_NODE$1;
  5204. function setNodeFromJSON(val) {
  5205. nodeFromJSON$1 = val;
  5206. }
  5207. function setMaxNode(val) {
  5208. MAX_NODE$1 = val;
  5209. }
  5210. var PriorityIndex = /** @class */ (function (_super) {
  5211. __extends(PriorityIndex, _super);
  5212. function PriorityIndex() {
  5213. return _super !== null && _super.apply(this, arguments) || this;
  5214. }
  5215. PriorityIndex.prototype.compare = function (a, b) {
  5216. var aPriority = a.node.getPriority();
  5217. var bPriority = b.node.getPriority();
  5218. var indexCmp = aPriority.compareTo(bPriority);
  5219. if (indexCmp === 0) {
  5220. return nameCompare(a.name, b.name);
  5221. }
  5222. else {
  5223. return indexCmp;
  5224. }
  5225. };
  5226. PriorityIndex.prototype.isDefinedOn = function (node) {
  5227. return !node.getPriority().isEmpty();
  5228. };
  5229. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5230. return !oldNode.getPriority().equals(newNode.getPriority());
  5231. };
  5232. PriorityIndex.prototype.minPost = function () {
  5233. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5234. return NamedNode.MIN;
  5235. };
  5236. PriorityIndex.prototype.maxPost = function () {
  5237. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5238. };
  5239. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5240. var priorityNode = nodeFromJSON$1(indexValue);
  5241. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5242. };
  5243. /**
  5244. * @returns String representation for inclusion in a query spec
  5245. */
  5246. PriorityIndex.prototype.toString = function () {
  5247. return '.priority';
  5248. };
  5249. return PriorityIndex;
  5250. }(Index));
  5251. var PRIORITY_INDEX = new PriorityIndex();
  5252. /**
  5253. * @license
  5254. * Copyright 2017 Google LLC
  5255. *
  5256. * Licensed under the Apache License, Version 2.0 (the "License");
  5257. * you may not use this file except in compliance with the License.
  5258. * You may obtain a copy of the License at
  5259. *
  5260. * http://www.apache.org/licenses/LICENSE-2.0
  5261. *
  5262. * Unless required by applicable law or agreed to in writing, software
  5263. * distributed under the License is distributed on an "AS IS" BASIS,
  5264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5265. * See the License for the specific language governing permissions and
  5266. * limitations under the License.
  5267. */
  5268. var LOG_2 = Math.log(2);
  5269. var Base12Num = /** @class */ (function () {
  5270. function Base12Num(length) {
  5271. var logBase2 = function (num) {
  5272. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5273. return parseInt((Math.log(num) / LOG_2), 10);
  5274. };
  5275. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5276. this.count = logBase2(length + 1);
  5277. this.current_ = this.count - 1;
  5278. var mask = bitMask(this.count);
  5279. this.bits_ = (length + 1) & mask;
  5280. }
  5281. Base12Num.prototype.nextBitIsOne = function () {
  5282. //noinspection JSBitwiseOperatorUsage
  5283. var result = !(this.bits_ & (0x1 << this.current_));
  5284. this.current_--;
  5285. return result;
  5286. };
  5287. return Base12Num;
  5288. }());
  5289. /**
  5290. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5291. * function
  5292. *
  5293. * Uses the algorithm described in the paper linked here:
  5294. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5295. *
  5296. * @param childList - Unsorted list of children
  5297. * @param cmp - The comparison method to be used
  5298. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5299. * type is not NamedNode
  5300. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5301. */
  5302. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5303. childList.sort(cmp);
  5304. var buildBalancedTree = function (low, high) {
  5305. var length = high - low;
  5306. var namedNode;
  5307. var key;
  5308. if (length === 0) {
  5309. return null;
  5310. }
  5311. else if (length === 1) {
  5312. namedNode = childList[low];
  5313. key = keyFn ? keyFn(namedNode) : namedNode;
  5314. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5315. }
  5316. else {
  5317. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5318. var middle = parseInt((length / 2), 10) + low;
  5319. var left = buildBalancedTree(low, middle);
  5320. var right = buildBalancedTree(middle + 1, high);
  5321. namedNode = childList[middle];
  5322. key = keyFn ? keyFn(namedNode) : namedNode;
  5323. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5324. }
  5325. };
  5326. var buildFrom12Array = function (base12) {
  5327. var node = null;
  5328. var root = null;
  5329. var index = childList.length;
  5330. var buildPennant = function (chunkSize, color) {
  5331. var low = index - chunkSize;
  5332. var high = index;
  5333. index -= chunkSize;
  5334. var childTree = buildBalancedTree(low + 1, high);
  5335. var namedNode = childList[low];
  5336. var key = keyFn ? keyFn(namedNode) : namedNode;
  5337. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5338. };
  5339. var attachPennant = function (pennant) {
  5340. if (node) {
  5341. node.left = pennant;
  5342. node = pennant;
  5343. }
  5344. else {
  5345. root = pennant;
  5346. node = pennant;
  5347. }
  5348. };
  5349. for (var i = 0; i < base12.count; ++i) {
  5350. var isOne = base12.nextBitIsOne();
  5351. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5352. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5353. if (isOne) {
  5354. buildPennant(chunkSize, LLRBNode.BLACK);
  5355. }
  5356. else {
  5357. // current == 2
  5358. buildPennant(chunkSize, LLRBNode.BLACK);
  5359. buildPennant(chunkSize, LLRBNode.RED);
  5360. }
  5361. }
  5362. return root;
  5363. };
  5364. var base12 = new Base12Num(childList.length);
  5365. var root = buildFrom12Array(base12);
  5366. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5367. return new SortedMap(mapSortFn || cmp, root);
  5368. };
  5369. /**
  5370. * @license
  5371. * Copyright 2017 Google LLC
  5372. *
  5373. * Licensed under the Apache License, Version 2.0 (the "License");
  5374. * you may not use this file except in compliance with the License.
  5375. * You may obtain a copy of the License at
  5376. *
  5377. * http://www.apache.org/licenses/LICENSE-2.0
  5378. *
  5379. * Unless required by applicable law or agreed to in writing, software
  5380. * distributed under the License is distributed on an "AS IS" BASIS,
  5381. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5382. * See the License for the specific language governing permissions and
  5383. * limitations under the License.
  5384. */
  5385. var _defaultIndexMap;
  5386. var fallbackObject = {};
  5387. var IndexMap = /** @class */ (function () {
  5388. function IndexMap(indexes_, indexSet_) {
  5389. this.indexes_ = indexes_;
  5390. this.indexSet_ = indexSet_;
  5391. }
  5392. Object.defineProperty(IndexMap, "Default", {
  5393. /**
  5394. * The default IndexMap for nodes without a priority
  5395. */
  5396. get: function () {
  5397. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5398. _defaultIndexMap =
  5399. _defaultIndexMap ||
  5400. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5401. return _defaultIndexMap;
  5402. },
  5403. enumerable: false,
  5404. configurable: true
  5405. });
  5406. IndexMap.prototype.get = function (indexKey) {
  5407. var sortedMap = safeGet(this.indexes_, indexKey);
  5408. if (!sortedMap) {
  5409. throw new Error('No index defined for ' + indexKey);
  5410. }
  5411. if (sortedMap instanceof SortedMap) {
  5412. return sortedMap;
  5413. }
  5414. else {
  5415. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5416. // regular child map
  5417. return null;
  5418. }
  5419. };
  5420. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5421. return contains(this.indexSet_, indexDefinition.toString());
  5422. };
  5423. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5424. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5425. var childList = [];
  5426. var sawIndexedValue = false;
  5427. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5428. var next = iter.getNext();
  5429. while (next) {
  5430. sawIndexedValue =
  5431. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5432. childList.push(next);
  5433. next = iter.getNext();
  5434. }
  5435. var newIndex;
  5436. if (sawIndexedValue) {
  5437. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5438. }
  5439. else {
  5440. newIndex = fallbackObject;
  5441. }
  5442. var indexName = indexDefinition.toString();
  5443. var newIndexSet = __assign({}, this.indexSet_);
  5444. newIndexSet[indexName] = indexDefinition;
  5445. var newIndexes = __assign({}, this.indexes_);
  5446. newIndexes[indexName] = newIndex;
  5447. return new IndexMap(newIndexes, newIndexSet);
  5448. };
  5449. /**
  5450. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5451. */
  5452. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5453. var _this = this;
  5454. var newIndexes = map(this.indexes_, function (indexedChildren, indexName) {
  5455. var index = safeGet(_this.indexSet_, indexName);
  5456. assert(index, 'Missing index implementation for ' + indexName);
  5457. if (indexedChildren === fallbackObject) {
  5458. // Check to see if we need to index everything
  5459. if (index.isDefinedOn(namedNode.node)) {
  5460. // We need to build this index
  5461. var childList = [];
  5462. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5463. var next = iter.getNext();
  5464. while (next) {
  5465. if (next.name !== namedNode.name) {
  5466. childList.push(next);
  5467. }
  5468. next = iter.getNext();
  5469. }
  5470. childList.push(namedNode);
  5471. return buildChildSet(childList, index.getCompare());
  5472. }
  5473. else {
  5474. // No change, this remains a fallback
  5475. return fallbackObject;
  5476. }
  5477. }
  5478. else {
  5479. var existingSnap = existingChildren.get(namedNode.name);
  5480. var newChildren = indexedChildren;
  5481. if (existingSnap) {
  5482. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5483. }
  5484. return newChildren.insert(namedNode, namedNode.node);
  5485. }
  5486. });
  5487. return new IndexMap(newIndexes, this.indexSet_);
  5488. };
  5489. /**
  5490. * Create a new IndexMap instance with the given value removed
  5491. */
  5492. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5493. var newIndexes = map(this.indexes_, function (indexedChildren) {
  5494. if (indexedChildren === fallbackObject) {
  5495. // This is the fallback. Just return it, nothing to do in this case
  5496. return indexedChildren;
  5497. }
  5498. else {
  5499. var existingSnap = existingChildren.get(namedNode.name);
  5500. if (existingSnap) {
  5501. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5502. }
  5503. else {
  5504. // No record of this child
  5505. return indexedChildren;
  5506. }
  5507. }
  5508. });
  5509. return new IndexMap(newIndexes, this.indexSet_);
  5510. };
  5511. return IndexMap;
  5512. }());
  5513. /**
  5514. * @license
  5515. * Copyright 2017 Google LLC
  5516. *
  5517. * Licensed under the Apache License, Version 2.0 (the "License");
  5518. * you may not use this file except in compliance with the License.
  5519. * You may obtain a copy of the License at
  5520. *
  5521. * http://www.apache.org/licenses/LICENSE-2.0
  5522. *
  5523. * Unless required by applicable law or agreed to in writing, software
  5524. * distributed under the License is distributed on an "AS IS" BASIS,
  5525. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5526. * See the License for the specific language governing permissions and
  5527. * limitations under the License.
  5528. */
  5529. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5530. var EMPTY_NODE;
  5531. /**
  5532. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5533. * (i.e. nodes with children). It implements Node and stores the
  5534. * list of children in the children property, sorted by child name.
  5535. */
  5536. var ChildrenNode = /** @class */ (function () {
  5537. /**
  5538. * @param children_ - List of children of this node..
  5539. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5540. */
  5541. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5542. this.children_ = children_;
  5543. this.priorityNode_ = priorityNode_;
  5544. this.indexMap_ = indexMap_;
  5545. this.lazyHash_ = null;
  5546. /**
  5547. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5548. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5549. * class instead of an empty ChildrenNode.
  5550. */
  5551. if (this.priorityNode_) {
  5552. validatePriorityNode(this.priorityNode_);
  5553. }
  5554. if (this.children_.isEmpty()) {
  5555. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5556. }
  5557. }
  5558. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5559. get: function () {
  5560. return (EMPTY_NODE ||
  5561. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5562. },
  5563. enumerable: false,
  5564. configurable: true
  5565. });
  5566. /** @inheritDoc */
  5567. ChildrenNode.prototype.isLeafNode = function () {
  5568. return false;
  5569. };
  5570. /** @inheritDoc */
  5571. ChildrenNode.prototype.getPriority = function () {
  5572. return this.priorityNode_ || EMPTY_NODE;
  5573. };
  5574. /** @inheritDoc */
  5575. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5576. if (this.children_.isEmpty()) {
  5577. // Don't allow priorities on empty nodes
  5578. return this;
  5579. }
  5580. else {
  5581. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5582. }
  5583. };
  5584. /** @inheritDoc */
  5585. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5586. // Hack to treat priority as a regular child
  5587. if (childName === '.priority') {
  5588. return this.getPriority();
  5589. }
  5590. else {
  5591. var child = this.children_.get(childName);
  5592. return child === null ? EMPTY_NODE : child;
  5593. }
  5594. };
  5595. /** @inheritDoc */
  5596. ChildrenNode.prototype.getChild = function (path) {
  5597. var front = pathGetFront(path);
  5598. if (front === null) {
  5599. return this;
  5600. }
  5601. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5602. };
  5603. /** @inheritDoc */
  5604. ChildrenNode.prototype.hasChild = function (childName) {
  5605. return this.children_.get(childName) !== null;
  5606. };
  5607. /** @inheritDoc */
  5608. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5609. assert(newChildNode, 'We should always be passing snapshot nodes');
  5610. if (childName === '.priority') {
  5611. return this.updatePriority(newChildNode);
  5612. }
  5613. else {
  5614. var namedNode = new NamedNode(childName, newChildNode);
  5615. var newChildren = void 0, newIndexMap = void 0;
  5616. if (newChildNode.isEmpty()) {
  5617. newChildren = this.children_.remove(childName);
  5618. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5619. }
  5620. else {
  5621. newChildren = this.children_.insert(childName, newChildNode);
  5622. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5623. }
  5624. var newPriority = newChildren.isEmpty()
  5625. ? EMPTY_NODE
  5626. : this.priorityNode_;
  5627. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5628. }
  5629. };
  5630. /** @inheritDoc */
  5631. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5632. var front = pathGetFront(path);
  5633. if (front === null) {
  5634. return newChildNode;
  5635. }
  5636. else {
  5637. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5638. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5639. return this.updateImmediateChild(front, newImmediateChild);
  5640. }
  5641. };
  5642. /** @inheritDoc */
  5643. ChildrenNode.prototype.isEmpty = function () {
  5644. return this.children_.isEmpty();
  5645. };
  5646. /** @inheritDoc */
  5647. ChildrenNode.prototype.numChildren = function () {
  5648. return this.children_.count();
  5649. };
  5650. /** @inheritDoc */
  5651. ChildrenNode.prototype.val = function (exportFormat) {
  5652. if (this.isEmpty()) {
  5653. return null;
  5654. }
  5655. var obj = {};
  5656. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5657. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5658. obj[key] = childNode.val(exportFormat);
  5659. numKeys++;
  5660. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5661. maxKey = Math.max(maxKey, Number(key));
  5662. }
  5663. else {
  5664. allIntegerKeys = false;
  5665. }
  5666. });
  5667. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5668. // convert to array.
  5669. var array = [];
  5670. // eslint-disable-next-line guard-for-in
  5671. for (var key in obj) {
  5672. array[key] = obj[key];
  5673. }
  5674. return array;
  5675. }
  5676. else {
  5677. if (exportFormat && !this.getPriority().isEmpty()) {
  5678. obj['.priority'] = this.getPriority().val();
  5679. }
  5680. return obj;
  5681. }
  5682. };
  5683. /** @inheritDoc */
  5684. ChildrenNode.prototype.hash = function () {
  5685. if (this.lazyHash_ === null) {
  5686. var toHash_1 = '';
  5687. if (!this.getPriority().isEmpty()) {
  5688. toHash_1 +=
  5689. 'priority:' +
  5690. priorityHashText(this.getPriority().val()) +
  5691. ':';
  5692. }
  5693. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5694. var childHash = childNode.hash();
  5695. if (childHash !== '') {
  5696. toHash_1 += ':' + key + ':' + childHash;
  5697. }
  5698. });
  5699. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5700. }
  5701. return this.lazyHash_;
  5702. };
  5703. /** @inheritDoc */
  5704. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5705. var idx = this.resolveIndex_(index);
  5706. if (idx) {
  5707. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5708. return predecessor ? predecessor.name : null;
  5709. }
  5710. else {
  5711. return this.children_.getPredecessorKey(childName);
  5712. }
  5713. };
  5714. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5715. var idx = this.resolveIndex_(indexDefinition);
  5716. if (idx) {
  5717. var minKey = idx.minKey();
  5718. return minKey && minKey.name;
  5719. }
  5720. else {
  5721. return this.children_.minKey();
  5722. }
  5723. };
  5724. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5725. var minKey = this.getFirstChildName(indexDefinition);
  5726. if (minKey) {
  5727. return new NamedNode(minKey, this.children_.get(minKey));
  5728. }
  5729. else {
  5730. return null;
  5731. }
  5732. };
  5733. /**
  5734. * Given an index, return the key name of the largest value we have, according to that index
  5735. */
  5736. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5737. var idx = this.resolveIndex_(indexDefinition);
  5738. if (idx) {
  5739. var maxKey = idx.maxKey();
  5740. return maxKey && maxKey.name;
  5741. }
  5742. else {
  5743. return this.children_.maxKey();
  5744. }
  5745. };
  5746. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5747. var maxKey = this.getLastChildName(indexDefinition);
  5748. if (maxKey) {
  5749. return new NamedNode(maxKey, this.children_.get(maxKey));
  5750. }
  5751. else {
  5752. return null;
  5753. }
  5754. };
  5755. ChildrenNode.prototype.forEachChild = function (index, action) {
  5756. var idx = this.resolveIndex_(index);
  5757. if (idx) {
  5758. return idx.inorderTraversal(function (wrappedNode) {
  5759. return action(wrappedNode.name, wrappedNode.node);
  5760. });
  5761. }
  5762. else {
  5763. return this.children_.inorderTraversal(action);
  5764. }
  5765. };
  5766. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5767. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5768. };
  5769. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5770. var idx = this.resolveIndex_(indexDefinition);
  5771. if (idx) {
  5772. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5773. }
  5774. else {
  5775. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5776. var next = iterator.peek();
  5777. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5778. iterator.getNext();
  5779. next = iterator.peek();
  5780. }
  5781. return iterator;
  5782. }
  5783. };
  5784. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5785. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5786. };
  5787. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5788. var idx = this.resolveIndex_(indexDefinition);
  5789. if (idx) {
  5790. return idx.getReverseIteratorFrom(endPost, function (key) {
  5791. return key;
  5792. });
  5793. }
  5794. else {
  5795. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5796. var next = iterator.peek();
  5797. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5798. iterator.getNext();
  5799. next = iterator.peek();
  5800. }
  5801. return iterator;
  5802. }
  5803. };
  5804. ChildrenNode.prototype.compareTo = function (other) {
  5805. if (this.isEmpty()) {
  5806. if (other.isEmpty()) {
  5807. return 0;
  5808. }
  5809. else {
  5810. return -1;
  5811. }
  5812. }
  5813. else if (other.isLeafNode() || other.isEmpty()) {
  5814. return 1;
  5815. }
  5816. else if (other === MAX_NODE) {
  5817. return -1;
  5818. }
  5819. else {
  5820. // Must be another node with children.
  5821. return 0;
  5822. }
  5823. };
  5824. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5825. if (indexDefinition === KEY_INDEX ||
  5826. this.indexMap_.hasIndex(indexDefinition)) {
  5827. return this;
  5828. }
  5829. else {
  5830. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5831. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5832. }
  5833. };
  5834. ChildrenNode.prototype.isIndexed = function (index) {
  5835. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5836. };
  5837. ChildrenNode.prototype.equals = function (other) {
  5838. if (other === this) {
  5839. return true;
  5840. }
  5841. else if (other.isLeafNode()) {
  5842. return false;
  5843. }
  5844. else {
  5845. var otherChildrenNode = other;
  5846. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5847. return false;
  5848. }
  5849. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5850. var thisIter = this.getIterator(PRIORITY_INDEX);
  5851. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5852. var thisCurrent = thisIter.getNext();
  5853. var otherCurrent = otherIter.getNext();
  5854. while (thisCurrent && otherCurrent) {
  5855. if (thisCurrent.name !== otherCurrent.name ||
  5856. !thisCurrent.node.equals(otherCurrent.node)) {
  5857. return false;
  5858. }
  5859. thisCurrent = thisIter.getNext();
  5860. otherCurrent = otherIter.getNext();
  5861. }
  5862. return thisCurrent === null && otherCurrent === null;
  5863. }
  5864. else {
  5865. return false;
  5866. }
  5867. }
  5868. };
  5869. /**
  5870. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5871. * instead.
  5872. *
  5873. */
  5874. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5875. if (indexDefinition === KEY_INDEX) {
  5876. return null;
  5877. }
  5878. else {
  5879. return this.indexMap_.get(indexDefinition.toString());
  5880. }
  5881. };
  5882. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5883. return ChildrenNode;
  5884. }());
  5885. var MaxNode = /** @class */ (function (_super) {
  5886. __extends(MaxNode, _super);
  5887. function MaxNode() {
  5888. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5889. }
  5890. MaxNode.prototype.compareTo = function (other) {
  5891. if (other === this) {
  5892. return 0;
  5893. }
  5894. else {
  5895. return 1;
  5896. }
  5897. };
  5898. MaxNode.prototype.equals = function (other) {
  5899. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5900. return other === this;
  5901. };
  5902. MaxNode.prototype.getPriority = function () {
  5903. return this;
  5904. };
  5905. MaxNode.prototype.getImmediateChild = function (childName) {
  5906. return ChildrenNode.EMPTY_NODE;
  5907. };
  5908. MaxNode.prototype.isEmpty = function () {
  5909. return false;
  5910. };
  5911. return MaxNode;
  5912. }(ChildrenNode));
  5913. /**
  5914. * Marker that will sort higher than any other snapshot.
  5915. */
  5916. var MAX_NODE = new MaxNode();
  5917. Object.defineProperties(NamedNode, {
  5918. MIN: {
  5919. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5920. },
  5921. MAX: {
  5922. value: new NamedNode(MAX_NAME, MAX_NODE)
  5923. }
  5924. });
  5925. /**
  5926. * Reference Extensions
  5927. */
  5928. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5929. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5930. setMaxNode$1(MAX_NODE);
  5931. setMaxNode(MAX_NODE);
  5932. /**
  5933. * @license
  5934. * Copyright 2017 Google LLC
  5935. *
  5936. * Licensed under the Apache License, Version 2.0 (the "License");
  5937. * you may not use this file except in compliance with the License.
  5938. * You may obtain a copy of the License at
  5939. *
  5940. * http://www.apache.org/licenses/LICENSE-2.0
  5941. *
  5942. * Unless required by applicable law or agreed to in writing, software
  5943. * distributed under the License is distributed on an "AS IS" BASIS,
  5944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5945. * See the License for the specific language governing permissions and
  5946. * limitations under the License.
  5947. */
  5948. var USE_HINZE = true;
  5949. /**
  5950. * Constructs a snapshot node representing the passed JSON and returns it.
  5951. * @param json - JSON to create a node for.
  5952. * @param priority - Optional priority to use. This will be ignored if the
  5953. * passed JSON contains a .priority property.
  5954. */
  5955. function nodeFromJSON(json, priority) {
  5956. if (priority === void 0) { priority = null; }
  5957. if (json === null) {
  5958. return ChildrenNode.EMPTY_NODE;
  5959. }
  5960. if (typeof json === 'object' && '.priority' in json) {
  5961. priority = json['.priority'];
  5962. }
  5963. assert(priority === null ||
  5964. typeof priority === 'string' ||
  5965. typeof priority === 'number' ||
  5966. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5967. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5968. json = json['.value'];
  5969. }
  5970. // Valid leaf nodes include non-objects or server-value wrapper objects
  5971. if (typeof json !== 'object' || '.sv' in json) {
  5972. var jsonLeaf = json;
  5973. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5974. }
  5975. if (!(json instanceof Array) && USE_HINZE) {
  5976. var children_1 = [];
  5977. var childrenHavePriority_1 = false;
  5978. var hinzeJsonObj = json;
  5979. each(hinzeJsonObj, function (key, child) {
  5980. if (key.substring(0, 1) !== '.') {
  5981. // Ignore metadata nodes
  5982. var childNode = nodeFromJSON(child);
  5983. if (!childNode.isEmpty()) {
  5984. childrenHavePriority_1 =
  5985. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  5986. children_1.push(new NamedNode(key, childNode));
  5987. }
  5988. }
  5989. });
  5990. if (children_1.length === 0) {
  5991. return ChildrenNode.EMPTY_NODE;
  5992. }
  5993. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  5994. if (childrenHavePriority_1) {
  5995. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  5996. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5997. }
  5998. else {
  5999. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6000. }
  6001. }
  6002. else {
  6003. var node_1 = ChildrenNode.EMPTY_NODE;
  6004. each(json, function (key, childData) {
  6005. if (contains(json, key)) {
  6006. if (key.substring(0, 1) !== '.') {
  6007. // ignore metadata nodes.
  6008. var childNode = nodeFromJSON(childData);
  6009. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6010. node_1 = node_1.updateImmediateChild(key, childNode);
  6011. }
  6012. }
  6013. }
  6014. });
  6015. return node_1.updatePriority(nodeFromJSON(priority));
  6016. }
  6017. }
  6018. setNodeFromJSON(nodeFromJSON);
  6019. /**
  6020. * @license
  6021. * Copyright 2017 Google LLC
  6022. *
  6023. * Licensed under the Apache License, Version 2.0 (the "License");
  6024. * you may not use this file except in compliance with the License.
  6025. * You may obtain a copy of the License at
  6026. *
  6027. * http://www.apache.org/licenses/LICENSE-2.0
  6028. *
  6029. * Unless required by applicable law or agreed to in writing, software
  6030. * distributed under the License is distributed on an "AS IS" BASIS,
  6031. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6032. * See the License for the specific language governing permissions and
  6033. * limitations under the License.
  6034. */
  6035. var PathIndex = /** @class */ (function (_super) {
  6036. __extends(PathIndex, _super);
  6037. function PathIndex(indexPath_) {
  6038. var _this = _super.call(this) || this;
  6039. _this.indexPath_ = indexPath_;
  6040. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6041. return _this;
  6042. }
  6043. PathIndex.prototype.extractChild = function (snap) {
  6044. return snap.getChild(this.indexPath_);
  6045. };
  6046. PathIndex.prototype.isDefinedOn = function (node) {
  6047. return !node.getChild(this.indexPath_).isEmpty();
  6048. };
  6049. PathIndex.prototype.compare = function (a, b) {
  6050. var aChild = this.extractChild(a.node);
  6051. var bChild = this.extractChild(b.node);
  6052. var indexCmp = aChild.compareTo(bChild);
  6053. if (indexCmp === 0) {
  6054. return nameCompare(a.name, b.name);
  6055. }
  6056. else {
  6057. return indexCmp;
  6058. }
  6059. };
  6060. PathIndex.prototype.makePost = function (indexValue, name) {
  6061. var valueNode = nodeFromJSON(indexValue);
  6062. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6063. return new NamedNode(name, node);
  6064. };
  6065. PathIndex.prototype.maxPost = function () {
  6066. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6067. return new NamedNode(MAX_NAME, node);
  6068. };
  6069. PathIndex.prototype.toString = function () {
  6070. return pathSlice(this.indexPath_, 0).join('/');
  6071. };
  6072. return PathIndex;
  6073. }(Index));
  6074. /**
  6075. * @license
  6076. * Copyright 2017 Google LLC
  6077. *
  6078. * Licensed under the Apache License, Version 2.0 (the "License");
  6079. * you may not use this file except in compliance with the License.
  6080. * You may obtain a copy of the License at
  6081. *
  6082. * http://www.apache.org/licenses/LICENSE-2.0
  6083. *
  6084. * Unless required by applicable law or agreed to in writing, software
  6085. * distributed under the License is distributed on an "AS IS" BASIS,
  6086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6087. * See the License for the specific language governing permissions and
  6088. * limitations under the License.
  6089. */
  6090. var ValueIndex = /** @class */ (function (_super) {
  6091. __extends(ValueIndex, _super);
  6092. function ValueIndex() {
  6093. return _super !== null && _super.apply(this, arguments) || this;
  6094. }
  6095. ValueIndex.prototype.compare = function (a, b) {
  6096. var indexCmp = a.node.compareTo(b.node);
  6097. if (indexCmp === 0) {
  6098. return nameCompare(a.name, b.name);
  6099. }
  6100. else {
  6101. return indexCmp;
  6102. }
  6103. };
  6104. ValueIndex.prototype.isDefinedOn = function (node) {
  6105. return true;
  6106. };
  6107. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6108. return !oldNode.equals(newNode);
  6109. };
  6110. ValueIndex.prototype.minPost = function () {
  6111. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6112. return NamedNode.MIN;
  6113. };
  6114. ValueIndex.prototype.maxPost = function () {
  6115. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6116. return NamedNode.MAX;
  6117. };
  6118. ValueIndex.prototype.makePost = function (indexValue, name) {
  6119. var valueNode = nodeFromJSON(indexValue);
  6120. return new NamedNode(name, valueNode);
  6121. };
  6122. /**
  6123. * @returns String representation for inclusion in a query spec
  6124. */
  6125. ValueIndex.prototype.toString = function () {
  6126. return '.value';
  6127. };
  6128. return ValueIndex;
  6129. }(Index));
  6130. var VALUE_INDEX = new ValueIndex();
  6131. /**
  6132. * @license
  6133. * Copyright 2017 Google LLC
  6134. *
  6135. * Licensed under the Apache License, Version 2.0 (the "License");
  6136. * you may not use this file except in compliance with the License.
  6137. * You may obtain a copy of the License at
  6138. *
  6139. * http://www.apache.org/licenses/LICENSE-2.0
  6140. *
  6141. * Unless required by applicable law or agreed to in writing, software
  6142. * distributed under the License is distributed on an "AS IS" BASIS,
  6143. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6144. * See the License for the specific language governing permissions and
  6145. * limitations under the License.
  6146. */
  6147. function changeValue(snapshotNode) {
  6148. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6149. }
  6150. function changeChildAdded(childName, snapshotNode) {
  6151. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6152. }
  6153. function changeChildRemoved(childName, snapshotNode) {
  6154. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6155. }
  6156. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6157. return {
  6158. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6159. snapshotNode: snapshotNode,
  6160. childName: childName,
  6161. oldSnap: oldSnap
  6162. };
  6163. }
  6164. function changeChildMoved(childName, snapshotNode) {
  6165. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6166. }
  6167. /**
  6168. * @license
  6169. * Copyright 2017 Google LLC
  6170. *
  6171. * Licensed under the Apache License, Version 2.0 (the "License");
  6172. * you may not use this file except in compliance with the License.
  6173. * You may obtain a copy of the License at
  6174. *
  6175. * http://www.apache.org/licenses/LICENSE-2.0
  6176. *
  6177. * Unless required by applicable law or agreed to in writing, software
  6178. * distributed under the License is distributed on an "AS IS" BASIS,
  6179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6180. * See the License for the specific language governing permissions and
  6181. * limitations under the License.
  6182. */
  6183. /**
  6184. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6185. */
  6186. var IndexedFilter = /** @class */ (function () {
  6187. function IndexedFilter(index_) {
  6188. this.index_ = index_;
  6189. }
  6190. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6191. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6192. var oldChild = snap.getImmediateChild(key);
  6193. // Check if anything actually changed.
  6194. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6195. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6196. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6197. // to avoid treating these cases as "nothing changed."
  6198. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6199. // Nothing changed.
  6200. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6201. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6202. return snap;
  6203. }
  6204. }
  6205. if (optChangeAccumulator != null) {
  6206. if (newChild.isEmpty()) {
  6207. if (snap.hasChild(key)) {
  6208. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6209. }
  6210. else {
  6211. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6212. }
  6213. }
  6214. else if (oldChild.isEmpty()) {
  6215. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6216. }
  6217. else {
  6218. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6219. }
  6220. }
  6221. if (snap.isLeafNode() && newChild.isEmpty()) {
  6222. return snap;
  6223. }
  6224. else {
  6225. // Make sure the node is indexed
  6226. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6227. }
  6228. };
  6229. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6230. if (optChangeAccumulator != null) {
  6231. if (!oldSnap.isLeafNode()) {
  6232. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6233. if (!newSnap.hasChild(key)) {
  6234. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6235. }
  6236. });
  6237. }
  6238. if (!newSnap.isLeafNode()) {
  6239. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6240. if (oldSnap.hasChild(key)) {
  6241. var oldChild = oldSnap.getImmediateChild(key);
  6242. if (!oldChild.equals(childNode)) {
  6243. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6244. }
  6245. }
  6246. else {
  6247. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6248. }
  6249. });
  6250. }
  6251. }
  6252. return newSnap.withIndex(this.index_);
  6253. };
  6254. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6255. if (oldSnap.isEmpty()) {
  6256. return ChildrenNode.EMPTY_NODE;
  6257. }
  6258. else {
  6259. return oldSnap.updatePriority(newPriority);
  6260. }
  6261. };
  6262. IndexedFilter.prototype.filtersNodes = function () {
  6263. return false;
  6264. };
  6265. IndexedFilter.prototype.getIndexedFilter = function () {
  6266. return this;
  6267. };
  6268. IndexedFilter.prototype.getIndex = function () {
  6269. return this.index_;
  6270. };
  6271. return IndexedFilter;
  6272. }());
  6273. /**
  6274. * @license
  6275. * Copyright 2017 Google LLC
  6276. *
  6277. * Licensed under the Apache License, Version 2.0 (the "License");
  6278. * you may not use this file except in compliance with the License.
  6279. * You may obtain a copy of the License at
  6280. *
  6281. * http://www.apache.org/licenses/LICENSE-2.0
  6282. *
  6283. * Unless required by applicable law or agreed to in writing, software
  6284. * distributed under the License is distributed on an "AS IS" BASIS,
  6285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6286. * See the License for the specific language governing permissions and
  6287. * limitations under the License.
  6288. */
  6289. /**
  6290. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6291. */
  6292. var RangedFilter = /** @class */ (function () {
  6293. function RangedFilter(params) {
  6294. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6295. this.index_ = params.getIndex();
  6296. this.startPost_ = RangedFilter.getStartPost_(params);
  6297. this.endPost_ = RangedFilter.getEndPost_(params);
  6298. this.startIsInclusive_ = !params.startAfterSet_;
  6299. this.endIsInclusive_ = !params.endBeforeSet_;
  6300. }
  6301. RangedFilter.prototype.getStartPost = function () {
  6302. return this.startPost_;
  6303. };
  6304. RangedFilter.prototype.getEndPost = function () {
  6305. return this.endPost_;
  6306. };
  6307. RangedFilter.prototype.matches = function (node) {
  6308. var isWithinStart = this.startIsInclusive_
  6309. ? this.index_.compare(this.getStartPost(), node) <= 0
  6310. : this.index_.compare(this.getStartPost(), node) < 0;
  6311. var isWithinEnd = this.endIsInclusive_
  6312. ? this.index_.compare(node, this.getEndPost()) <= 0
  6313. : this.index_.compare(node, this.getEndPost()) < 0;
  6314. return isWithinStart && isWithinEnd;
  6315. };
  6316. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6317. if (!this.matches(new NamedNode(key, newChild))) {
  6318. newChild = ChildrenNode.EMPTY_NODE;
  6319. }
  6320. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6321. };
  6322. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6323. if (newSnap.isLeafNode()) {
  6324. // Make sure we have a children node with the correct index, not a leaf node;
  6325. newSnap = ChildrenNode.EMPTY_NODE;
  6326. }
  6327. var filtered = newSnap.withIndex(this.index_);
  6328. // Don't support priorities on queries
  6329. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6330. var self = this;
  6331. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6332. if (!self.matches(new NamedNode(key, childNode))) {
  6333. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6334. }
  6335. });
  6336. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6337. };
  6338. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6339. // Don't support priorities on queries
  6340. return oldSnap;
  6341. };
  6342. RangedFilter.prototype.filtersNodes = function () {
  6343. return true;
  6344. };
  6345. RangedFilter.prototype.getIndexedFilter = function () {
  6346. return this.indexedFilter_;
  6347. };
  6348. RangedFilter.prototype.getIndex = function () {
  6349. return this.index_;
  6350. };
  6351. RangedFilter.getStartPost_ = function (params) {
  6352. if (params.hasStart()) {
  6353. var startName = params.getIndexStartName();
  6354. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6355. }
  6356. else {
  6357. return params.getIndex().minPost();
  6358. }
  6359. };
  6360. RangedFilter.getEndPost_ = function (params) {
  6361. if (params.hasEnd()) {
  6362. var endName = params.getIndexEndName();
  6363. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6364. }
  6365. else {
  6366. return params.getIndex().maxPost();
  6367. }
  6368. };
  6369. return RangedFilter;
  6370. }());
  6371. /**
  6372. * @license
  6373. * Copyright 2017 Google LLC
  6374. *
  6375. * Licensed under the Apache License, Version 2.0 (the "License");
  6376. * you may not use this file except in compliance with the License.
  6377. * You may obtain a copy of the License at
  6378. *
  6379. * http://www.apache.org/licenses/LICENSE-2.0
  6380. *
  6381. * Unless required by applicable law or agreed to in writing, software
  6382. * distributed under the License is distributed on an "AS IS" BASIS,
  6383. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6384. * See the License for the specific language governing permissions and
  6385. * limitations under the License.
  6386. */
  6387. /**
  6388. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6389. */
  6390. var LimitedFilter = /** @class */ (function () {
  6391. function LimitedFilter(params) {
  6392. var _this = this;
  6393. this.withinDirectionalStart = function (node) {
  6394. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6395. };
  6396. this.withinDirectionalEnd = function (node) {
  6397. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6398. };
  6399. this.withinStartPost = function (node) {
  6400. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6401. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6402. };
  6403. this.withinEndPost = function (node) {
  6404. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6405. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6406. };
  6407. this.rangedFilter_ = new RangedFilter(params);
  6408. this.index_ = params.getIndex();
  6409. this.limit_ = params.getLimit();
  6410. this.reverse_ = !params.isViewFromLeft();
  6411. this.startIsInclusive_ = !params.startAfterSet_;
  6412. this.endIsInclusive_ = !params.endBeforeSet_;
  6413. }
  6414. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6415. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6416. newChild = ChildrenNode.EMPTY_NODE;
  6417. }
  6418. if (snap.getImmediateChild(key).equals(newChild)) {
  6419. // No change
  6420. return snap;
  6421. }
  6422. else if (snap.numChildren() < this.limit_) {
  6423. return this.rangedFilter_
  6424. .getIndexedFilter()
  6425. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6426. }
  6427. else {
  6428. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6429. }
  6430. };
  6431. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6432. var filtered;
  6433. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6434. // Make sure we have a children node with the correct index, not a leaf node;
  6435. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6436. }
  6437. else {
  6438. if (this.limit_ * 2 < newSnap.numChildren() &&
  6439. newSnap.isIndexed(this.index_)) {
  6440. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6441. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6442. // anchor to the startPost, endPost, or last element as appropriate
  6443. var iterator = void 0;
  6444. if (this.reverse_) {
  6445. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6446. }
  6447. else {
  6448. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6449. }
  6450. var count = 0;
  6451. while (iterator.hasNext() && count < this.limit_) {
  6452. var next = iterator.getNext();
  6453. if (!this.withinDirectionalStart(next)) {
  6454. // if we have not reached the start, skip to the next element
  6455. continue;
  6456. }
  6457. else if (!this.withinDirectionalEnd(next)) {
  6458. // if we have reached the end, stop adding elements
  6459. break;
  6460. }
  6461. else {
  6462. filtered = filtered.updateImmediateChild(next.name, next.node);
  6463. count++;
  6464. }
  6465. }
  6466. }
  6467. else {
  6468. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6469. filtered = newSnap.withIndex(this.index_);
  6470. // Don't support priorities on queries
  6471. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6472. var iterator = void 0;
  6473. if (this.reverse_) {
  6474. iterator = filtered.getReverseIterator(this.index_);
  6475. }
  6476. else {
  6477. iterator = filtered.getIterator(this.index_);
  6478. }
  6479. var count = 0;
  6480. while (iterator.hasNext()) {
  6481. var next = iterator.getNext();
  6482. var inRange = count < this.limit_ &&
  6483. this.withinDirectionalStart(next) &&
  6484. this.withinDirectionalEnd(next);
  6485. if (inRange) {
  6486. count++;
  6487. }
  6488. else {
  6489. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6490. }
  6491. }
  6492. }
  6493. }
  6494. return this.rangedFilter_
  6495. .getIndexedFilter()
  6496. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6497. };
  6498. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6499. // Don't support priorities on queries
  6500. return oldSnap;
  6501. };
  6502. LimitedFilter.prototype.filtersNodes = function () {
  6503. return true;
  6504. };
  6505. LimitedFilter.prototype.getIndexedFilter = function () {
  6506. return this.rangedFilter_.getIndexedFilter();
  6507. };
  6508. LimitedFilter.prototype.getIndex = function () {
  6509. return this.index_;
  6510. };
  6511. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6512. // TODO: rename all cache stuff etc to general snap terminology
  6513. var cmp;
  6514. if (this.reverse_) {
  6515. var indexCmp_1 = this.index_.getCompare();
  6516. cmp = function (a, b) { return indexCmp_1(b, a); };
  6517. }
  6518. else {
  6519. cmp = this.index_.getCompare();
  6520. }
  6521. var oldEventCache = snap;
  6522. assert(oldEventCache.numChildren() === this.limit_, '');
  6523. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6524. var windowBoundary = this.reverse_
  6525. ? oldEventCache.getFirstChild(this.index_)
  6526. : oldEventCache.getLastChild(this.index_);
  6527. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6528. if (oldEventCache.hasChild(childKey)) {
  6529. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6530. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6531. while (nextChild != null &&
  6532. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6533. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6534. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6535. // the limited filter...
  6536. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6537. }
  6538. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6539. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6540. if (remainsInWindow) {
  6541. if (changeAccumulator != null) {
  6542. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6543. }
  6544. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6545. }
  6546. else {
  6547. if (changeAccumulator != null) {
  6548. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6549. }
  6550. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6551. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6552. if (nextChildInRange) {
  6553. if (changeAccumulator != null) {
  6554. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6555. }
  6556. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6557. }
  6558. else {
  6559. return newEventCache;
  6560. }
  6561. }
  6562. }
  6563. else if (childSnap.isEmpty()) {
  6564. // we're deleting a node, but it was not in the window, so ignore it
  6565. return snap;
  6566. }
  6567. else if (inRange) {
  6568. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6569. if (changeAccumulator != null) {
  6570. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6571. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6572. }
  6573. return oldEventCache
  6574. .updateImmediateChild(childKey, childSnap)
  6575. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6576. }
  6577. else {
  6578. return snap;
  6579. }
  6580. }
  6581. else {
  6582. return snap;
  6583. }
  6584. };
  6585. return LimitedFilter;
  6586. }());
  6587. /**
  6588. * @license
  6589. * Copyright 2017 Google LLC
  6590. *
  6591. * Licensed under the Apache License, Version 2.0 (the "License");
  6592. * you may not use this file except in compliance with the License.
  6593. * You may obtain a copy of the License at
  6594. *
  6595. * http://www.apache.org/licenses/LICENSE-2.0
  6596. *
  6597. * Unless required by applicable law or agreed to in writing, software
  6598. * distributed under the License is distributed on an "AS IS" BASIS,
  6599. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6600. * See the License for the specific language governing permissions and
  6601. * limitations under the License.
  6602. */
  6603. /**
  6604. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6605. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6606. * user-facing API level, so it is not done here.
  6607. *
  6608. * @internal
  6609. */
  6610. var QueryParams = /** @class */ (function () {
  6611. function QueryParams() {
  6612. this.limitSet_ = false;
  6613. this.startSet_ = false;
  6614. this.startNameSet_ = false;
  6615. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6616. this.endSet_ = false;
  6617. this.endNameSet_ = false;
  6618. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6619. this.limit_ = 0;
  6620. this.viewFrom_ = '';
  6621. this.indexStartValue_ = null;
  6622. this.indexStartName_ = '';
  6623. this.indexEndValue_ = null;
  6624. this.indexEndName_ = '';
  6625. this.index_ = PRIORITY_INDEX;
  6626. }
  6627. QueryParams.prototype.hasStart = function () {
  6628. return this.startSet_;
  6629. };
  6630. /**
  6631. * @returns True if it would return from left.
  6632. */
  6633. QueryParams.prototype.isViewFromLeft = function () {
  6634. if (this.viewFrom_ === '') {
  6635. // limit(), rather than limitToFirst or limitToLast was called.
  6636. // This means that only one of startSet_ and endSet_ is true. Use them
  6637. // to calculate which side of the view to anchor to. If neither is set,
  6638. // anchor to the end.
  6639. return this.startSet_;
  6640. }
  6641. else {
  6642. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6643. }
  6644. };
  6645. /**
  6646. * Only valid to call if hasStart() returns true
  6647. */
  6648. QueryParams.prototype.getIndexStartValue = function () {
  6649. assert(this.startSet_, 'Only valid if start has been set');
  6650. return this.indexStartValue_;
  6651. };
  6652. /**
  6653. * Only valid to call if hasStart() returns true.
  6654. * Returns the starting key name for the range defined by these query parameters
  6655. */
  6656. QueryParams.prototype.getIndexStartName = function () {
  6657. assert(this.startSet_, 'Only valid if start has been set');
  6658. if (this.startNameSet_) {
  6659. return this.indexStartName_;
  6660. }
  6661. else {
  6662. return MIN_NAME;
  6663. }
  6664. };
  6665. QueryParams.prototype.hasEnd = function () {
  6666. return this.endSet_;
  6667. };
  6668. /**
  6669. * Only valid to call if hasEnd() returns true.
  6670. */
  6671. QueryParams.prototype.getIndexEndValue = function () {
  6672. assert(this.endSet_, 'Only valid if end has been set');
  6673. return this.indexEndValue_;
  6674. };
  6675. /**
  6676. * Only valid to call if hasEnd() returns true.
  6677. * Returns the end key name for the range defined by these query parameters
  6678. */
  6679. QueryParams.prototype.getIndexEndName = function () {
  6680. assert(this.endSet_, 'Only valid if end has been set');
  6681. if (this.endNameSet_) {
  6682. return this.indexEndName_;
  6683. }
  6684. else {
  6685. return MAX_NAME;
  6686. }
  6687. };
  6688. QueryParams.prototype.hasLimit = function () {
  6689. return this.limitSet_;
  6690. };
  6691. /**
  6692. * @returns True if a limit has been set and it has been explicitly anchored
  6693. */
  6694. QueryParams.prototype.hasAnchoredLimit = function () {
  6695. return this.limitSet_ && this.viewFrom_ !== '';
  6696. };
  6697. /**
  6698. * Only valid to call if hasLimit() returns true
  6699. */
  6700. QueryParams.prototype.getLimit = function () {
  6701. assert(this.limitSet_, 'Only valid if limit has been set');
  6702. return this.limit_;
  6703. };
  6704. QueryParams.prototype.getIndex = function () {
  6705. return this.index_;
  6706. };
  6707. QueryParams.prototype.loadsAllData = function () {
  6708. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6709. };
  6710. QueryParams.prototype.isDefault = function () {
  6711. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6712. };
  6713. QueryParams.prototype.copy = function () {
  6714. var copy = new QueryParams();
  6715. copy.limitSet_ = this.limitSet_;
  6716. copy.limit_ = this.limit_;
  6717. copy.startSet_ = this.startSet_;
  6718. copy.startAfterSet_ = this.startAfterSet_;
  6719. copy.indexStartValue_ = this.indexStartValue_;
  6720. copy.startNameSet_ = this.startNameSet_;
  6721. copy.indexStartName_ = this.indexStartName_;
  6722. copy.endSet_ = this.endSet_;
  6723. copy.endBeforeSet_ = this.endBeforeSet_;
  6724. copy.indexEndValue_ = this.indexEndValue_;
  6725. copy.endNameSet_ = this.endNameSet_;
  6726. copy.indexEndName_ = this.indexEndName_;
  6727. copy.index_ = this.index_;
  6728. copy.viewFrom_ = this.viewFrom_;
  6729. return copy;
  6730. };
  6731. return QueryParams;
  6732. }());
  6733. function queryParamsGetNodeFilter(queryParams) {
  6734. if (queryParams.loadsAllData()) {
  6735. return new IndexedFilter(queryParams.getIndex());
  6736. }
  6737. else if (queryParams.hasLimit()) {
  6738. return new LimitedFilter(queryParams);
  6739. }
  6740. else {
  6741. return new RangedFilter(queryParams);
  6742. }
  6743. }
  6744. function queryParamsLimitToFirst(queryParams, newLimit) {
  6745. var newParams = queryParams.copy();
  6746. newParams.limitSet_ = true;
  6747. newParams.limit_ = newLimit;
  6748. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6749. return newParams;
  6750. }
  6751. function queryParamsLimitToLast(queryParams, newLimit) {
  6752. var newParams = queryParams.copy();
  6753. newParams.limitSet_ = true;
  6754. newParams.limit_ = newLimit;
  6755. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6756. return newParams;
  6757. }
  6758. function queryParamsStartAt(queryParams, indexValue, key) {
  6759. var newParams = queryParams.copy();
  6760. newParams.startSet_ = true;
  6761. if (indexValue === undefined) {
  6762. indexValue = null;
  6763. }
  6764. newParams.indexStartValue_ = indexValue;
  6765. if (key != null) {
  6766. newParams.startNameSet_ = true;
  6767. newParams.indexStartName_ = key;
  6768. }
  6769. else {
  6770. newParams.startNameSet_ = false;
  6771. newParams.indexStartName_ = '';
  6772. }
  6773. return newParams;
  6774. }
  6775. function queryParamsStartAfter(queryParams, indexValue, key) {
  6776. var params;
  6777. if (queryParams.index_ === KEY_INDEX || !!key) {
  6778. params = queryParamsStartAt(queryParams, indexValue, key);
  6779. }
  6780. else {
  6781. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6782. }
  6783. params.startAfterSet_ = true;
  6784. return params;
  6785. }
  6786. function queryParamsEndAt(queryParams, indexValue, key) {
  6787. var newParams = queryParams.copy();
  6788. newParams.endSet_ = true;
  6789. if (indexValue === undefined) {
  6790. indexValue = null;
  6791. }
  6792. newParams.indexEndValue_ = indexValue;
  6793. if (key !== undefined) {
  6794. newParams.endNameSet_ = true;
  6795. newParams.indexEndName_ = key;
  6796. }
  6797. else {
  6798. newParams.endNameSet_ = false;
  6799. newParams.indexEndName_ = '';
  6800. }
  6801. return newParams;
  6802. }
  6803. function queryParamsEndBefore(queryParams, indexValue, key) {
  6804. var params;
  6805. if (queryParams.index_ === KEY_INDEX || !!key) {
  6806. params = queryParamsEndAt(queryParams, indexValue, key);
  6807. }
  6808. else {
  6809. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6810. }
  6811. params.endBeforeSet_ = true;
  6812. return params;
  6813. }
  6814. function queryParamsOrderBy(queryParams, index) {
  6815. var newParams = queryParams.copy();
  6816. newParams.index_ = index;
  6817. return newParams;
  6818. }
  6819. /**
  6820. * Returns a set of REST query string parameters representing this query.
  6821. *
  6822. * @returns query string parameters
  6823. */
  6824. function queryParamsToRestQueryStringParameters(queryParams) {
  6825. var qs = {};
  6826. if (queryParams.isDefault()) {
  6827. return qs;
  6828. }
  6829. var orderBy;
  6830. if (queryParams.index_ === PRIORITY_INDEX) {
  6831. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6832. }
  6833. else if (queryParams.index_ === VALUE_INDEX) {
  6834. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6835. }
  6836. else if (queryParams.index_ === KEY_INDEX) {
  6837. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6838. }
  6839. else {
  6840. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6841. orderBy = queryParams.index_.toString();
  6842. }
  6843. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6844. if (queryParams.startSet_) {
  6845. var startParam = queryParams.startAfterSet_
  6846. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6847. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6848. qs[startParam] = stringify(queryParams.indexStartValue_);
  6849. if (queryParams.startNameSet_) {
  6850. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6851. }
  6852. }
  6853. if (queryParams.endSet_) {
  6854. var endParam = queryParams.endBeforeSet_
  6855. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6856. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6857. qs[endParam] = stringify(queryParams.indexEndValue_);
  6858. if (queryParams.endNameSet_) {
  6859. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6860. }
  6861. }
  6862. if (queryParams.limitSet_) {
  6863. if (queryParams.isViewFromLeft()) {
  6864. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6865. }
  6866. else {
  6867. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6868. }
  6869. }
  6870. return qs;
  6871. }
  6872. function queryParamsGetQueryObject(queryParams) {
  6873. var obj = {};
  6874. if (queryParams.startSet_) {
  6875. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6876. queryParams.indexStartValue_;
  6877. if (queryParams.startNameSet_) {
  6878. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6879. queryParams.indexStartName_;
  6880. }
  6881. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6882. !queryParams.startAfterSet_;
  6883. }
  6884. if (queryParams.endSet_) {
  6885. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6886. if (queryParams.endNameSet_) {
  6887. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6888. }
  6889. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6890. !queryParams.endBeforeSet_;
  6891. }
  6892. if (queryParams.limitSet_) {
  6893. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6894. var viewFrom = queryParams.viewFrom_;
  6895. if (viewFrom === '') {
  6896. if (queryParams.isViewFromLeft()) {
  6897. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6898. }
  6899. else {
  6900. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6901. }
  6902. }
  6903. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6904. }
  6905. // For now, priority index is the default, so we only specify if it's some other index
  6906. if (queryParams.index_ !== PRIORITY_INDEX) {
  6907. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6908. }
  6909. return obj;
  6910. }
  6911. /**
  6912. * @license
  6913. * Copyright 2017 Google LLC
  6914. *
  6915. * Licensed under the Apache License, Version 2.0 (the "License");
  6916. * you may not use this file except in compliance with the License.
  6917. * You may obtain a copy of the License at
  6918. *
  6919. * http://www.apache.org/licenses/LICENSE-2.0
  6920. *
  6921. * Unless required by applicable law or agreed to in writing, software
  6922. * distributed under the License is distributed on an "AS IS" BASIS,
  6923. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6924. * See the License for the specific language governing permissions and
  6925. * limitations under the License.
  6926. */
  6927. /**
  6928. * An implementation of ServerActions that communicates with the server via REST requests.
  6929. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6930. * persistent connection (using WebSockets or long-polling)
  6931. */
  6932. var ReadonlyRestClient = /** @class */ (function (_super) {
  6933. __extends(ReadonlyRestClient, _super);
  6934. /**
  6935. * @param repoInfo_ - Data about the namespace we are connecting to
  6936. * @param onDataUpdate_ - A callback for new data from the server
  6937. */
  6938. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6939. var _this = _super.call(this) || this;
  6940. _this.repoInfo_ = repoInfo_;
  6941. _this.onDataUpdate_ = onDataUpdate_;
  6942. _this.authTokenProvider_ = authTokenProvider_;
  6943. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6944. /** @private {function(...[*])} */
  6945. _this.log_ = logWrapper('p:rest:');
  6946. /**
  6947. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6948. * that's been removed. :-/
  6949. */
  6950. _this.listens_ = {};
  6951. return _this;
  6952. }
  6953. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6954. throw new Error('Method not implemented.');
  6955. };
  6956. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6957. if (tag !== undefined) {
  6958. return 'tag$' + tag;
  6959. }
  6960. else {
  6961. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6962. return query._path.toString();
  6963. }
  6964. };
  6965. /** @inheritDoc */
  6966. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6967. var _this = this;
  6968. var pathString = query._path.toString();
  6969. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6970. // Mark this listener so we can tell if it's removed.
  6971. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6972. var thisListen = {};
  6973. this.listens_[listenId] = thisListen;
  6974. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6975. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6976. var data = result;
  6977. if (error === 404) {
  6978. data = null;
  6979. error = null;
  6980. }
  6981. if (error === null) {
  6982. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6983. }
  6984. if (safeGet(_this.listens_, listenId) === thisListen) {
  6985. var status_1;
  6986. if (!error) {
  6987. status_1 = 'ok';
  6988. }
  6989. else if (error === 401) {
  6990. status_1 = 'permission_denied';
  6991. }
  6992. else {
  6993. status_1 = 'rest_error:' + error;
  6994. }
  6995. onComplete(status_1, null);
  6996. }
  6997. });
  6998. };
  6999. /** @inheritDoc */
  7000. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7001. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7002. delete this.listens_[listenId];
  7003. };
  7004. ReadonlyRestClient.prototype.get = function (query) {
  7005. var _this = this;
  7006. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7007. var pathString = query._path.toString();
  7008. var deferred = new Deferred();
  7009. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7010. var data = result;
  7011. if (error === 404) {
  7012. data = null;
  7013. error = null;
  7014. }
  7015. if (error === null) {
  7016. _this.onDataUpdate_(pathString, data,
  7017. /*isMerge=*/ false,
  7018. /*tag=*/ null);
  7019. deferred.resolve(data);
  7020. }
  7021. else {
  7022. deferred.reject(new Error(data));
  7023. }
  7024. });
  7025. return deferred.promise;
  7026. };
  7027. /** @inheritDoc */
  7028. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7029. // no-op since we just always call getToken.
  7030. };
  7031. /**
  7032. * Performs a REST request to the given path, with the provided query string parameters,
  7033. * and any auth credentials we have.
  7034. */
  7035. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7036. var _this = this;
  7037. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7038. queryStringParameters['format'] = 'export';
  7039. return Promise.all([
  7040. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7041. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7042. ]).then(function (_a) {
  7043. var _b = __read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7044. if (authToken && authToken.accessToken) {
  7045. queryStringParameters['auth'] = authToken.accessToken;
  7046. }
  7047. if (appCheckToken && appCheckToken.token) {
  7048. queryStringParameters['ac'] = appCheckToken.token;
  7049. }
  7050. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7051. _this.repoInfo_.host +
  7052. pathString +
  7053. '?' +
  7054. 'ns=' +
  7055. _this.repoInfo_.namespace +
  7056. querystring(queryStringParameters);
  7057. _this.log_('Sending REST request for ' + url);
  7058. var xhr = new XMLHttpRequest();
  7059. xhr.onreadystatechange = function () {
  7060. if (callback && xhr.readyState === 4) {
  7061. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7062. var res = null;
  7063. if (xhr.status >= 200 && xhr.status < 300) {
  7064. try {
  7065. res = jsonEval(xhr.responseText);
  7066. }
  7067. catch (e) {
  7068. warn('Failed to parse JSON response for ' +
  7069. url +
  7070. ': ' +
  7071. xhr.responseText);
  7072. }
  7073. callback(null, res);
  7074. }
  7075. else {
  7076. // 401 and 404 are expected.
  7077. if (xhr.status !== 401 && xhr.status !== 404) {
  7078. warn('Got unsuccessful REST response for ' +
  7079. url +
  7080. ' Status: ' +
  7081. xhr.status);
  7082. }
  7083. callback(xhr.status);
  7084. }
  7085. callback = null;
  7086. }
  7087. };
  7088. xhr.open('GET', url, /*asynchronous=*/ true);
  7089. xhr.send();
  7090. });
  7091. };
  7092. return ReadonlyRestClient;
  7093. }(ServerActions));
  7094. /**
  7095. * @license
  7096. * Copyright 2017 Google LLC
  7097. *
  7098. * Licensed under the Apache License, Version 2.0 (the "License");
  7099. * you may not use this file except in compliance with the License.
  7100. * You may obtain a copy of the License at
  7101. *
  7102. * http://www.apache.org/licenses/LICENSE-2.0
  7103. *
  7104. * Unless required by applicable law or agreed to in writing, software
  7105. * distributed under the License is distributed on an "AS IS" BASIS,
  7106. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7107. * See the License for the specific language governing permissions and
  7108. * limitations under the License.
  7109. */
  7110. /**
  7111. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7112. */
  7113. var SnapshotHolder = /** @class */ (function () {
  7114. function SnapshotHolder() {
  7115. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7116. }
  7117. SnapshotHolder.prototype.getNode = function (path) {
  7118. return this.rootNode_.getChild(path);
  7119. };
  7120. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7121. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7122. };
  7123. return SnapshotHolder;
  7124. }());
  7125. /**
  7126. * @license
  7127. * Copyright 2017 Google LLC
  7128. *
  7129. * Licensed under the Apache License, Version 2.0 (the "License");
  7130. * you may not use this file except in compliance with the License.
  7131. * You may obtain a copy of the License at
  7132. *
  7133. * http://www.apache.org/licenses/LICENSE-2.0
  7134. *
  7135. * Unless required by applicable law or agreed to in writing, software
  7136. * distributed under the License is distributed on an "AS IS" BASIS,
  7137. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7138. * See the License for the specific language governing permissions and
  7139. * limitations under the License.
  7140. */
  7141. function newSparseSnapshotTree() {
  7142. return {
  7143. value: null,
  7144. children: new Map()
  7145. };
  7146. }
  7147. /**
  7148. * Stores the given node at the specified path. If there is already a node
  7149. * at a shallower path, it merges the new data into that snapshot node.
  7150. *
  7151. * @param path - Path to look up snapshot for.
  7152. * @param data - The new data, or null.
  7153. */
  7154. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7155. if (pathIsEmpty(path)) {
  7156. sparseSnapshotTree.value = data;
  7157. sparseSnapshotTree.children.clear();
  7158. }
  7159. else if (sparseSnapshotTree.value !== null) {
  7160. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7161. }
  7162. else {
  7163. var childKey = pathGetFront(path);
  7164. if (!sparseSnapshotTree.children.has(childKey)) {
  7165. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7166. }
  7167. var child = sparseSnapshotTree.children.get(childKey);
  7168. path = pathPopFront(path);
  7169. sparseSnapshotTreeRemember(child, path, data);
  7170. }
  7171. }
  7172. /**
  7173. * Purge the data at path from the cache.
  7174. *
  7175. * @param path - Path to look up snapshot for.
  7176. * @returns True if this node should now be removed.
  7177. */
  7178. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7179. if (pathIsEmpty(path)) {
  7180. sparseSnapshotTree.value = null;
  7181. sparseSnapshotTree.children.clear();
  7182. return true;
  7183. }
  7184. else {
  7185. if (sparseSnapshotTree.value !== null) {
  7186. if (sparseSnapshotTree.value.isLeafNode()) {
  7187. // We're trying to forget a node that doesn't exist
  7188. return false;
  7189. }
  7190. else {
  7191. var value = sparseSnapshotTree.value;
  7192. sparseSnapshotTree.value = null;
  7193. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7194. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7195. });
  7196. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7197. }
  7198. }
  7199. else if (sparseSnapshotTree.children.size > 0) {
  7200. var childKey = pathGetFront(path);
  7201. path = pathPopFront(path);
  7202. if (sparseSnapshotTree.children.has(childKey)) {
  7203. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7204. if (safeToRemove) {
  7205. sparseSnapshotTree.children.delete(childKey);
  7206. }
  7207. }
  7208. return sparseSnapshotTree.children.size === 0;
  7209. }
  7210. else {
  7211. return true;
  7212. }
  7213. }
  7214. }
  7215. /**
  7216. * Recursively iterates through all of the stored tree and calls the
  7217. * callback on each one.
  7218. *
  7219. * @param prefixPath - Path to look up node for.
  7220. * @param func - The function to invoke for each tree.
  7221. */
  7222. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7223. if (sparseSnapshotTree.value !== null) {
  7224. func(prefixPath, sparseSnapshotTree.value);
  7225. }
  7226. else {
  7227. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7228. var path = new Path(prefixPath.toString() + '/' + key);
  7229. sparseSnapshotTreeForEachTree(tree, path, func);
  7230. });
  7231. }
  7232. }
  7233. /**
  7234. * Iterates through each immediate child and triggers the callback.
  7235. * Only seems to be used in tests.
  7236. *
  7237. * @param func - The function to invoke for each child.
  7238. */
  7239. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7240. sparseSnapshotTree.children.forEach(function (tree, key) {
  7241. func(key, tree);
  7242. });
  7243. }
  7244. /**
  7245. * @license
  7246. * Copyright 2017 Google LLC
  7247. *
  7248. * Licensed under the Apache License, Version 2.0 (the "License");
  7249. * you may not use this file except in compliance with the License.
  7250. * You may obtain a copy of the License at
  7251. *
  7252. * http://www.apache.org/licenses/LICENSE-2.0
  7253. *
  7254. * Unless required by applicable law or agreed to in writing, software
  7255. * distributed under the License is distributed on an "AS IS" BASIS,
  7256. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7257. * See the License for the specific language governing permissions and
  7258. * limitations under the License.
  7259. */
  7260. /**
  7261. * Returns the delta from the previous call to get stats.
  7262. *
  7263. * @param collection_ - The collection to "listen" to.
  7264. */
  7265. var StatsListener = /** @class */ (function () {
  7266. function StatsListener(collection_) {
  7267. this.collection_ = collection_;
  7268. this.last_ = null;
  7269. }
  7270. StatsListener.prototype.get = function () {
  7271. var newStats = this.collection_.get();
  7272. var delta = __assign({}, newStats);
  7273. if (this.last_) {
  7274. each(this.last_, function (stat, value) {
  7275. delta[stat] = delta[stat] - value;
  7276. });
  7277. }
  7278. this.last_ = newStats;
  7279. return delta;
  7280. };
  7281. return StatsListener;
  7282. }());
  7283. /**
  7284. * @license
  7285. * Copyright 2017 Google LLC
  7286. *
  7287. * Licensed under the Apache License, Version 2.0 (the "License");
  7288. * you may not use this file except in compliance with the License.
  7289. * You may obtain a copy of the License at
  7290. *
  7291. * http://www.apache.org/licenses/LICENSE-2.0
  7292. *
  7293. * Unless required by applicable law or agreed to in writing, software
  7294. * distributed under the License is distributed on an "AS IS" BASIS,
  7295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7296. * See the License for the specific language governing permissions and
  7297. * limitations under the License.
  7298. */
  7299. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7300. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7301. // seconds to try to ensure the Firebase connection is established / settled.
  7302. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7303. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7304. // We'll continue to report stats on average every 5 minutes.
  7305. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7306. var StatsReporter = /** @class */ (function () {
  7307. function StatsReporter(collection, server_) {
  7308. this.server_ = server_;
  7309. this.statsToReport_ = {};
  7310. this.statsListener_ = new StatsListener(collection);
  7311. var timeout = FIRST_STATS_MIN_TIME +
  7312. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7313. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7314. }
  7315. StatsReporter.prototype.reportStats_ = function () {
  7316. var _this = this;
  7317. var stats = this.statsListener_.get();
  7318. var reportedStats = {};
  7319. var haveStatsToReport = false;
  7320. each(stats, function (stat, value) {
  7321. if (value > 0 && contains(_this.statsToReport_, stat)) {
  7322. reportedStats[stat] = value;
  7323. haveStatsToReport = true;
  7324. }
  7325. });
  7326. if (haveStatsToReport) {
  7327. this.server_.reportStats(reportedStats);
  7328. }
  7329. // queue our next run.
  7330. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7331. };
  7332. return StatsReporter;
  7333. }());
  7334. /**
  7335. * @license
  7336. * Copyright 2017 Google LLC
  7337. *
  7338. * Licensed under the Apache License, Version 2.0 (the "License");
  7339. * you may not use this file except in compliance with the License.
  7340. * You may obtain a copy of the License at
  7341. *
  7342. * http://www.apache.org/licenses/LICENSE-2.0
  7343. *
  7344. * Unless required by applicable law or agreed to in writing, software
  7345. * distributed under the License is distributed on an "AS IS" BASIS,
  7346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7347. * See the License for the specific language governing permissions and
  7348. * limitations under the License.
  7349. */
  7350. /**
  7351. *
  7352. * @enum
  7353. */
  7354. var OperationType;
  7355. (function (OperationType) {
  7356. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7357. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7358. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7359. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7360. })(OperationType || (OperationType = {}));
  7361. function newOperationSourceUser() {
  7362. return {
  7363. fromUser: true,
  7364. fromServer: false,
  7365. queryId: null,
  7366. tagged: false
  7367. };
  7368. }
  7369. function newOperationSourceServer() {
  7370. return {
  7371. fromUser: false,
  7372. fromServer: true,
  7373. queryId: null,
  7374. tagged: false
  7375. };
  7376. }
  7377. function newOperationSourceServerTaggedQuery(queryId) {
  7378. return {
  7379. fromUser: false,
  7380. fromServer: true,
  7381. queryId: queryId,
  7382. tagged: true
  7383. };
  7384. }
  7385. /**
  7386. * @license
  7387. * Copyright 2017 Google LLC
  7388. *
  7389. * Licensed under the Apache License, Version 2.0 (the "License");
  7390. * you may not use this file except in compliance with the License.
  7391. * You may obtain a copy of the License at
  7392. *
  7393. * http://www.apache.org/licenses/LICENSE-2.0
  7394. *
  7395. * Unless required by applicable law or agreed to in writing, software
  7396. * distributed under the License is distributed on an "AS IS" BASIS,
  7397. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7398. * See the License for the specific language governing permissions and
  7399. * limitations under the License.
  7400. */
  7401. var AckUserWrite = /** @class */ (function () {
  7402. /**
  7403. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7404. */
  7405. function AckUserWrite(
  7406. /** @inheritDoc */ path,
  7407. /** @inheritDoc */ affectedTree,
  7408. /** @inheritDoc */ revert) {
  7409. this.path = path;
  7410. this.affectedTree = affectedTree;
  7411. this.revert = revert;
  7412. /** @inheritDoc */
  7413. this.type = OperationType.ACK_USER_WRITE;
  7414. /** @inheritDoc */
  7415. this.source = newOperationSourceUser();
  7416. }
  7417. AckUserWrite.prototype.operationForChild = function (childName) {
  7418. if (!pathIsEmpty(this.path)) {
  7419. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7420. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7421. }
  7422. else if (this.affectedTree.value != null) {
  7423. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7424. // All child locations are affected as well; just return same operation.
  7425. return this;
  7426. }
  7427. else {
  7428. var childTree = this.affectedTree.subtree(new Path(childName));
  7429. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7430. }
  7431. };
  7432. return AckUserWrite;
  7433. }());
  7434. /**
  7435. * @license
  7436. * Copyright 2017 Google LLC
  7437. *
  7438. * Licensed under the Apache License, Version 2.0 (the "License");
  7439. * you may not use this file except in compliance with the License.
  7440. * You may obtain a copy of the License at
  7441. *
  7442. * http://www.apache.org/licenses/LICENSE-2.0
  7443. *
  7444. * Unless required by applicable law or agreed to in writing, software
  7445. * distributed under the License is distributed on an "AS IS" BASIS,
  7446. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7447. * See the License for the specific language governing permissions and
  7448. * limitations under the License.
  7449. */
  7450. var ListenComplete = /** @class */ (function () {
  7451. function ListenComplete(source, path) {
  7452. this.source = source;
  7453. this.path = path;
  7454. /** @inheritDoc */
  7455. this.type = OperationType.LISTEN_COMPLETE;
  7456. }
  7457. ListenComplete.prototype.operationForChild = function (childName) {
  7458. if (pathIsEmpty(this.path)) {
  7459. return new ListenComplete(this.source, newEmptyPath());
  7460. }
  7461. else {
  7462. return new ListenComplete(this.source, pathPopFront(this.path));
  7463. }
  7464. };
  7465. return ListenComplete;
  7466. }());
  7467. /**
  7468. * @license
  7469. * Copyright 2017 Google LLC
  7470. *
  7471. * Licensed under the Apache License, Version 2.0 (the "License");
  7472. * you may not use this file except in compliance with the License.
  7473. * You may obtain a copy of the License at
  7474. *
  7475. * http://www.apache.org/licenses/LICENSE-2.0
  7476. *
  7477. * Unless required by applicable law or agreed to in writing, software
  7478. * distributed under the License is distributed on an "AS IS" BASIS,
  7479. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7480. * See the License for the specific language governing permissions and
  7481. * limitations under the License.
  7482. */
  7483. var Overwrite = /** @class */ (function () {
  7484. function Overwrite(source, path, snap) {
  7485. this.source = source;
  7486. this.path = path;
  7487. this.snap = snap;
  7488. /** @inheritDoc */
  7489. this.type = OperationType.OVERWRITE;
  7490. }
  7491. Overwrite.prototype.operationForChild = function (childName) {
  7492. if (pathIsEmpty(this.path)) {
  7493. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7494. }
  7495. else {
  7496. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7497. }
  7498. };
  7499. return Overwrite;
  7500. }());
  7501. /**
  7502. * @license
  7503. * Copyright 2017 Google LLC
  7504. *
  7505. * Licensed under the Apache License, Version 2.0 (the "License");
  7506. * you may not use this file except in compliance with the License.
  7507. * You may obtain a copy of the License at
  7508. *
  7509. * http://www.apache.org/licenses/LICENSE-2.0
  7510. *
  7511. * Unless required by applicable law or agreed to in writing, software
  7512. * distributed under the License is distributed on an "AS IS" BASIS,
  7513. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7514. * See the License for the specific language governing permissions and
  7515. * limitations under the License.
  7516. */
  7517. var Merge = /** @class */ (function () {
  7518. function Merge(
  7519. /** @inheritDoc */ source,
  7520. /** @inheritDoc */ path,
  7521. /** @inheritDoc */ children) {
  7522. this.source = source;
  7523. this.path = path;
  7524. this.children = children;
  7525. /** @inheritDoc */
  7526. this.type = OperationType.MERGE;
  7527. }
  7528. Merge.prototype.operationForChild = function (childName) {
  7529. if (pathIsEmpty(this.path)) {
  7530. var childTree = this.children.subtree(new Path(childName));
  7531. if (childTree.isEmpty()) {
  7532. // This child is unaffected
  7533. return null;
  7534. }
  7535. else if (childTree.value) {
  7536. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7537. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7538. }
  7539. else {
  7540. // This is a merge at a deeper level
  7541. return new Merge(this.source, newEmptyPath(), childTree);
  7542. }
  7543. }
  7544. else {
  7545. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7546. return new Merge(this.source, pathPopFront(this.path), this.children);
  7547. }
  7548. };
  7549. Merge.prototype.toString = function () {
  7550. return ('Operation(' +
  7551. this.path +
  7552. ': ' +
  7553. this.source.toString() +
  7554. ' merge: ' +
  7555. this.children.toString() +
  7556. ')');
  7557. };
  7558. return Merge;
  7559. }());
  7560. /**
  7561. * @license
  7562. * Copyright 2017 Google LLC
  7563. *
  7564. * Licensed under the Apache License, Version 2.0 (the "License");
  7565. * you may not use this file except in compliance with the License.
  7566. * You may obtain a copy of the License at
  7567. *
  7568. * http://www.apache.org/licenses/LICENSE-2.0
  7569. *
  7570. * Unless required by applicable law or agreed to in writing, software
  7571. * distributed under the License is distributed on an "AS IS" BASIS,
  7572. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7573. * See the License for the specific language governing permissions and
  7574. * limitations under the License.
  7575. */
  7576. /**
  7577. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7578. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7579. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7580. * whether a node potentially had children removed due to a filter.
  7581. */
  7582. var CacheNode = /** @class */ (function () {
  7583. function CacheNode(node_, fullyInitialized_, filtered_) {
  7584. this.node_ = node_;
  7585. this.fullyInitialized_ = fullyInitialized_;
  7586. this.filtered_ = filtered_;
  7587. }
  7588. /**
  7589. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7590. */
  7591. CacheNode.prototype.isFullyInitialized = function () {
  7592. return this.fullyInitialized_;
  7593. };
  7594. /**
  7595. * Returns whether this node is potentially missing children due to a filter applied to the node
  7596. */
  7597. CacheNode.prototype.isFiltered = function () {
  7598. return this.filtered_;
  7599. };
  7600. CacheNode.prototype.isCompleteForPath = function (path) {
  7601. if (pathIsEmpty(path)) {
  7602. return this.isFullyInitialized() && !this.filtered_;
  7603. }
  7604. var childKey = pathGetFront(path);
  7605. return this.isCompleteForChild(childKey);
  7606. };
  7607. CacheNode.prototype.isCompleteForChild = function (key) {
  7608. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7609. };
  7610. CacheNode.prototype.getNode = function () {
  7611. return this.node_;
  7612. };
  7613. return CacheNode;
  7614. }());
  7615. /**
  7616. * @license
  7617. * Copyright 2017 Google LLC
  7618. *
  7619. * Licensed under the Apache License, Version 2.0 (the "License");
  7620. * you may not use this file except in compliance with the License.
  7621. * You may obtain a copy of the License at
  7622. *
  7623. * http://www.apache.org/licenses/LICENSE-2.0
  7624. *
  7625. * Unless required by applicable law or agreed to in writing, software
  7626. * distributed under the License is distributed on an "AS IS" BASIS,
  7627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7628. * See the License for the specific language governing permissions and
  7629. * limitations under the License.
  7630. */
  7631. /**
  7632. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7633. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7634. * for details.
  7635. *
  7636. */
  7637. var EventGenerator = /** @class */ (function () {
  7638. function EventGenerator(query_) {
  7639. this.query_ = query_;
  7640. this.index_ = this.query_._queryParams.getIndex();
  7641. }
  7642. return EventGenerator;
  7643. }());
  7644. /**
  7645. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7646. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7647. *
  7648. * Notes:
  7649. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7650. * our index.
  7651. * - prevName will be calculated based on the index ordering.
  7652. */
  7653. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7654. var events = [];
  7655. var moves = [];
  7656. changes.forEach(function (change) {
  7657. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7658. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7659. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7660. }
  7661. });
  7662. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7663. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7664. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7665. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7666. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7667. return events;
  7668. }
  7669. /**
  7670. * Given changes of a single change type, generate the corresponding events.
  7671. */
  7672. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7673. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7674. filteredChanges.sort(function (a, b) {
  7675. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7676. });
  7677. filteredChanges.forEach(function (change) {
  7678. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7679. registrations.forEach(function (registration) {
  7680. if (registration.respondsTo(change.type)) {
  7681. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7682. }
  7683. });
  7684. });
  7685. }
  7686. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7687. if (change.type === 'value' || change.type === 'child_removed') {
  7688. return change;
  7689. }
  7690. else {
  7691. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7692. return change;
  7693. }
  7694. }
  7695. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7696. if (a.childName == null || b.childName == null) {
  7697. throw assertionError('Should only compare child_ events.');
  7698. }
  7699. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7700. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7701. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7702. }
  7703. /**
  7704. * @license
  7705. * Copyright 2017 Google LLC
  7706. *
  7707. * Licensed under the Apache License, Version 2.0 (the "License");
  7708. * you may not use this file except in compliance with the License.
  7709. * You may obtain a copy of the License at
  7710. *
  7711. * http://www.apache.org/licenses/LICENSE-2.0
  7712. *
  7713. * Unless required by applicable law or agreed to in writing, software
  7714. * distributed under the License is distributed on an "AS IS" BASIS,
  7715. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7716. * See the License for the specific language governing permissions and
  7717. * limitations under the License.
  7718. */
  7719. function newViewCache(eventCache, serverCache) {
  7720. return { eventCache: eventCache, serverCache: serverCache };
  7721. }
  7722. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7723. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7724. }
  7725. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7726. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7727. }
  7728. function viewCacheGetCompleteEventSnap(viewCache) {
  7729. return viewCache.eventCache.isFullyInitialized()
  7730. ? viewCache.eventCache.getNode()
  7731. : null;
  7732. }
  7733. function viewCacheGetCompleteServerSnap(viewCache) {
  7734. return viewCache.serverCache.isFullyInitialized()
  7735. ? viewCache.serverCache.getNode()
  7736. : null;
  7737. }
  7738. /**
  7739. * @license
  7740. * Copyright 2017 Google LLC
  7741. *
  7742. * Licensed under the Apache License, Version 2.0 (the "License");
  7743. * you may not use this file except in compliance with the License.
  7744. * You may obtain a copy of the License at
  7745. *
  7746. * http://www.apache.org/licenses/LICENSE-2.0
  7747. *
  7748. * Unless required by applicable law or agreed to in writing, software
  7749. * distributed under the License is distributed on an "AS IS" BASIS,
  7750. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7751. * See the License for the specific language governing permissions and
  7752. * limitations under the License.
  7753. */
  7754. var emptyChildrenSingleton;
  7755. /**
  7756. * Singleton empty children collection.
  7757. *
  7758. */
  7759. var EmptyChildren = function () {
  7760. if (!emptyChildrenSingleton) {
  7761. emptyChildrenSingleton = new SortedMap(stringCompare);
  7762. }
  7763. return emptyChildrenSingleton;
  7764. };
  7765. /**
  7766. * A tree with immutable elements.
  7767. */
  7768. var ImmutableTree = /** @class */ (function () {
  7769. function ImmutableTree(value, children) {
  7770. if (children === void 0) { children = EmptyChildren(); }
  7771. this.value = value;
  7772. this.children = children;
  7773. }
  7774. ImmutableTree.fromObject = function (obj) {
  7775. var tree = new ImmutableTree(null);
  7776. each(obj, function (childPath, childSnap) {
  7777. tree = tree.set(new Path(childPath), childSnap);
  7778. });
  7779. return tree;
  7780. };
  7781. /**
  7782. * True if the value is empty and there are no children
  7783. */
  7784. ImmutableTree.prototype.isEmpty = function () {
  7785. return this.value === null && this.children.isEmpty();
  7786. };
  7787. /**
  7788. * Given a path and predicate, return the first node and the path to that node
  7789. * where the predicate returns true.
  7790. *
  7791. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7792. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7793. *
  7794. * @param relativePath - The remainder of the path
  7795. * @param predicate - The predicate to satisfy to return a node
  7796. */
  7797. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7798. if (this.value != null && predicate(this.value)) {
  7799. return { path: newEmptyPath(), value: this.value };
  7800. }
  7801. else {
  7802. if (pathIsEmpty(relativePath)) {
  7803. return null;
  7804. }
  7805. else {
  7806. var front = pathGetFront(relativePath);
  7807. var child = this.children.get(front);
  7808. if (child !== null) {
  7809. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7810. if (childExistingPathAndValue != null) {
  7811. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7812. return { path: fullPath, value: childExistingPathAndValue.value };
  7813. }
  7814. else {
  7815. return null;
  7816. }
  7817. }
  7818. else {
  7819. return null;
  7820. }
  7821. }
  7822. }
  7823. };
  7824. /**
  7825. * Find, if it exists, the shortest subpath of the given path that points a defined
  7826. * value in the tree
  7827. */
  7828. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7829. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7830. };
  7831. /**
  7832. * @returns The subtree at the given path
  7833. */
  7834. ImmutableTree.prototype.subtree = function (relativePath) {
  7835. if (pathIsEmpty(relativePath)) {
  7836. return this;
  7837. }
  7838. else {
  7839. var front = pathGetFront(relativePath);
  7840. var childTree = this.children.get(front);
  7841. if (childTree !== null) {
  7842. return childTree.subtree(pathPopFront(relativePath));
  7843. }
  7844. else {
  7845. return new ImmutableTree(null);
  7846. }
  7847. }
  7848. };
  7849. /**
  7850. * Sets a value at the specified path.
  7851. *
  7852. * @param relativePath - Path to set value at.
  7853. * @param toSet - Value to set.
  7854. * @returns Resulting tree.
  7855. */
  7856. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7857. if (pathIsEmpty(relativePath)) {
  7858. return new ImmutableTree(toSet, this.children);
  7859. }
  7860. else {
  7861. var front = pathGetFront(relativePath);
  7862. var child = this.children.get(front) || new ImmutableTree(null);
  7863. var newChild = child.set(pathPopFront(relativePath), toSet);
  7864. var newChildren = this.children.insert(front, newChild);
  7865. return new ImmutableTree(this.value, newChildren);
  7866. }
  7867. };
  7868. /**
  7869. * Removes the value at the specified path.
  7870. *
  7871. * @param relativePath - Path to value to remove.
  7872. * @returns Resulting tree.
  7873. */
  7874. ImmutableTree.prototype.remove = function (relativePath) {
  7875. if (pathIsEmpty(relativePath)) {
  7876. if (this.children.isEmpty()) {
  7877. return new ImmutableTree(null);
  7878. }
  7879. else {
  7880. return new ImmutableTree(null, this.children);
  7881. }
  7882. }
  7883. else {
  7884. var front = pathGetFront(relativePath);
  7885. var child = this.children.get(front);
  7886. if (child) {
  7887. var newChild = child.remove(pathPopFront(relativePath));
  7888. var newChildren = void 0;
  7889. if (newChild.isEmpty()) {
  7890. newChildren = this.children.remove(front);
  7891. }
  7892. else {
  7893. newChildren = this.children.insert(front, newChild);
  7894. }
  7895. if (this.value === null && newChildren.isEmpty()) {
  7896. return new ImmutableTree(null);
  7897. }
  7898. else {
  7899. return new ImmutableTree(this.value, newChildren);
  7900. }
  7901. }
  7902. else {
  7903. return this;
  7904. }
  7905. }
  7906. };
  7907. /**
  7908. * Gets a value from the tree.
  7909. *
  7910. * @param relativePath - Path to get value for.
  7911. * @returns Value at path, or null.
  7912. */
  7913. ImmutableTree.prototype.get = function (relativePath) {
  7914. if (pathIsEmpty(relativePath)) {
  7915. return this.value;
  7916. }
  7917. else {
  7918. var front = pathGetFront(relativePath);
  7919. var child = this.children.get(front);
  7920. if (child) {
  7921. return child.get(pathPopFront(relativePath));
  7922. }
  7923. else {
  7924. return null;
  7925. }
  7926. }
  7927. };
  7928. /**
  7929. * Replace the subtree at the specified path with the given new tree.
  7930. *
  7931. * @param relativePath - Path to replace subtree for.
  7932. * @param newTree - New tree.
  7933. * @returns Resulting tree.
  7934. */
  7935. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7936. if (pathIsEmpty(relativePath)) {
  7937. return newTree;
  7938. }
  7939. else {
  7940. var front = pathGetFront(relativePath);
  7941. var child = this.children.get(front) || new ImmutableTree(null);
  7942. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7943. var newChildren = void 0;
  7944. if (newChild.isEmpty()) {
  7945. newChildren = this.children.remove(front);
  7946. }
  7947. else {
  7948. newChildren = this.children.insert(front, newChild);
  7949. }
  7950. return new ImmutableTree(this.value, newChildren);
  7951. }
  7952. };
  7953. /**
  7954. * Performs a depth first fold on this tree. Transforms a tree into a single
  7955. * value, given a function that operates on the path to a node, an optional
  7956. * current value, and a map of child names to folded subtrees
  7957. */
  7958. ImmutableTree.prototype.fold = function (fn) {
  7959. return this.fold_(newEmptyPath(), fn);
  7960. };
  7961. /**
  7962. * Recursive helper for public-facing fold() method
  7963. */
  7964. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7965. var accum = {};
  7966. this.children.inorderTraversal(function (childKey, childTree) {
  7967. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7968. });
  7969. return fn(pathSoFar, this.value, accum);
  7970. };
  7971. /**
  7972. * Find the first matching value on the given path. Return the result of applying f to it.
  7973. */
  7974. ImmutableTree.prototype.findOnPath = function (path, f) {
  7975. return this.findOnPath_(path, newEmptyPath(), f);
  7976. };
  7977. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7978. var result = this.value ? f(pathSoFar, this.value) : false;
  7979. if (result) {
  7980. return result;
  7981. }
  7982. else {
  7983. if (pathIsEmpty(pathToFollow)) {
  7984. return null;
  7985. }
  7986. else {
  7987. var front = pathGetFront(pathToFollow);
  7988. var nextChild = this.children.get(front);
  7989. if (nextChild) {
  7990. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7991. }
  7992. else {
  7993. return null;
  7994. }
  7995. }
  7996. }
  7997. };
  7998. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  7999. return this.foreachOnPath_(path, newEmptyPath(), f);
  8000. };
  8001. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8002. if (pathIsEmpty(pathToFollow)) {
  8003. return this;
  8004. }
  8005. else {
  8006. if (this.value) {
  8007. f(currentRelativePath, this.value);
  8008. }
  8009. var front = pathGetFront(pathToFollow);
  8010. var nextChild = this.children.get(front);
  8011. if (nextChild) {
  8012. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8013. }
  8014. else {
  8015. return new ImmutableTree(null);
  8016. }
  8017. }
  8018. };
  8019. /**
  8020. * Calls the given function for each node in the tree that has a value.
  8021. *
  8022. * @param f - A function to be called with the path from the root of the tree to
  8023. * a node, and the value at that node. Called in depth-first order.
  8024. */
  8025. ImmutableTree.prototype.foreach = function (f) {
  8026. this.foreach_(newEmptyPath(), f);
  8027. };
  8028. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8029. this.children.inorderTraversal(function (childName, childTree) {
  8030. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8031. });
  8032. if (this.value) {
  8033. f(currentRelativePath, this.value);
  8034. }
  8035. };
  8036. ImmutableTree.prototype.foreachChild = function (f) {
  8037. this.children.inorderTraversal(function (childName, childTree) {
  8038. if (childTree.value) {
  8039. f(childName, childTree.value);
  8040. }
  8041. });
  8042. };
  8043. return ImmutableTree;
  8044. }());
  8045. /**
  8046. * @license
  8047. * Copyright 2017 Google LLC
  8048. *
  8049. * Licensed under the Apache License, Version 2.0 (the "License");
  8050. * you may not use this file except in compliance with the License.
  8051. * You may obtain a copy of the License at
  8052. *
  8053. * http://www.apache.org/licenses/LICENSE-2.0
  8054. *
  8055. * Unless required by applicable law or agreed to in writing, software
  8056. * distributed under the License is distributed on an "AS IS" BASIS,
  8057. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8058. * See the License for the specific language governing permissions and
  8059. * limitations under the License.
  8060. */
  8061. /**
  8062. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8063. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8064. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8065. * to reflect the write added.
  8066. */
  8067. var CompoundWrite = /** @class */ (function () {
  8068. function CompoundWrite(writeTree_) {
  8069. this.writeTree_ = writeTree_;
  8070. }
  8071. CompoundWrite.empty = function () {
  8072. return new CompoundWrite(new ImmutableTree(null));
  8073. };
  8074. return CompoundWrite;
  8075. }());
  8076. function compoundWriteAddWrite(compoundWrite, path, node) {
  8077. if (pathIsEmpty(path)) {
  8078. return new CompoundWrite(new ImmutableTree(node));
  8079. }
  8080. else {
  8081. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8082. if (rootmost != null) {
  8083. var rootMostPath = rootmost.path;
  8084. var value = rootmost.value;
  8085. var relativePath = newRelativePath(rootMostPath, path);
  8086. value = value.updateChild(relativePath, node);
  8087. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8088. }
  8089. else {
  8090. var subtree = new ImmutableTree(node);
  8091. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8092. return new CompoundWrite(newWriteTree);
  8093. }
  8094. }
  8095. }
  8096. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8097. var newWrite = compoundWrite;
  8098. each(updates, function (childKey, node) {
  8099. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8100. });
  8101. return newWrite;
  8102. }
  8103. /**
  8104. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8105. * location, which must be removed by calling this method with that path.
  8106. *
  8107. * @param compoundWrite - The CompoundWrite to remove.
  8108. * @param path - The path at which a write and all deeper writes should be removed
  8109. * @returns The new CompoundWrite with the removed path
  8110. */
  8111. function compoundWriteRemoveWrite(compoundWrite, path) {
  8112. if (pathIsEmpty(path)) {
  8113. return CompoundWrite.empty();
  8114. }
  8115. else {
  8116. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8117. return new CompoundWrite(newWriteTree);
  8118. }
  8119. }
  8120. /**
  8121. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8122. * considered "complete".
  8123. *
  8124. * @param compoundWrite - The CompoundWrite to check.
  8125. * @param path - The path to check for
  8126. * @returns Whether there is a complete write at that path
  8127. */
  8128. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8129. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8130. }
  8131. /**
  8132. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8133. * writes from deeper paths, but will return child nodes from a more shallow path.
  8134. *
  8135. * @param compoundWrite - The CompoundWrite to get the node from.
  8136. * @param path - The path to get a complete write
  8137. * @returns The node if complete at that path, or null otherwise.
  8138. */
  8139. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8140. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8141. if (rootmost != null) {
  8142. return compoundWrite.writeTree_
  8143. .get(rootmost.path)
  8144. .getChild(newRelativePath(rootmost.path, path));
  8145. }
  8146. else {
  8147. return null;
  8148. }
  8149. }
  8150. /**
  8151. * Returns all children that are guaranteed to be a complete overwrite.
  8152. *
  8153. * @param compoundWrite - The CompoundWrite to get children from.
  8154. * @returns A list of all complete children.
  8155. */
  8156. function compoundWriteGetCompleteChildren(compoundWrite) {
  8157. var children = [];
  8158. var node = compoundWrite.writeTree_.value;
  8159. if (node != null) {
  8160. // If it's a leaf node, it has no children; so nothing to do.
  8161. if (!node.isLeafNode()) {
  8162. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8163. children.push(new NamedNode(childName, childNode));
  8164. });
  8165. }
  8166. }
  8167. else {
  8168. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8169. if (childTree.value != null) {
  8170. children.push(new NamedNode(childName, childTree.value));
  8171. }
  8172. });
  8173. }
  8174. return children;
  8175. }
  8176. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8177. if (pathIsEmpty(path)) {
  8178. return compoundWrite;
  8179. }
  8180. else {
  8181. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8182. if (shadowingNode != null) {
  8183. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8184. }
  8185. else {
  8186. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8187. }
  8188. }
  8189. }
  8190. /**
  8191. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8192. * @returns Whether this CompoundWrite is empty
  8193. */
  8194. function compoundWriteIsEmpty(compoundWrite) {
  8195. return compoundWrite.writeTree_.isEmpty();
  8196. }
  8197. /**
  8198. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8199. * node
  8200. * @param node - The node to apply this CompoundWrite to
  8201. * @returns The node with all writes applied
  8202. */
  8203. function compoundWriteApply(compoundWrite, node) {
  8204. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8205. }
  8206. function applySubtreeWrite(relativePath, writeTree, node) {
  8207. if (writeTree.value != null) {
  8208. // Since there a write is always a leaf, we're done here
  8209. return node.updateChild(relativePath, writeTree.value);
  8210. }
  8211. else {
  8212. var priorityWrite_1 = null;
  8213. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8214. if (childKey === '.priority') {
  8215. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8216. // to apply priorities to empty nodes that are later filled
  8217. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8218. priorityWrite_1 = childTree.value;
  8219. }
  8220. else {
  8221. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8222. }
  8223. });
  8224. // If there was a priority write, we only apply it if the node is not empty
  8225. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8226. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8227. }
  8228. return node;
  8229. }
  8230. }
  8231. /**
  8232. * @license
  8233. * Copyright 2017 Google LLC
  8234. *
  8235. * Licensed under the Apache License, Version 2.0 (the "License");
  8236. * you may not use this file except in compliance with the License.
  8237. * You may obtain a copy of the License at
  8238. *
  8239. * http://www.apache.org/licenses/LICENSE-2.0
  8240. *
  8241. * Unless required by applicable law or agreed to in writing, software
  8242. * distributed under the License is distributed on an "AS IS" BASIS,
  8243. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8244. * See the License for the specific language governing permissions and
  8245. * limitations under the License.
  8246. */
  8247. /**
  8248. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8249. *
  8250. */
  8251. function writeTreeChildWrites(writeTree, path) {
  8252. return newWriteTreeRef(path, writeTree);
  8253. }
  8254. /**
  8255. * Record a new overwrite from user code.
  8256. *
  8257. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8258. */
  8259. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8260. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8261. if (visible === undefined) {
  8262. visible = true;
  8263. }
  8264. writeTree.allWrites.push({
  8265. path: path,
  8266. snap: snap,
  8267. writeId: writeId,
  8268. visible: visible
  8269. });
  8270. if (visible) {
  8271. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8272. }
  8273. writeTree.lastWriteId = writeId;
  8274. }
  8275. /**
  8276. * Record a new merge from user code.
  8277. */
  8278. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8279. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8280. writeTree.allWrites.push({
  8281. path: path,
  8282. children: changedChildren,
  8283. writeId: writeId,
  8284. visible: true
  8285. });
  8286. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8287. writeTree.lastWriteId = writeId;
  8288. }
  8289. function writeTreeGetWrite(writeTree, writeId) {
  8290. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8291. var record = writeTree.allWrites[i];
  8292. if (record.writeId === writeId) {
  8293. return record;
  8294. }
  8295. }
  8296. return null;
  8297. }
  8298. /**
  8299. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8300. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8301. *
  8302. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8303. * events as a result).
  8304. */
  8305. function writeTreeRemoveWrite(writeTree, writeId) {
  8306. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8307. // out of order.
  8308. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8309. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8310. var idx = writeTree.allWrites.findIndex(function (s) {
  8311. return s.writeId === writeId;
  8312. });
  8313. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8314. var writeToRemove = writeTree.allWrites[idx];
  8315. writeTree.allWrites.splice(idx, 1);
  8316. var removedWriteWasVisible = writeToRemove.visible;
  8317. var removedWriteOverlapsWithOtherWrites = false;
  8318. var i = writeTree.allWrites.length - 1;
  8319. while (removedWriteWasVisible && i >= 0) {
  8320. var currentWrite = writeTree.allWrites[i];
  8321. if (currentWrite.visible) {
  8322. if (i >= idx &&
  8323. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8324. // The removed write was completely shadowed by a subsequent write.
  8325. removedWriteWasVisible = false;
  8326. }
  8327. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8328. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8329. removedWriteOverlapsWithOtherWrites = true;
  8330. }
  8331. }
  8332. i--;
  8333. }
  8334. if (!removedWriteWasVisible) {
  8335. return false;
  8336. }
  8337. else if (removedWriteOverlapsWithOtherWrites) {
  8338. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8339. writeTreeResetTree_(writeTree);
  8340. return true;
  8341. }
  8342. else {
  8343. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8344. if (writeToRemove.snap) {
  8345. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8346. }
  8347. else {
  8348. var children = writeToRemove.children;
  8349. each(children, function (childName) {
  8350. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8351. });
  8352. }
  8353. return true;
  8354. }
  8355. }
  8356. function writeTreeRecordContainsPath_(writeRecord, path) {
  8357. if (writeRecord.snap) {
  8358. return pathContains(writeRecord.path, path);
  8359. }
  8360. else {
  8361. for (var childName in writeRecord.children) {
  8362. if (writeRecord.children.hasOwnProperty(childName) &&
  8363. pathContains(pathChild(writeRecord.path, childName), path)) {
  8364. return true;
  8365. }
  8366. }
  8367. return false;
  8368. }
  8369. }
  8370. /**
  8371. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8372. */
  8373. function writeTreeResetTree_(writeTree) {
  8374. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8375. if (writeTree.allWrites.length > 0) {
  8376. writeTree.lastWriteId =
  8377. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8378. }
  8379. else {
  8380. writeTree.lastWriteId = -1;
  8381. }
  8382. }
  8383. /**
  8384. * The default filter used when constructing the tree. Keep everything that's visible.
  8385. */
  8386. function writeTreeDefaultFilter_(write) {
  8387. return write.visible;
  8388. }
  8389. /**
  8390. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8391. * event data at that path.
  8392. */
  8393. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8394. var compoundWrite = CompoundWrite.empty();
  8395. for (var i = 0; i < writes.length; ++i) {
  8396. var write = writes[i];
  8397. // Theory, a later set will either:
  8398. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8399. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8400. if (filter(write)) {
  8401. var writePath = write.path;
  8402. var relativePath = void 0;
  8403. if (write.snap) {
  8404. if (pathContains(treeRoot, writePath)) {
  8405. relativePath = newRelativePath(treeRoot, writePath);
  8406. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8407. }
  8408. else if (pathContains(writePath, treeRoot)) {
  8409. relativePath = newRelativePath(writePath, treeRoot);
  8410. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8411. }
  8412. else ;
  8413. }
  8414. else if (write.children) {
  8415. if (pathContains(treeRoot, writePath)) {
  8416. relativePath = newRelativePath(treeRoot, writePath);
  8417. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8418. }
  8419. else if (pathContains(writePath, treeRoot)) {
  8420. relativePath = newRelativePath(writePath, treeRoot);
  8421. if (pathIsEmpty(relativePath)) {
  8422. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8423. }
  8424. else {
  8425. var child = safeGet(write.children, pathGetFront(relativePath));
  8426. if (child) {
  8427. // There exists a child in this node that matches the root path
  8428. var deepNode = child.getChild(pathPopFront(relativePath));
  8429. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8430. }
  8431. }
  8432. }
  8433. else ;
  8434. }
  8435. else {
  8436. throw assertionError('WriteRecord should have .snap or .children');
  8437. }
  8438. }
  8439. }
  8440. return compoundWrite;
  8441. }
  8442. /**
  8443. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8444. * writes), attempt to calculate a complete snapshot for the given path
  8445. *
  8446. * @param writeIdsToExclude - An optional set to be excluded
  8447. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8448. */
  8449. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8450. if (!writeIdsToExclude && !includeHiddenWrites) {
  8451. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8452. if (shadowingNode != null) {
  8453. return shadowingNode;
  8454. }
  8455. else {
  8456. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8457. if (compoundWriteIsEmpty(subMerge)) {
  8458. return completeServerCache;
  8459. }
  8460. else if (completeServerCache == null &&
  8461. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8462. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8463. return null;
  8464. }
  8465. else {
  8466. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8467. return compoundWriteApply(subMerge, layeredCache);
  8468. }
  8469. }
  8470. }
  8471. else {
  8472. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8473. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8474. return completeServerCache;
  8475. }
  8476. else {
  8477. // If the server cache is null, and we don't have a complete cache, we need to return null
  8478. if (!includeHiddenWrites &&
  8479. completeServerCache == null &&
  8480. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8481. return null;
  8482. }
  8483. else {
  8484. var filter = function (write) {
  8485. return ((write.visible || includeHiddenWrites) &&
  8486. (!writeIdsToExclude ||
  8487. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8488. (pathContains(write.path, treePath) ||
  8489. pathContains(treePath, write.path)));
  8490. };
  8491. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8492. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8493. return compoundWriteApply(mergeAtPath, layeredCache);
  8494. }
  8495. }
  8496. }
  8497. }
  8498. /**
  8499. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8500. * Used when creating new views, to pre-fill their complete event children snapshot.
  8501. */
  8502. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8503. var completeChildren = ChildrenNode.EMPTY_NODE;
  8504. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8505. if (topLevelSet) {
  8506. if (!topLevelSet.isLeafNode()) {
  8507. // we're shadowing everything. Return the children.
  8508. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8509. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8510. });
  8511. }
  8512. return completeChildren;
  8513. }
  8514. else if (completeServerChildren) {
  8515. // Layer any children we have on top of this
  8516. // We know we don't have a top-level set, so just enumerate existing children
  8517. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8518. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8519. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8520. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8521. });
  8522. // Add any complete children we have from the set
  8523. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8524. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8525. });
  8526. return completeChildren;
  8527. }
  8528. else {
  8529. // We don't have anything to layer on top of. Layer on any children we have
  8530. // Note that we can return an empty snap if we have a defined delete
  8531. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8532. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8533. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8534. });
  8535. return completeChildren;
  8536. }
  8537. }
  8538. /**
  8539. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8540. * applied to the event cache.
  8541. *
  8542. * Possibilities:
  8543. *
  8544. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8545. *
  8546. * 2. Some write is completely shadowing. No events to be raised
  8547. *
  8548. * 3. Is partially shadowed. Events
  8549. *
  8550. * Either existingEventSnap or existingServerSnap must exist
  8551. */
  8552. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8553. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8554. var path = pathChild(treePath, childPath);
  8555. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8556. // At this point we can probably guarantee that we're in case 2, meaning no events
  8557. // May need to check visibility while doing the findRootMostValueAndPath call
  8558. return null;
  8559. }
  8560. else {
  8561. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8562. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8563. if (compoundWriteIsEmpty(childMerge)) {
  8564. // We're not shadowing at all. Case 1
  8565. return existingServerSnap.getChild(childPath);
  8566. }
  8567. else {
  8568. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8569. // However this is tricky to find out, since user updates don't necessary change the server
  8570. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8571. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8572. // only check if the updates change the serverNode.
  8573. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8574. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8575. }
  8576. }
  8577. }
  8578. /**
  8579. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8580. * complete child for this ChildKey.
  8581. */
  8582. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8583. var path = pathChild(treePath, childKey);
  8584. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8585. if (shadowingNode != null) {
  8586. return shadowingNode;
  8587. }
  8588. else {
  8589. if (existingServerSnap.isCompleteForChild(childKey)) {
  8590. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8591. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8592. }
  8593. else {
  8594. return null;
  8595. }
  8596. }
  8597. }
  8598. /**
  8599. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8600. * a higher path, this will return the child of that write relative to the write and this path.
  8601. * Returns null if there is no write at this path.
  8602. */
  8603. function writeTreeShadowingWrite(writeTree, path) {
  8604. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8605. }
  8606. /**
  8607. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8608. * the window, but may now be in the window.
  8609. */
  8610. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8611. var toIterate;
  8612. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8613. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8614. if (shadowingNode != null) {
  8615. toIterate = shadowingNode;
  8616. }
  8617. else if (completeServerData != null) {
  8618. toIterate = compoundWriteApply(merge, completeServerData);
  8619. }
  8620. else {
  8621. // no children to iterate on
  8622. return [];
  8623. }
  8624. toIterate = toIterate.withIndex(index);
  8625. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8626. var nodes = [];
  8627. var cmp = index.getCompare();
  8628. var iter = reverse
  8629. ? toIterate.getReverseIteratorFrom(startPost, index)
  8630. : toIterate.getIteratorFrom(startPost, index);
  8631. var next = iter.getNext();
  8632. while (next && nodes.length < count) {
  8633. if (cmp(next, startPost) !== 0) {
  8634. nodes.push(next);
  8635. }
  8636. next = iter.getNext();
  8637. }
  8638. return nodes;
  8639. }
  8640. else {
  8641. return [];
  8642. }
  8643. }
  8644. function newWriteTree() {
  8645. return {
  8646. visibleWrites: CompoundWrite.empty(),
  8647. allWrites: [],
  8648. lastWriteId: -1
  8649. };
  8650. }
  8651. /**
  8652. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8653. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8654. * can lead to a more expensive calculation.
  8655. *
  8656. * @param writeIdsToExclude - Optional writes to exclude.
  8657. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8658. */
  8659. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8660. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8661. }
  8662. /**
  8663. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8664. * mix of the given server data and write data.
  8665. *
  8666. */
  8667. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8668. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8669. }
  8670. /**
  8671. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8672. * if anything, needs to be applied to the event cache.
  8673. *
  8674. * Possibilities:
  8675. *
  8676. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8677. *
  8678. * 2. Some write is completely shadowing. No events to be raised
  8679. *
  8680. * 3. Is partially shadowed. Events should be raised
  8681. *
  8682. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8683. *
  8684. *
  8685. */
  8686. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8687. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8688. }
  8689. /**
  8690. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8691. * a higher path, this will return the child of that write relative to the write and this path.
  8692. * Returns null if there is no write at this path.
  8693. *
  8694. */
  8695. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8696. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8697. }
  8698. /**
  8699. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8700. * the window, but may now be in the window
  8701. */
  8702. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8703. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8704. }
  8705. /**
  8706. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8707. * complete child for this ChildKey.
  8708. */
  8709. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8710. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8711. }
  8712. /**
  8713. * Return a WriteTreeRef for a child.
  8714. */
  8715. function writeTreeRefChild(writeTreeRef, childName) {
  8716. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8717. }
  8718. function newWriteTreeRef(path, writeTree) {
  8719. return {
  8720. treePath: path,
  8721. writeTree: writeTree
  8722. };
  8723. }
  8724. /**
  8725. * @license
  8726. * Copyright 2017 Google LLC
  8727. *
  8728. * Licensed under the Apache License, Version 2.0 (the "License");
  8729. * you may not use this file except in compliance with the License.
  8730. * You may obtain a copy of the License at
  8731. *
  8732. * http://www.apache.org/licenses/LICENSE-2.0
  8733. *
  8734. * Unless required by applicable law or agreed to in writing, software
  8735. * distributed under the License is distributed on an "AS IS" BASIS,
  8736. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8737. * See the License for the specific language governing permissions and
  8738. * limitations under the License.
  8739. */
  8740. var ChildChangeAccumulator = /** @class */ (function () {
  8741. function ChildChangeAccumulator() {
  8742. this.changeMap = new Map();
  8743. }
  8744. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8745. var type = change.type;
  8746. var childKey = change.childName;
  8747. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8748. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8749. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8750. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8751. var oldChange = this.changeMap.get(childKey);
  8752. if (oldChange) {
  8753. var oldType = oldChange.type;
  8754. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8755. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8756. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8757. }
  8758. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8759. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8760. this.changeMap.delete(childKey);
  8761. }
  8762. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8763. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8764. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8765. }
  8766. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8767. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8768. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8769. }
  8770. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8771. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8772. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8773. }
  8774. else {
  8775. throw assertionError('Illegal combination of changes: ' +
  8776. change +
  8777. ' occurred after ' +
  8778. oldChange);
  8779. }
  8780. }
  8781. else {
  8782. this.changeMap.set(childKey, change);
  8783. }
  8784. };
  8785. ChildChangeAccumulator.prototype.getChanges = function () {
  8786. return Array.from(this.changeMap.values());
  8787. };
  8788. return ChildChangeAccumulator;
  8789. }());
  8790. /**
  8791. * @license
  8792. * Copyright 2017 Google LLC
  8793. *
  8794. * Licensed under the Apache License, Version 2.0 (the "License");
  8795. * you may not use this file except in compliance with the License.
  8796. * You may obtain a copy of the License at
  8797. *
  8798. * http://www.apache.org/licenses/LICENSE-2.0
  8799. *
  8800. * Unless required by applicable law or agreed to in writing, software
  8801. * distributed under the License is distributed on an "AS IS" BASIS,
  8802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8803. * See the License for the specific language governing permissions and
  8804. * limitations under the License.
  8805. */
  8806. /**
  8807. * An implementation of CompleteChildSource that never returns any additional children
  8808. */
  8809. // eslint-disable-next-line @typescript-eslint/naming-convention
  8810. var NoCompleteChildSource_ = /** @class */ (function () {
  8811. function NoCompleteChildSource_() {
  8812. }
  8813. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8814. return null;
  8815. };
  8816. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8817. return null;
  8818. };
  8819. return NoCompleteChildSource_;
  8820. }());
  8821. /**
  8822. * Singleton instance.
  8823. */
  8824. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8825. /**
  8826. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8827. * old event caches available to calculate complete children.
  8828. */
  8829. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8830. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8831. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8832. this.writes_ = writes_;
  8833. this.viewCache_ = viewCache_;
  8834. this.optCompleteServerCache_ = optCompleteServerCache_;
  8835. }
  8836. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8837. var node = this.viewCache_.eventCache;
  8838. if (node.isCompleteForChild(childKey)) {
  8839. return node.getNode().getImmediateChild(childKey);
  8840. }
  8841. else {
  8842. var serverNode = this.optCompleteServerCache_ != null
  8843. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8844. : this.viewCache_.serverCache;
  8845. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8846. }
  8847. };
  8848. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8849. var completeServerData = this.optCompleteServerCache_ != null
  8850. ? this.optCompleteServerCache_
  8851. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8852. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8853. if (nodes.length === 0) {
  8854. return null;
  8855. }
  8856. else {
  8857. return nodes[0];
  8858. }
  8859. };
  8860. return WriteTreeCompleteChildSource;
  8861. }());
  8862. /**
  8863. * @license
  8864. * Copyright 2017 Google LLC
  8865. *
  8866. * Licensed under the Apache License, Version 2.0 (the "License");
  8867. * you may not use this file except in compliance with the License.
  8868. * You may obtain a copy of the License at
  8869. *
  8870. * http://www.apache.org/licenses/LICENSE-2.0
  8871. *
  8872. * Unless required by applicable law or agreed to in writing, software
  8873. * distributed under the License is distributed on an "AS IS" BASIS,
  8874. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8875. * See the License for the specific language governing permissions and
  8876. * limitations under the License.
  8877. */
  8878. function newViewProcessor(filter) {
  8879. return { filter: filter };
  8880. }
  8881. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8882. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8883. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8884. }
  8885. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8886. var accumulator = new ChildChangeAccumulator();
  8887. var newViewCache, filterServerNode;
  8888. if (operation.type === OperationType.OVERWRITE) {
  8889. var overwrite = operation;
  8890. if (overwrite.source.fromUser) {
  8891. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8892. }
  8893. else {
  8894. assert(overwrite.source.fromServer, 'Unknown source.');
  8895. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8896. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8897. // again
  8898. filterServerNode =
  8899. overwrite.source.tagged ||
  8900. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8901. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8902. }
  8903. }
  8904. else if (operation.type === OperationType.MERGE) {
  8905. var merge = operation;
  8906. if (merge.source.fromUser) {
  8907. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8908. }
  8909. else {
  8910. assert(merge.source.fromServer, 'Unknown source.');
  8911. // We filter the node if it's a tagged update or the node has been previously filtered
  8912. filterServerNode =
  8913. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8914. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8915. }
  8916. }
  8917. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8918. var ackUserWrite = operation;
  8919. if (!ackUserWrite.revert) {
  8920. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8921. }
  8922. else {
  8923. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8924. }
  8925. }
  8926. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8927. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8928. }
  8929. else {
  8930. throw assertionError('Unknown operation type: ' + operation.type);
  8931. }
  8932. var changes = accumulator.getChanges();
  8933. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8934. return { viewCache: newViewCache, changes: changes };
  8935. }
  8936. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8937. var eventSnap = newViewCache.eventCache;
  8938. if (eventSnap.isFullyInitialized()) {
  8939. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8940. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8941. if (accumulator.length > 0 ||
  8942. !oldViewCache.eventCache.isFullyInitialized() ||
  8943. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8944. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8945. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8946. }
  8947. }
  8948. }
  8949. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8950. var oldEventSnap = viewCache.eventCache;
  8951. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8952. // we have a shadowing write, ignore changes
  8953. return viewCache;
  8954. }
  8955. else {
  8956. var newEventCache = void 0, serverNode = void 0;
  8957. if (pathIsEmpty(changePath)) {
  8958. // TODO: figure out how this plays with "sliding ack windows"
  8959. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8960. if (viewCache.serverCache.isFiltered()) {
  8961. // We need to special case this, because we need to only apply writes to complete children, or
  8962. // we might end up raising events for incomplete children. If the server data is filtered deep
  8963. // writes cannot be guaranteed to be complete
  8964. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8965. var completeChildren = serverCache instanceof ChildrenNode
  8966. ? serverCache
  8967. : ChildrenNode.EMPTY_NODE;
  8968. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8969. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8970. }
  8971. else {
  8972. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8973. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8974. }
  8975. }
  8976. else {
  8977. var childKey = pathGetFront(changePath);
  8978. if (childKey === '.priority') {
  8979. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8980. var oldEventNode = oldEventSnap.getNode();
  8981. serverNode = viewCache.serverCache.getNode();
  8982. // we might have overwrites for this priority
  8983. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8984. if (updatedPriority != null) {
  8985. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8986. }
  8987. else {
  8988. // priority didn't change, keep old node
  8989. newEventCache = oldEventSnap.getNode();
  8990. }
  8991. }
  8992. else {
  8993. var childChangePath = pathPopFront(changePath);
  8994. // update child
  8995. var newEventChild = void 0;
  8996. if (oldEventSnap.isCompleteForChild(childKey)) {
  8997. serverNode = viewCache.serverCache.getNode();
  8998. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8999. if (eventChildUpdate != null) {
  9000. newEventChild = oldEventSnap
  9001. .getNode()
  9002. .getImmediateChild(childKey)
  9003. .updateChild(childChangePath, eventChildUpdate);
  9004. }
  9005. else {
  9006. // Nothing changed, just keep the old child
  9007. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9008. }
  9009. }
  9010. else {
  9011. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9012. }
  9013. if (newEventChild != null) {
  9014. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9015. }
  9016. else {
  9017. // no complete child available or no change
  9018. newEventCache = oldEventSnap.getNode();
  9019. }
  9020. }
  9021. }
  9022. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9023. }
  9024. }
  9025. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9026. var oldServerSnap = oldViewCache.serverCache;
  9027. var newServerCache;
  9028. var serverFilter = filterServerNode
  9029. ? viewProcessor.filter
  9030. : viewProcessor.filter.getIndexedFilter();
  9031. if (pathIsEmpty(changePath)) {
  9032. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9033. }
  9034. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9035. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9036. var newServerNode = oldServerSnap
  9037. .getNode()
  9038. .updateChild(changePath, changedSnap);
  9039. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9040. }
  9041. else {
  9042. var childKey = pathGetFront(changePath);
  9043. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9044. pathGetLength(changePath) > 1) {
  9045. // We don't update incomplete nodes with updates intended for other listeners
  9046. return oldViewCache;
  9047. }
  9048. var childChangePath = pathPopFront(changePath);
  9049. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9050. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9051. if (childKey === '.priority') {
  9052. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9053. }
  9054. else {
  9055. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9056. }
  9057. }
  9058. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9059. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9060. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9061. }
  9062. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9063. var oldEventSnap = oldViewCache.eventCache;
  9064. var newViewCache, newEventCache;
  9065. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9066. if (pathIsEmpty(changePath)) {
  9067. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9068. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9069. }
  9070. else {
  9071. var childKey = pathGetFront(changePath);
  9072. if (childKey === '.priority') {
  9073. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9074. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9075. }
  9076. else {
  9077. var childChangePath = pathPopFront(changePath);
  9078. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9079. var newChild = void 0;
  9080. if (pathIsEmpty(childChangePath)) {
  9081. // Child overwrite, we can replace the child
  9082. newChild = changedSnap;
  9083. }
  9084. else {
  9085. var childNode = source.getCompleteChild(childKey);
  9086. if (childNode != null) {
  9087. if (pathGetBack(childChangePath) === '.priority' &&
  9088. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9089. // This is a priority update on an empty node. If this node exists on the server, the
  9090. // server will send down the priority in the update, so ignore for now
  9091. newChild = childNode;
  9092. }
  9093. else {
  9094. newChild = childNode.updateChild(childChangePath, changedSnap);
  9095. }
  9096. }
  9097. else {
  9098. // There is no complete child node available
  9099. newChild = ChildrenNode.EMPTY_NODE;
  9100. }
  9101. }
  9102. if (!oldChild.equals(newChild)) {
  9103. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9104. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9105. }
  9106. else {
  9107. newViewCache = oldViewCache;
  9108. }
  9109. }
  9110. }
  9111. return newViewCache;
  9112. }
  9113. function viewProcessorCacheHasChild(viewCache, childKey) {
  9114. return viewCache.eventCache.isCompleteForChild(childKey);
  9115. }
  9116. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9117. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9118. // window leaving room for new items. It's important we process these changes first, so we
  9119. // iterate the changes twice, first processing any that affect items currently in view.
  9120. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9121. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9122. // not the other.
  9123. var curViewCache = viewCache;
  9124. changedChildren.foreach(function (relativePath, childNode) {
  9125. var writePath = pathChild(path, relativePath);
  9126. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9127. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9128. }
  9129. });
  9130. changedChildren.foreach(function (relativePath, childNode) {
  9131. var writePath = pathChild(path, relativePath);
  9132. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9133. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9134. }
  9135. });
  9136. return curViewCache;
  9137. }
  9138. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9139. merge.foreach(function (relativePath, childNode) {
  9140. node = node.updateChild(relativePath, childNode);
  9141. });
  9142. return node;
  9143. }
  9144. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9145. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9146. // wait for the complete data update coming soon.
  9147. if (viewCache.serverCache.getNode().isEmpty() &&
  9148. !viewCache.serverCache.isFullyInitialized()) {
  9149. return viewCache;
  9150. }
  9151. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9152. // window leaving room for new items. It's important we process these changes first, so we
  9153. // iterate the changes twice, first processing any that affect items currently in view.
  9154. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9155. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9156. // not the other.
  9157. var curViewCache = viewCache;
  9158. var viewMergeTree;
  9159. if (pathIsEmpty(path)) {
  9160. viewMergeTree = changedChildren;
  9161. }
  9162. else {
  9163. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9164. }
  9165. var serverNode = viewCache.serverCache.getNode();
  9166. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9167. if (serverNode.hasChild(childKey)) {
  9168. var serverChild = viewCache.serverCache
  9169. .getNode()
  9170. .getImmediateChild(childKey);
  9171. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9172. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9173. }
  9174. });
  9175. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9176. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9177. childMergeTree.value === null;
  9178. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9179. var serverChild = viewCache.serverCache
  9180. .getNode()
  9181. .getImmediateChild(childKey);
  9182. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9183. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9184. }
  9185. });
  9186. return curViewCache;
  9187. }
  9188. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9189. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9190. return viewCache;
  9191. }
  9192. // Only filter server node if it is currently filtered
  9193. var filterServerNode = viewCache.serverCache.isFiltered();
  9194. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9195. // now that it won't be shadowed.
  9196. var serverCache = viewCache.serverCache;
  9197. if (affectedTree.value != null) {
  9198. // This is an overwrite.
  9199. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9200. serverCache.isCompleteForPath(ackPath)) {
  9201. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9202. }
  9203. else if (pathIsEmpty(ackPath)) {
  9204. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9205. // should just re-apply whatever we have in our cache as a merge.
  9206. var changedChildren_1 = new ImmutableTree(null);
  9207. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9208. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9209. });
  9210. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9211. }
  9212. else {
  9213. return viewCache;
  9214. }
  9215. }
  9216. else {
  9217. // This is a merge.
  9218. var changedChildren_2 = new ImmutableTree(null);
  9219. affectedTree.foreach(function (mergePath, value) {
  9220. var serverCachePath = pathChild(ackPath, mergePath);
  9221. if (serverCache.isCompleteForPath(serverCachePath)) {
  9222. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9223. }
  9224. });
  9225. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9226. }
  9227. }
  9228. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9229. var oldServerNode = viewCache.serverCache;
  9230. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9231. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9232. }
  9233. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9234. var complete;
  9235. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9236. return viewCache;
  9237. }
  9238. else {
  9239. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9240. var oldEventCache = viewCache.eventCache.getNode();
  9241. var newEventCache = void 0;
  9242. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9243. var newNode = void 0;
  9244. if (viewCache.serverCache.isFullyInitialized()) {
  9245. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9246. }
  9247. else {
  9248. var serverChildren = viewCache.serverCache.getNode();
  9249. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9250. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9251. }
  9252. newNode = newNode;
  9253. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9254. }
  9255. else {
  9256. var childKey = pathGetFront(path);
  9257. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9258. if (newChild == null &&
  9259. viewCache.serverCache.isCompleteForChild(childKey)) {
  9260. newChild = oldEventCache.getImmediateChild(childKey);
  9261. }
  9262. if (newChild != null) {
  9263. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9264. }
  9265. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9266. // No complete child available, delete the existing one, if any
  9267. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9268. }
  9269. else {
  9270. newEventCache = oldEventCache;
  9271. }
  9272. if (newEventCache.isEmpty() &&
  9273. viewCache.serverCache.isFullyInitialized()) {
  9274. // We might have reverted all child writes. Maybe the old event was a leaf node
  9275. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9276. if (complete.isLeafNode()) {
  9277. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9278. }
  9279. }
  9280. }
  9281. complete =
  9282. viewCache.serverCache.isFullyInitialized() ||
  9283. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9284. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9285. }
  9286. }
  9287. /**
  9288. * @license
  9289. * Copyright 2017 Google LLC
  9290. *
  9291. * Licensed under the Apache License, Version 2.0 (the "License");
  9292. * you may not use this file except in compliance with the License.
  9293. * You may obtain a copy of the License at
  9294. *
  9295. * http://www.apache.org/licenses/LICENSE-2.0
  9296. *
  9297. * Unless required by applicable law or agreed to in writing, software
  9298. * distributed under the License is distributed on an "AS IS" BASIS,
  9299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9300. * See the License for the specific language governing permissions and
  9301. * limitations under the License.
  9302. */
  9303. /**
  9304. * A view represents a specific location and query that has 1 or more event registrations.
  9305. *
  9306. * It does several things:
  9307. * - Maintains the list of event registrations for this location/query.
  9308. * - Maintains a cache of the data visible for this location/query.
  9309. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9310. * registrations returns the set of events to be raised.
  9311. */
  9312. var View = /** @class */ (function () {
  9313. function View(query_, initialViewCache) {
  9314. this.query_ = query_;
  9315. this.eventRegistrations_ = [];
  9316. var params = this.query_._queryParams;
  9317. var indexFilter = new IndexedFilter(params.getIndex());
  9318. var filter = queryParamsGetNodeFilter(params);
  9319. this.processor_ = newViewProcessor(filter);
  9320. var initialServerCache = initialViewCache.serverCache;
  9321. var initialEventCache = initialViewCache.eventCache;
  9322. // Don't filter server node with other filter than index, wait for tagged listen
  9323. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9324. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9325. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9326. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9327. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9328. this.eventGenerator_ = new EventGenerator(this.query_);
  9329. }
  9330. Object.defineProperty(View.prototype, "query", {
  9331. get: function () {
  9332. return this.query_;
  9333. },
  9334. enumerable: false,
  9335. configurable: true
  9336. });
  9337. return View;
  9338. }());
  9339. function viewGetServerCache(view) {
  9340. return view.viewCache_.serverCache.getNode();
  9341. }
  9342. function viewGetCompleteNode(view) {
  9343. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9344. }
  9345. function viewGetCompleteServerCache(view, path) {
  9346. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9347. if (cache) {
  9348. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9349. // we need to see if it contains the child we're interested in.
  9350. if (view.query._queryParams.loadsAllData() ||
  9351. (!pathIsEmpty(path) &&
  9352. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9353. return cache.getChild(path);
  9354. }
  9355. }
  9356. return null;
  9357. }
  9358. function viewIsEmpty(view) {
  9359. return view.eventRegistrations_.length === 0;
  9360. }
  9361. function viewAddEventRegistration(view, eventRegistration) {
  9362. view.eventRegistrations_.push(eventRegistration);
  9363. }
  9364. /**
  9365. * @param eventRegistration - If null, remove all callbacks.
  9366. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9367. * @returns Cancel events, if cancelError was provided.
  9368. */
  9369. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9370. var cancelEvents = [];
  9371. if (cancelError) {
  9372. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9373. var path_1 = view.query._path;
  9374. view.eventRegistrations_.forEach(function (registration) {
  9375. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9376. if (maybeEvent) {
  9377. cancelEvents.push(maybeEvent);
  9378. }
  9379. });
  9380. }
  9381. if (eventRegistration) {
  9382. var remaining = [];
  9383. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9384. var existing = view.eventRegistrations_[i];
  9385. if (!existing.matches(eventRegistration)) {
  9386. remaining.push(existing);
  9387. }
  9388. else if (eventRegistration.hasAnyCallback()) {
  9389. // We're removing just this one
  9390. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9391. break;
  9392. }
  9393. }
  9394. view.eventRegistrations_ = remaining;
  9395. }
  9396. else {
  9397. view.eventRegistrations_ = [];
  9398. }
  9399. return cancelEvents;
  9400. }
  9401. /**
  9402. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9403. */
  9404. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9405. if (operation.type === OperationType.MERGE &&
  9406. operation.source.queryId !== null) {
  9407. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9408. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9409. }
  9410. var oldViewCache = view.viewCache_;
  9411. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9412. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9413. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9414. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9415. view.viewCache_ = result.viewCache;
  9416. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9417. }
  9418. function viewGetInitialEvents(view, registration) {
  9419. var eventSnap = view.viewCache_.eventCache;
  9420. var initialChanges = [];
  9421. if (!eventSnap.getNode().isLeafNode()) {
  9422. var eventNode = eventSnap.getNode();
  9423. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9424. initialChanges.push(changeChildAdded(key, childNode));
  9425. });
  9426. }
  9427. if (eventSnap.isFullyInitialized()) {
  9428. initialChanges.push(changeValue(eventSnap.getNode()));
  9429. }
  9430. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9431. }
  9432. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9433. var registrations = eventRegistration
  9434. ? [eventRegistration]
  9435. : view.eventRegistrations_;
  9436. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9437. }
  9438. /**
  9439. * @license
  9440. * Copyright 2017 Google LLC
  9441. *
  9442. * Licensed under the Apache License, Version 2.0 (the "License");
  9443. * you may not use this file except in compliance with the License.
  9444. * You may obtain a copy of the License at
  9445. *
  9446. * http://www.apache.org/licenses/LICENSE-2.0
  9447. *
  9448. * Unless required by applicable law or agreed to in writing, software
  9449. * distributed under the License is distributed on an "AS IS" BASIS,
  9450. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9451. * See the License for the specific language governing permissions and
  9452. * limitations under the License.
  9453. */
  9454. var referenceConstructor$1;
  9455. /**
  9456. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9457. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9458. * and user writes (set, transaction, update).
  9459. *
  9460. * It's responsible for:
  9461. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9462. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9463. * applyUserOverwrite, etc.)
  9464. */
  9465. var SyncPoint = /** @class */ (function () {
  9466. function SyncPoint() {
  9467. /**
  9468. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9469. * queryId and the value is the View for that query.
  9470. *
  9471. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9472. */
  9473. this.views = new Map();
  9474. }
  9475. return SyncPoint;
  9476. }());
  9477. function syncPointSetReferenceConstructor(val) {
  9478. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9479. referenceConstructor$1 = val;
  9480. }
  9481. function syncPointGetReferenceConstructor() {
  9482. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9483. return referenceConstructor$1;
  9484. }
  9485. function syncPointIsEmpty(syncPoint) {
  9486. return syncPoint.views.size === 0;
  9487. }
  9488. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9489. var e_1, _a;
  9490. var queryId = operation.source.queryId;
  9491. if (queryId !== null) {
  9492. var view = syncPoint.views.get(queryId);
  9493. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9494. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9495. }
  9496. else {
  9497. var events = [];
  9498. try {
  9499. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9500. var view = _c.value;
  9501. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9502. }
  9503. }
  9504. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9505. finally {
  9506. try {
  9507. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9508. }
  9509. finally { if (e_1) throw e_1.error; }
  9510. }
  9511. return events;
  9512. }
  9513. }
  9514. /**
  9515. * Get a view for the specified query.
  9516. *
  9517. * @param query - The query to return a view for
  9518. * @param writesCache
  9519. * @param serverCache
  9520. * @param serverCacheComplete
  9521. * @returns Events to raise.
  9522. */
  9523. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9524. var queryId = query._queryIdentifier;
  9525. var view = syncPoint.views.get(queryId);
  9526. if (!view) {
  9527. // TODO: make writesCache take flag for complete server node
  9528. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9529. var eventCacheComplete = false;
  9530. if (eventCache) {
  9531. eventCacheComplete = true;
  9532. }
  9533. else if (serverCache instanceof ChildrenNode) {
  9534. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9535. eventCacheComplete = false;
  9536. }
  9537. else {
  9538. eventCache = ChildrenNode.EMPTY_NODE;
  9539. eventCacheComplete = false;
  9540. }
  9541. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9542. return new View(query, viewCache);
  9543. }
  9544. return view;
  9545. }
  9546. /**
  9547. * Add an event callback for the specified query.
  9548. *
  9549. * @param query
  9550. * @param eventRegistration
  9551. * @param writesCache
  9552. * @param serverCache - Complete server cache, if we have it.
  9553. * @param serverCacheComplete
  9554. * @returns Events to raise.
  9555. */
  9556. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9557. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9558. if (!syncPoint.views.has(query._queryIdentifier)) {
  9559. syncPoint.views.set(query._queryIdentifier, view);
  9560. }
  9561. // This is guaranteed to exist now, we just created anything that was missing
  9562. viewAddEventRegistration(view, eventRegistration);
  9563. return viewGetInitialEvents(view, eventRegistration);
  9564. }
  9565. /**
  9566. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9567. *
  9568. * If query is the default query, we'll check all views for the specified eventRegistration.
  9569. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9570. *
  9571. * @param eventRegistration - If null, remove all callbacks.
  9572. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9573. * @returns removed queries and any cancel events
  9574. */
  9575. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9576. var e_2, _a;
  9577. var queryId = query._queryIdentifier;
  9578. var removed = [];
  9579. var cancelEvents = [];
  9580. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9581. if (queryId === 'default') {
  9582. try {
  9583. // When you do ref.off(...), we search all views for the registration to remove.
  9584. for (var _b = __values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9585. var _d = __read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9586. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9587. if (viewIsEmpty(view)) {
  9588. syncPoint.views.delete(viewQueryId);
  9589. // We'll deal with complete views later.
  9590. if (!view.query._queryParams.loadsAllData()) {
  9591. removed.push(view.query);
  9592. }
  9593. }
  9594. }
  9595. }
  9596. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9597. finally {
  9598. try {
  9599. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9600. }
  9601. finally { if (e_2) throw e_2.error; }
  9602. }
  9603. }
  9604. else {
  9605. // remove the callback from the specific view.
  9606. var view = syncPoint.views.get(queryId);
  9607. if (view) {
  9608. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9609. if (viewIsEmpty(view)) {
  9610. syncPoint.views.delete(queryId);
  9611. // We'll deal with complete views later.
  9612. if (!view.query._queryParams.loadsAllData()) {
  9613. removed.push(view.query);
  9614. }
  9615. }
  9616. }
  9617. }
  9618. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9619. // We removed our last complete view.
  9620. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9621. }
  9622. return { removed: removed, events: cancelEvents };
  9623. }
  9624. function syncPointGetQueryViews(syncPoint) {
  9625. var e_3, _a;
  9626. var result = [];
  9627. try {
  9628. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9629. var view = _c.value;
  9630. if (!view.query._queryParams.loadsAllData()) {
  9631. result.push(view);
  9632. }
  9633. }
  9634. }
  9635. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9636. finally {
  9637. try {
  9638. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9639. }
  9640. finally { if (e_3) throw e_3.error; }
  9641. }
  9642. return result;
  9643. }
  9644. /**
  9645. * @param path - The path to the desired complete snapshot
  9646. * @returns A complete cache, if it exists
  9647. */
  9648. function syncPointGetCompleteServerCache(syncPoint, path) {
  9649. var e_4, _a;
  9650. var serverCache = null;
  9651. try {
  9652. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9653. var view = _c.value;
  9654. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9655. }
  9656. }
  9657. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9658. finally {
  9659. try {
  9660. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9661. }
  9662. finally { if (e_4) throw e_4.error; }
  9663. }
  9664. return serverCache;
  9665. }
  9666. function syncPointViewForQuery(syncPoint, query) {
  9667. var params = query._queryParams;
  9668. if (params.loadsAllData()) {
  9669. return syncPointGetCompleteView(syncPoint);
  9670. }
  9671. else {
  9672. var queryId = query._queryIdentifier;
  9673. return syncPoint.views.get(queryId);
  9674. }
  9675. }
  9676. function syncPointViewExistsForQuery(syncPoint, query) {
  9677. return syncPointViewForQuery(syncPoint, query) != null;
  9678. }
  9679. function syncPointHasCompleteView(syncPoint) {
  9680. return syncPointGetCompleteView(syncPoint) != null;
  9681. }
  9682. function syncPointGetCompleteView(syncPoint) {
  9683. var e_5, _a;
  9684. try {
  9685. for (var _b = __values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9686. var view = _c.value;
  9687. if (view.query._queryParams.loadsAllData()) {
  9688. return view;
  9689. }
  9690. }
  9691. }
  9692. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9693. finally {
  9694. try {
  9695. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9696. }
  9697. finally { if (e_5) throw e_5.error; }
  9698. }
  9699. return null;
  9700. }
  9701. /**
  9702. * @license
  9703. * Copyright 2017 Google LLC
  9704. *
  9705. * Licensed under the Apache License, Version 2.0 (the "License");
  9706. * you may not use this file except in compliance with the License.
  9707. * You may obtain a copy of the License at
  9708. *
  9709. * http://www.apache.org/licenses/LICENSE-2.0
  9710. *
  9711. * Unless required by applicable law or agreed to in writing, software
  9712. * distributed under the License is distributed on an "AS IS" BASIS,
  9713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9714. * See the License for the specific language governing permissions and
  9715. * limitations under the License.
  9716. */
  9717. var referenceConstructor;
  9718. function syncTreeSetReferenceConstructor(val) {
  9719. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9720. referenceConstructor = val;
  9721. }
  9722. function syncTreeGetReferenceConstructor() {
  9723. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9724. return referenceConstructor;
  9725. }
  9726. /**
  9727. * Static tracker for next query tag.
  9728. */
  9729. var syncTreeNextQueryTag_ = 1;
  9730. /**
  9731. * SyncTree is the central class for managing event callback registration, data caching, views
  9732. * (query processing), and event generation. There are typically two SyncTree instances for
  9733. * each Repo, one for the normal Firebase data, and one for the .info data.
  9734. *
  9735. * It has a number of responsibilities, including:
  9736. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9737. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9738. * (applyUserOverwrite(), applyUserMerge()).
  9739. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9740. * applyServerMerge()).
  9741. * - Generating user-facing events for server and user changes (all of the apply* methods
  9742. * return the set of events that need to be raised as a result).
  9743. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9744. * to the correct set of paths and queries to satisfy the current set of user event
  9745. * callbacks (listens are started/stopped using the provided listenProvider).
  9746. *
  9747. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9748. * events are returned to the caller rather than raised synchronously.
  9749. *
  9750. */
  9751. var SyncTree = /** @class */ (function () {
  9752. /**
  9753. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9754. * to server data.
  9755. */
  9756. function SyncTree(listenProvider_) {
  9757. this.listenProvider_ = listenProvider_;
  9758. /**
  9759. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9760. */
  9761. this.syncPointTree_ = new ImmutableTree(null);
  9762. /**
  9763. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9764. */
  9765. this.pendingWriteTree_ = newWriteTree();
  9766. this.tagToQueryMap = new Map();
  9767. this.queryToTagMap = new Map();
  9768. }
  9769. return SyncTree;
  9770. }());
  9771. /**
  9772. * Apply the data changes for a user-generated set() or transaction() call.
  9773. *
  9774. * @returns Events to raise.
  9775. */
  9776. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9777. // Record pending write.
  9778. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9779. if (!visible) {
  9780. return [];
  9781. }
  9782. else {
  9783. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9784. }
  9785. }
  9786. /**
  9787. * Apply the data from a user-generated update() call
  9788. *
  9789. * @returns Events to raise.
  9790. */
  9791. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9792. // Record pending merge.
  9793. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9794. var changeTree = ImmutableTree.fromObject(changedChildren);
  9795. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9796. }
  9797. /**
  9798. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9799. *
  9800. * @param revert - True if the given write failed and needs to be reverted
  9801. * @returns Events to raise.
  9802. */
  9803. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9804. if (revert === void 0) { revert = false; }
  9805. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9806. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9807. if (!needToReevaluate) {
  9808. return [];
  9809. }
  9810. else {
  9811. var affectedTree_1 = new ImmutableTree(null);
  9812. if (write.snap != null) {
  9813. // overwrite
  9814. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9815. }
  9816. else {
  9817. each(write.children, function (pathString) {
  9818. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9819. });
  9820. }
  9821. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9822. }
  9823. }
  9824. /**
  9825. * Apply new server data for the specified path..
  9826. *
  9827. * @returns Events to raise.
  9828. */
  9829. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9830. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9831. }
  9832. /**
  9833. * Apply new server data to be merged in at the specified path.
  9834. *
  9835. * @returns Events to raise.
  9836. */
  9837. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9838. var changeTree = ImmutableTree.fromObject(changedChildren);
  9839. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9840. }
  9841. /**
  9842. * Apply a listen complete for a query
  9843. *
  9844. * @returns Events to raise.
  9845. */
  9846. function syncTreeApplyListenComplete(syncTree, path) {
  9847. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9848. }
  9849. /**
  9850. * Apply a listen complete for a tagged query
  9851. *
  9852. * @returns Events to raise.
  9853. */
  9854. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9855. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9856. if (queryKey) {
  9857. var r = syncTreeParseQueryKey_(queryKey);
  9858. var queryPath = r.path, queryId = r.queryId;
  9859. var relativePath = newRelativePath(queryPath, path);
  9860. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9861. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9862. }
  9863. else {
  9864. // We've already removed the query. No big deal, ignore the update
  9865. return [];
  9866. }
  9867. }
  9868. /**
  9869. * Remove event callback(s).
  9870. *
  9871. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9872. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9873. *
  9874. * @param eventRegistration - If null, all callbacks are removed.
  9875. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9876. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9877. * deduping needs to take place. This flag allows toggling of that behavior
  9878. * @returns Cancel events, if cancelError was provided.
  9879. */
  9880. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9881. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9882. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9883. var path = query._path;
  9884. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9885. var cancelEvents = [];
  9886. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9887. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9888. // not loadsAllData().
  9889. if (maybeSyncPoint &&
  9890. (query._queryIdentifier === 'default' ||
  9891. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9892. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9893. if (syncPointIsEmpty(maybeSyncPoint)) {
  9894. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9895. }
  9896. var removed = removedAndEvents.removed;
  9897. cancelEvents = removedAndEvents.events;
  9898. if (!skipListenerDedup) {
  9899. /**
  9900. * We may have just removed one of many listeners and can short-circuit this whole process
  9901. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9902. * properly set up.
  9903. */
  9904. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9905. // queryId === 'default'
  9906. var removingDefault = -1 !==
  9907. removed.findIndex(function (query) {
  9908. return query._queryParams.loadsAllData();
  9909. });
  9910. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9911. return syncPointHasCompleteView(parentSyncPoint);
  9912. });
  9913. if (removingDefault && !covered) {
  9914. var subtree = syncTree.syncPointTree_.subtree(path);
  9915. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9916. // removal
  9917. if (!subtree.isEmpty()) {
  9918. // We need to fold over our subtree and collect the listeners to send
  9919. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9920. // Ok, we've collected all the listens we need. Set them up.
  9921. for (var i = 0; i < newViews.length; ++i) {
  9922. var view = newViews[i], newQuery = view.query;
  9923. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9924. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9925. }
  9926. }
  9927. // Otherwise there's nothing below us, so nothing we need to start listening on
  9928. }
  9929. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9930. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9931. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9932. if (!covered && removed.length > 0 && !cancelError) {
  9933. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9934. // default. Otherwise, we need to iterate through and cancel each individual query
  9935. if (removingDefault) {
  9936. // We don't tag default listeners
  9937. var defaultTag = null;
  9938. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9939. }
  9940. else {
  9941. removed.forEach(function (queryToRemove) {
  9942. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9943. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9944. });
  9945. }
  9946. }
  9947. }
  9948. // Now, clear all of the tags we're tracking for the removed listens
  9949. syncTreeRemoveTags_(syncTree, removed);
  9950. }
  9951. return cancelEvents;
  9952. }
  9953. /**
  9954. * Apply new server data for the specified tagged query.
  9955. *
  9956. * @returns Events to raise.
  9957. */
  9958. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9959. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9960. if (queryKey != null) {
  9961. var r = syncTreeParseQueryKey_(queryKey);
  9962. var queryPath = r.path, queryId = r.queryId;
  9963. var relativePath = newRelativePath(queryPath, path);
  9964. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9965. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9966. }
  9967. else {
  9968. // Query must have been removed already
  9969. return [];
  9970. }
  9971. }
  9972. /**
  9973. * Apply server data to be merged in for the specified tagged query.
  9974. *
  9975. * @returns Events to raise.
  9976. */
  9977. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9978. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9979. if (queryKey) {
  9980. var r = syncTreeParseQueryKey_(queryKey);
  9981. var queryPath = r.path, queryId = r.queryId;
  9982. var relativePath = newRelativePath(queryPath, path);
  9983. var changeTree = ImmutableTree.fromObject(changedChildren);
  9984. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9985. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9986. }
  9987. else {
  9988. // We've already removed the query. No big deal, ignore the update
  9989. return [];
  9990. }
  9991. }
  9992. /**
  9993. * Add an event callback for the specified query.
  9994. *
  9995. * @returns Events to raise.
  9996. */
  9997. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  9998. if (skipSetupListener === void 0) { skipSetupListener = false; }
  9999. var path = query._path;
  10000. var serverCache = null;
  10001. var foundAncestorDefaultView = false;
  10002. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10003. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10004. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10005. var relativePath = newRelativePath(pathToSyncPoint, path);
  10006. serverCache =
  10007. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10008. foundAncestorDefaultView =
  10009. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10010. });
  10011. var syncPoint = syncTree.syncPointTree_.get(path);
  10012. if (!syncPoint) {
  10013. syncPoint = new SyncPoint();
  10014. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10015. }
  10016. else {
  10017. foundAncestorDefaultView =
  10018. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10019. serverCache =
  10020. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10021. }
  10022. var serverCacheComplete;
  10023. if (serverCache != null) {
  10024. serverCacheComplete = true;
  10025. }
  10026. else {
  10027. serverCacheComplete = false;
  10028. serverCache = ChildrenNode.EMPTY_NODE;
  10029. var subtree = syncTree.syncPointTree_.subtree(path);
  10030. subtree.foreachChild(function (childName, childSyncPoint) {
  10031. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10032. if (completeCache) {
  10033. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10034. }
  10035. });
  10036. }
  10037. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10038. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10039. // We need to track a tag for this query
  10040. var queryKey = syncTreeMakeQueryKey_(query);
  10041. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10042. var tag = syncTreeGetNextQueryTag_();
  10043. syncTree.queryToTagMap.set(queryKey, tag);
  10044. syncTree.tagToQueryMap.set(tag, queryKey);
  10045. }
  10046. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10047. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10048. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10049. var view = syncPointViewForQuery(syncPoint, query);
  10050. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10051. }
  10052. return events;
  10053. }
  10054. /**
  10055. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10056. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10057. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10058. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10059. *
  10060. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10061. *
  10062. * @param path - The path to the data we want
  10063. * @param writeIdsToExclude - A specific set to be excluded
  10064. */
  10065. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10066. var includeHiddenSets = true;
  10067. var writeTree = syncTree.pendingWriteTree_;
  10068. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10069. var relativePath = newRelativePath(pathSoFar, path);
  10070. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10071. if (serverCache) {
  10072. return serverCache;
  10073. }
  10074. });
  10075. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10076. }
  10077. function syncTreeGetServerValue(syncTree, query) {
  10078. var path = query._path;
  10079. var serverCache = null;
  10080. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10081. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10082. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10083. var relativePath = newRelativePath(pathToSyncPoint, path);
  10084. serverCache =
  10085. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10086. });
  10087. var syncPoint = syncTree.syncPointTree_.get(path);
  10088. if (!syncPoint) {
  10089. syncPoint = new SyncPoint();
  10090. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10091. }
  10092. else {
  10093. serverCache =
  10094. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10095. }
  10096. var serverCacheComplete = serverCache != null;
  10097. var serverCacheNode = serverCacheComplete
  10098. ? new CacheNode(serverCache, true, false)
  10099. : null;
  10100. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10101. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10102. return viewGetCompleteNode(view);
  10103. }
  10104. /**
  10105. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10106. *
  10107. * NOTES:
  10108. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10109. *
  10110. * - We call applyOperation() on each SyncPoint passing three things:
  10111. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10112. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10113. * 3. A snapshot Node with cached server data, if we have it.
  10114. *
  10115. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10116. */
  10117. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10118. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10119. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10120. }
  10121. /**
  10122. * Recursive helper for applyOperationToSyncPoints_
  10123. */
  10124. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10125. if (pathIsEmpty(operation.path)) {
  10126. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10127. }
  10128. else {
  10129. var syncPoint = syncPointTree.get(newEmptyPath());
  10130. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10131. if (serverCache == null && syncPoint != null) {
  10132. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10133. }
  10134. var events = [];
  10135. var childName = pathGetFront(operation.path);
  10136. var childOperation = operation.operationForChild(childName);
  10137. var childTree = syncPointTree.children.get(childName);
  10138. if (childTree && childOperation) {
  10139. var childServerCache = serverCache
  10140. ? serverCache.getImmediateChild(childName)
  10141. : null;
  10142. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10143. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10144. }
  10145. if (syncPoint) {
  10146. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10147. }
  10148. return events;
  10149. }
  10150. }
  10151. /**
  10152. * Recursive helper for applyOperationToSyncPoints_
  10153. */
  10154. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10155. var syncPoint = syncPointTree.get(newEmptyPath());
  10156. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10157. if (serverCache == null && syncPoint != null) {
  10158. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10159. }
  10160. var events = [];
  10161. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10162. var childServerCache = serverCache
  10163. ? serverCache.getImmediateChild(childName)
  10164. : null;
  10165. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10166. var childOperation = operation.operationForChild(childName);
  10167. if (childOperation) {
  10168. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10169. }
  10170. });
  10171. if (syncPoint) {
  10172. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10173. }
  10174. return events;
  10175. }
  10176. function syncTreeCreateListenerForView_(syncTree, view) {
  10177. var query = view.query;
  10178. var tag = syncTreeTagForQuery(syncTree, query);
  10179. return {
  10180. hashFn: function () {
  10181. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10182. return cache.hash();
  10183. },
  10184. onComplete: function (status) {
  10185. if (status === 'ok') {
  10186. if (tag) {
  10187. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10188. }
  10189. else {
  10190. return syncTreeApplyListenComplete(syncTree, query._path);
  10191. }
  10192. }
  10193. else {
  10194. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10195. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10196. var error = errorForServerCode(status, query);
  10197. return syncTreeRemoveEventRegistration(syncTree, query,
  10198. /*eventRegistration*/ null, error);
  10199. }
  10200. }
  10201. };
  10202. }
  10203. /**
  10204. * Return the tag associated with the given query.
  10205. */
  10206. function syncTreeTagForQuery(syncTree, query) {
  10207. var queryKey = syncTreeMakeQueryKey_(query);
  10208. return syncTree.queryToTagMap.get(queryKey);
  10209. }
  10210. /**
  10211. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10212. */
  10213. function syncTreeMakeQueryKey_(query) {
  10214. return query._path.toString() + '$' + query._queryIdentifier;
  10215. }
  10216. /**
  10217. * Return the query associated with the given tag, if we have one
  10218. */
  10219. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10220. return syncTree.tagToQueryMap.get(tag);
  10221. }
  10222. /**
  10223. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10224. */
  10225. function syncTreeParseQueryKey_(queryKey) {
  10226. var splitIndex = queryKey.indexOf('$');
  10227. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10228. return {
  10229. queryId: queryKey.substr(splitIndex + 1),
  10230. path: new Path(queryKey.substr(0, splitIndex))
  10231. };
  10232. }
  10233. /**
  10234. * A helper method to apply tagged operations
  10235. */
  10236. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10237. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10238. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10239. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10240. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10241. }
  10242. /**
  10243. * This collapses multiple unfiltered views into a single view, since we only need a single
  10244. * listener for them.
  10245. */
  10246. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10247. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10248. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10249. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10250. return [completeView];
  10251. }
  10252. else {
  10253. // No complete view here, flatten any deeper listens into an array
  10254. var views_1 = [];
  10255. if (maybeChildSyncPoint) {
  10256. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10257. }
  10258. each(childMap, function (_key, childViews) {
  10259. views_1 = views_1.concat(childViews);
  10260. });
  10261. return views_1;
  10262. }
  10263. });
  10264. }
  10265. /**
  10266. * Normalizes a query to a query we send the server for listening
  10267. *
  10268. * @returns The normalized query
  10269. */
  10270. function syncTreeQueryForListening_(query) {
  10271. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10272. // We treat queries that load all data as default queries
  10273. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10274. // from Query
  10275. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10276. }
  10277. else {
  10278. return query;
  10279. }
  10280. }
  10281. function syncTreeRemoveTags_(syncTree, queries) {
  10282. for (var j = 0; j < queries.length; ++j) {
  10283. var removedQuery = queries[j];
  10284. if (!removedQuery._queryParams.loadsAllData()) {
  10285. // We should have a tag for this
  10286. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10287. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10288. syncTree.queryToTagMap.delete(removedQueryKey);
  10289. syncTree.tagToQueryMap.delete(removedQueryTag);
  10290. }
  10291. }
  10292. }
  10293. /**
  10294. * Static accessor for query tags.
  10295. */
  10296. function syncTreeGetNextQueryTag_() {
  10297. return syncTreeNextQueryTag_++;
  10298. }
  10299. /**
  10300. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10301. *
  10302. * @returns This method can return events to support synchronous data sources
  10303. */
  10304. function syncTreeSetupListener_(syncTree, query, view) {
  10305. var path = query._path;
  10306. var tag = syncTreeTagForQuery(syncTree, query);
  10307. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10308. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10309. var subtree = syncTree.syncPointTree_.subtree(path);
  10310. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10311. // may need to shadow other listens as well.
  10312. if (tag) {
  10313. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10314. }
  10315. else {
  10316. // Shadow everything at or below this location, this is a default listener.
  10317. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10318. if (!pathIsEmpty(relativePath) &&
  10319. maybeChildSyncPoint &&
  10320. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10321. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10322. }
  10323. else {
  10324. // No default listener here, flatten any deeper queries into an array
  10325. var queries_1 = [];
  10326. if (maybeChildSyncPoint) {
  10327. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10328. }
  10329. each(childMap, function (_key, childQueries) {
  10330. queries_1 = queries_1.concat(childQueries);
  10331. });
  10332. return queries_1;
  10333. }
  10334. });
  10335. for (var i = 0; i < queriesToStop.length; ++i) {
  10336. var queryToStop = queriesToStop[i];
  10337. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10338. }
  10339. }
  10340. return events;
  10341. }
  10342. /**
  10343. * @license
  10344. * Copyright 2017 Google LLC
  10345. *
  10346. * Licensed under the Apache License, Version 2.0 (the "License");
  10347. * you may not use this file except in compliance with the License.
  10348. * You may obtain a copy of the License at
  10349. *
  10350. * http://www.apache.org/licenses/LICENSE-2.0
  10351. *
  10352. * Unless required by applicable law or agreed to in writing, software
  10353. * distributed under the License is distributed on an "AS IS" BASIS,
  10354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10355. * See the License for the specific language governing permissions and
  10356. * limitations under the License.
  10357. */
  10358. var ExistingValueProvider = /** @class */ (function () {
  10359. function ExistingValueProvider(node_) {
  10360. this.node_ = node_;
  10361. }
  10362. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10363. var child = this.node_.getImmediateChild(childName);
  10364. return new ExistingValueProvider(child);
  10365. };
  10366. ExistingValueProvider.prototype.node = function () {
  10367. return this.node_;
  10368. };
  10369. return ExistingValueProvider;
  10370. }());
  10371. var DeferredValueProvider = /** @class */ (function () {
  10372. function DeferredValueProvider(syncTree, path) {
  10373. this.syncTree_ = syncTree;
  10374. this.path_ = path;
  10375. }
  10376. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10377. var childPath = pathChild(this.path_, childName);
  10378. return new DeferredValueProvider(this.syncTree_, childPath);
  10379. };
  10380. DeferredValueProvider.prototype.node = function () {
  10381. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10382. };
  10383. return DeferredValueProvider;
  10384. }());
  10385. /**
  10386. * Generate placeholders for deferred values.
  10387. */
  10388. var generateWithValues = function (values) {
  10389. values = values || {};
  10390. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10391. return values;
  10392. };
  10393. /**
  10394. * Value to use when firing local events. When writing server values, fire
  10395. * local events with an approximate value, otherwise return value as-is.
  10396. */
  10397. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10398. if (!value || typeof value !== 'object') {
  10399. return value;
  10400. }
  10401. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10402. if (typeof value['.sv'] === 'string') {
  10403. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10404. }
  10405. else if (typeof value['.sv'] === 'object') {
  10406. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10407. }
  10408. else {
  10409. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10410. }
  10411. };
  10412. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10413. switch (op) {
  10414. case 'timestamp':
  10415. return serverValues['timestamp'];
  10416. default:
  10417. assert(false, 'Unexpected server value: ' + op);
  10418. }
  10419. };
  10420. var resolveComplexDeferredValue = function (op, existing, unused) {
  10421. if (!op.hasOwnProperty('increment')) {
  10422. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10423. }
  10424. var delta = op['increment'];
  10425. if (typeof delta !== 'number') {
  10426. assert(false, 'Unexpected increment value: ' + delta);
  10427. }
  10428. var existingNode = existing.node();
  10429. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10430. // Incrementing a non-number sets the value to the incremented amount
  10431. if (!existingNode.isLeafNode()) {
  10432. return delta;
  10433. }
  10434. var leaf = existingNode;
  10435. var existingVal = leaf.getValue();
  10436. if (typeof existingVal !== 'number') {
  10437. return delta;
  10438. }
  10439. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10440. return existingVal + delta;
  10441. };
  10442. /**
  10443. * Recursively replace all deferred values and priorities in the tree with the
  10444. * specified generated replacement values.
  10445. * @param path - path to which write is relative
  10446. * @param node - new data written at path
  10447. * @param syncTree - current data
  10448. */
  10449. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10450. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10451. };
  10452. /**
  10453. * Recursively replace all deferred values and priorities in the node with the
  10454. * specified generated replacement values. If there are no server values in the node,
  10455. * it'll be returned as-is.
  10456. */
  10457. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10458. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10459. };
  10460. function resolveDeferredValue(node, existingVal, serverValues) {
  10461. var rawPri = node.getPriority().val();
  10462. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10463. var newNode;
  10464. if (node.isLeafNode()) {
  10465. var leafNode = node;
  10466. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10467. if (value !== leafNode.getValue() ||
  10468. priority !== leafNode.getPriority().val()) {
  10469. return new LeafNode(value, nodeFromJSON(priority));
  10470. }
  10471. else {
  10472. return node;
  10473. }
  10474. }
  10475. else {
  10476. var childrenNode = node;
  10477. newNode = childrenNode;
  10478. if (priority !== childrenNode.getPriority().val()) {
  10479. newNode = newNode.updatePriority(new LeafNode(priority));
  10480. }
  10481. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10482. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10483. if (newChildNode !== childNode) {
  10484. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10485. }
  10486. });
  10487. return newNode;
  10488. }
  10489. }
  10490. /**
  10491. * @license
  10492. * Copyright 2017 Google LLC
  10493. *
  10494. * Licensed under the Apache License, Version 2.0 (the "License");
  10495. * you may not use this file except in compliance with the License.
  10496. * You may obtain a copy of the License at
  10497. *
  10498. * http://www.apache.org/licenses/LICENSE-2.0
  10499. *
  10500. * Unless required by applicable law or agreed to in writing, software
  10501. * distributed under the License is distributed on an "AS IS" BASIS,
  10502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10503. * See the License for the specific language governing permissions and
  10504. * limitations under the License.
  10505. */
  10506. /**
  10507. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10508. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10509. * children.
  10510. */
  10511. var Tree = /** @class */ (function () {
  10512. /**
  10513. * @param name - Optional name of the node.
  10514. * @param parent - Optional parent node.
  10515. * @param node - Optional node to wrap.
  10516. */
  10517. function Tree(name, parent, node) {
  10518. if (name === void 0) { name = ''; }
  10519. if (parent === void 0) { parent = null; }
  10520. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10521. this.name = name;
  10522. this.parent = parent;
  10523. this.node = node;
  10524. }
  10525. return Tree;
  10526. }());
  10527. /**
  10528. * Returns a sub-Tree for the given path.
  10529. *
  10530. * @param pathObj - Path to look up.
  10531. * @returns Tree for path.
  10532. */
  10533. function treeSubTree(tree, pathObj) {
  10534. // TODO: Require pathObj to be Path?
  10535. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10536. var child = tree, next = pathGetFront(path);
  10537. while (next !== null) {
  10538. var childNode = safeGet(child.node.children, next) || {
  10539. children: {},
  10540. childCount: 0
  10541. };
  10542. child = new Tree(next, child, childNode);
  10543. path = pathPopFront(path);
  10544. next = pathGetFront(path);
  10545. }
  10546. return child;
  10547. }
  10548. /**
  10549. * Returns the data associated with this tree node.
  10550. *
  10551. * @returns The data or null if no data exists.
  10552. */
  10553. function treeGetValue(tree) {
  10554. return tree.node.value;
  10555. }
  10556. /**
  10557. * Sets data to this tree node.
  10558. *
  10559. * @param value - Value to set.
  10560. */
  10561. function treeSetValue(tree, value) {
  10562. tree.node.value = value;
  10563. treeUpdateParents(tree);
  10564. }
  10565. /**
  10566. * @returns Whether the tree has any children.
  10567. */
  10568. function treeHasChildren(tree) {
  10569. return tree.node.childCount > 0;
  10570. }
  10571. /**
  10572. * @returns Whethe rthe tree is empty (no value or children).
  10573. */
  10574. function treeIsEmpty(tree) {
  10575. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10576. }
  10577. /**
  10578. * Calls action for each child of this tree node.
  10579. *
  10580. * @param action - Action to be called for each child.
  10581. */
  10582. function treeForEachChild(tree, action) {
  10583. each(tree.node.children, function (child, childTree) {
  10584. action(new Tree(child, tree, childTree));
  10585. });
  10586. }
  10587. /**
  10588. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10589. *
  10590. * @param action - Action to be called for each child.
  10591. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10592. * false.
  10593. * @param childrenFirst - Whether to call action on children before calling it on
  10594. * parent.
  10595. */
  10596. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10597. if (includeSelf && !childrenFirst) {
  10598. action(tree);
  10599. }
  10600. treeForEachChild(tree, function (child) {
  10601. treeForEachDescendant(child, action, true, childrenFirst);
  10602. });
  10603. if (includeSelf && childrenFirst) {
  10604. action(tree);
  10605. }
  10606. }
  10607. /**
  10608. * Calls action on each ancestor node.
  10609. *
  10610. * @param action - Action to be called on each parent; return
  10611. * true to abort.
  10612. * @param includeSelf - Whether to call action on this node as well.
  10613. * @returns true if the action callback returned true.
  10614. */
  10615. function treeForEachAncestor(tree, action, includeSelf) {
  10616. var node = includeSelf ? tree : tree.parent;
  10617. while (node !== null) {
  10618. if (action(node)) {
  10619. return true;
  10620. }
  10621. node = node.parent;
  10622. }
  10623. return false;
  10624. }
  10625. /**
  10626. * @returns The path of this tree node, as a Path.
  10627. */
  10628. function treeGetPath(tree) {
  10629. return new Path(tree.parent === null
  10630. ? tree.name
  10631. : treeGetPath(tree.parent) + '/' + tree.name);
  10632. }
  10633. /**
  10634. * Adds or removes this child from its parent based on whether it's empty or not.
  10635. */
  10636. function treeUpdateParents(tree) {
  10637. if (tree.parent !== null) {
  10638. treeUpdateChild(tree.parent, tree.name, tree);
  10639. }
  10640. }
  10641. /**
  10642. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10643. *
  10644. * @param childName - The name of the child to update.
  10645. * @param child - The child to update.
  10646. */
  10647. function treeUpdateChild(tree, childName, child) {
  10648. var childEmpty = treeIsEmpty(child);
  10649. var childExists = contains(tree.node.children, childName);
  10650. if (childEmpty && childExists) {
  10651. delete tree.node.children[childName];
  10652. tree.node.childCount--;
  10653. treeUpdateParents(tree);
  10654. }
  10655. else if (!childEmpty && !childExists) {
  10656. tree.node.children[childName] = child.node;
  10657. tree.node.childCount++;
  10658. treeUpdateParents(tree);
  10659. }
  10660. }
  10661. /**
  10662. * @license
  10663. * Copyright 2017 Google LLC
  10664. *
  10665. * Licensed under the Apache License, Version 2.0 (the "License");
  10666. * you may not use this file except in compliance with the License.
  10667. * You may obtain a copy of the License at
  10668. *
  10669. * http://www.apache.org/licenses/LICENSE-2.0
  10670. *
  10671. * Unless required by applicable law or agreed to in writing, software
  10672. * distributed under the License is distributed on an "AS IS" BASIS,
  10673. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10674. * See the License for the specific language governing permissions and
  10675. * limitations under the License.
  10676. */
  10677. /**
  10678. * True for invalid Firebase keys
  10679. */
  10680. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10681. /**
  10682. * True for invalid Firebase paths.
  10683. * Allows '/' in paths.
  10684. */
  10685. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10686. /**
  10687. * Maximum number of characters to allow in leaf value
  10688. */
  10689. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10690. var isValidKey = function (key) {
  10691. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10692. };
  10693. var isValidPathString = function (pathString) {
  10694. return (typeof pathString === 'string' &&
  10695. pathString.length !== 0 &&
  10696. !INVALID_PATH_REGEX_.test(pathString));
  10697. };
  10698. var isValidRootPathString = function (pathString) {
  10699. if (pathString) {
  10700. // Allow '/.info/' at the beginning.
  10701. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10702. }
  10703. return isValidPathString(pathString);
  10704. };
  10705. var isValidPriority = function (priority) {
  10706. return (priority === null ||
  10707. typeof priority === 'string' ||
  10708. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10709. (priority &&
  10710. typeof priority === 'object' &&
  10711. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10712. contains(priority, '.sv')));
  10713. };
  10714. /**
  10715. * Pre-validate a datum passed as an argument to Firebase function.
  10716. */
  10717. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10718. if (optional && value === undefined) {
  10719. return;
  10720. }
  10721. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10722. };
  10723. /**
  10724. * Validate a data object client-side before sending to server.
  10725. */
  10726. var validateFirebaseData = function (errorPrefix, data, path_) {
  10727. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10728. if (data === undefined) {
  10729. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10730. }
  10731. if (typeof data === 'function') {
  10732. throw new Error(errorPrefix +
  10733. 'contains a function ' +
  10734. validationPathToErrorString(path) +
  10735. ' with contents = ' +
  10736. data.toString());
  10737. }
  10738. if (isInvalidJSONNumber(data)) {
  10739. throw new Error(errorPrefix +
  10740. 'contains ' +
  10741. data.toString() +
  10742. ' ' +
  10743. validationPathToErrorString(path));
  10744. }
  10745. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10746. if (typeof data === 'string' &&
  10747. data.length > MAX_LEAF_SIZE_ / 3 &&
  10748. stringLength(data) > MAX_LEAF_SIZE_) {
  10749. throw new Error(errorPrefix +
  10750. 'contains a string greater than ' +
  10751. MAX_LEAF_SIZE_ +
  10752. ' utf8 bytes ' +
  10753. validationPathToErrorString(path) +
  10754. " ('" +
  10755. data.substring(0, 50) +
  10756. "...')");
  10757. }
  10758. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10759. // to save extra walking of large objects.
  10760. if (data && typeof data === 'object') {
  10761. var hasDotValue_1 = false;
  10762. var hasActualChild_1 = false;
  10763. each(data, function (key, value) {
  10764. if (key === '.value') {
  10765. hasDotValue_1 = true;
  10766. }
  10767. else if (key !== '.priority' && key !== '.sv') {
  10768. hasActualChild_1 = true;
  10769. if (!isValidKey(key)) {
  10770. throw new Error(errorPrefix +
  10771. ' contains an invalid key (' +
  10772. key +
  10773. ') ' +
  10774. validationPathToErrorString(path) +
  10775. '. Keys must be non-empty strings ' +
  10776. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10777. }
  10778. }
  10779. validationPathPush(path, key);
  10780. validateFirebaseData(errorPrefix, value, path);
  10781. validationPathPop(path);
  10782. });
  10783. if (hasDotValue_1 && hasActualChild_1) {
  10784. throw new Error(errorPrefix +
  10785. ' contains ".value" child ' +
  10786. validationPathToErrorString(path) +
  10787. ' in addition to actual children.');
  10788. }
  10789. }
  10790. };
  10791. /**
  10792. * Pre-validate paths passed in the firebase function.
  10793. */
  10794. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10795. var i, curPath;
  10796. for (i = 0; i < mergePaths.length; i++) {
  10797. curPath = mergePaths[i];
  10798. var keys = pathSlice(curPath);
  10799. for (var j = 0; j < keys.length; j++) {
  10800. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10801. else if (!isValidKey(keys[j])) {
  10802. throw new Error(errorPrefix +
  10803. 'contains an invalid key (' +
  10804. keys[j] +
  10805. ') in path ' +
  10806. curPath.toString() +
  10807. '. Keys must be non-empty strings ' +
  10808. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10809. }
  10810. }
  10811. }
  10812. // Check that update keys are not descendants of each other.
  10813. // We rely on the property that sorting guarantees that ancestors come
  10814. // right before descendants.
  10815. mergePaths.sort(pathCompare);
  10816. var prevPath = null;
  10817. for (i = 0; i < mergePaths.length; i++) {
  10818. curPath = mergePaths[i];
  10819. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10820. throw new Error(errorPrefix +
  10821. 'contains a path ' +
  10822. prevPath.toString() +
  10823. ' that is ancestor of another path ' +
  10824. curPath.toString());
  10825. }
  10826. prevPath = curPath;
  10827. }
  10828. };
  10829. /**
  10830. * pre-validate an object passed as an argument to firebase function (
  10831. * must be an object - e.g. for firebase.update()).
  10832. */
  10833. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10834. if (optional && data === undefined) {
  10835. return;
  10836. }
  10837. var errorPrefix$1 = errorPrefix(fnName, 'values');
  10838. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10839. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10840. }
  10841. var mergePaths = [];
  10842. each(data, function (key, value) {
  10843. var curPath = new Path(key);
  10844. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10845. if (pathGetBack(curPath) === '.priority') {
  10846. if (!isValidPriority(value)) {
  10847. throw new Error(errorPrefix$1 +
  10848. "contains an invalid value for '" +
  10849. curPath.toString() +
  10850. "', which must be a valid " +
  10851. 'Firebase priority (a string, finite number, server value, or null).');
  10852. }
  10853. }
  10854. mergePaths.push(curPath);
  10855. });
  10856. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10857. };
  10858. var validatePriority = function (fnName, priority, optional) {
  10859. if (optional && priority === undefined) {
  10860. return;
  10861. }
  10862. if (isInvalidJSONNumber(priority)) {
  10863. throw new Error(errorPrefix(fnName, 'priority') +
  10864. 'is ' +
  10865. priority.toString() +
  10866. ', but must be a valid Firebase priority (a string, finite number, ' +
  10867. 'server value, or null).');
  10868. }
  10869. // Special case to allow importing data with a .sv.
  10870. if (!isValidPriority(priority)) {
  10871. throw new Error(errorPrefix(fnName, 'priority') +
  10872. 'must be a valid Firebase priority ' +
  10873. '(a string, finite number, server value, or null).');
  10874. }
  10875. };
  10876. var validateKey = function (fnName, argumentName, key, optional) {
  10877. if (optional && key === undefined) {
  10878. return;
  10879. }
  10880. if (!isValidKey(key)) {
  10881. throw new Error(errorPrefix(fnName, argumentName) +
  10882. 'was an invalid key = "' +
  10883. key +
  10884. '". Firebase keys must be non-empty strings and ' +
  10885. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10886. }
  10887. };
  10888. /**
  10889. * @internal
  10890. */
  10891. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10892. if (optional && pathString === undefined) {
  10893. return;
  10894. }
  10895. if (!isValidPathString(pathString)) {
  10896. throw new Error(errorPrefix(fnName, argumentName) +
  10897. 'was an invalid path = "' +
  10898. pathString +
  10899. '". Paths must be non-empty strings and ' +
  10900. 'can\'t contain ".", "#", "$", "[", or "]"');
  10901. }
  10902. };
  10903. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10904. if (pathString) {
  10905. // Allow '/.info/' at the beginning.
  10906. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10907. }
  10908. validatePathString(fnName, argumentName, pathString, optional);
  10909. };
  10910. /**
  10911. * @internal
  10912. */
  10913. var validateWritablePath = function (fnName, path) {
  10914. if (pathGetFront(path) === '.info') {
  10915. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10916. }
  10917. };
  10918. var validateUrl = function (fnName, parsedUrl) {
  10919. // TODO = Validate server better.
  10920. var pathString = parsedUrl.path.toString();
  10921. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10922. parsedUrl.repoInfo.host.length === 0 ||
  10923. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10924. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10925. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10926. throw new Error(errorPrefix(fnName, 'url') +
  10927. 'must be a valid firebase URL and ' +
  10928. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10929. }
  10930. };
  10931. /**
  10932. * @license
  10933. * Copyright 2017 Google LLC
  10934. *
  10935. * Licensed under the Apache License, Version 2.0 (the "License");
  10936. * you may not use this file except in compliance with the License.
  10937. * You may obtain a copy of the License at
  10938. *
  10939. * http://www.apache.org/licenses/LICENSE-2.0
  10940. *
  10941. * Unless required by applicable law or agreed to in writing, software
  10942. * distributed under the License is distributed on an "AS IS" BASIS,
  10943. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10944. * See the License for the specific language governing permissions and
  10945. * limitations under the License.
  10946. */
  10947. /**
  10948. * The event queue serves a few purposes:
  10949. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10950. * events being queued.
  10951. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10952. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10953. * left off, ensuring that the events are still raised synchronously and in order.
  10954. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10955. * events are raised synchronously.
  10956. *
  10957. * NOTE: This can all go away if/when we move to async events.
  10958. *
  10959. */
  10960. var EventQueue = /** @class */ (function () {
  10961. function EventQueue() {
  10962. this.eventLists_ = [];
  10963. /**
  10964. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10965. */
  10966. this.recursionDepth_ = 0;
  10967. }
  10968. return EventQueue;
  10969. }());
  10970. /**
  10971. * @param eventDataList - The new events to queue.
  10972. */
  10973. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10974. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10975. var currList = null;
  10976. for (var i = 0; i < eventDataList.length; i++) {
  10977. var data = eventDataList[i];
  10978. var path = data.getPath();
  10979. if (currList !== null && !pathEquals(path, currList.path)) {
  10980. eventQueue.eventLists_.push(currList);
  10981. currList = null;
  10982. }
  10983. if (currList === null) {
  10984. currList = { events: [], path: path };
  10985. }
  10986. currList.events.push(data);
  10987. }
  10988. if (currList) {
  10989. eventQueue.eventLists_.push(currList);
  10990. }
  10991. }
  10992. /**
  10993. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10994. * for the specified path.
  10995. *
  10996. * It is assumed that the new events are all for the specified path.
  10997. *
  10998. * @param path - The path to raise events for.
  10999. * @param eventDataList - The new events to raise.
  11000. */
  11001. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11002. eventQueueQueueEvents(eventQueue, eventDataList);
  11003. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11004. return pathEquals(eventPath, path);
  11005. });
  11006. }
  11007. /**
  11008. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11009. * locations related to the specified change path (i.e. all ancestors and descendants).
  11010. *
  11011. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11012. *
  11013. * @param changedPath - The path to raise events for.
  11014. * @param eventDataList - The events to raise
  11015. */
  11016. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11017. eventQueueQueueEvents(eventQueue, eventDataList);
  11018. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11019. return pathContains(eventPath, changedPath) ||
  11020. pathContains(changedPath, eventPath);
  11021. });
  11022. }
  11023. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11024. eventQueue.recursionDepth_++;
  11025. var sentAll = true;
  11026. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11027. var eventList = eventQueue.eventLists_[i];
  11028. if (eventList) {
  11029. var eventPath = eventList.path;
  11030. if (predicate(eventPath)) {
  11031. eventListRaise(eventQueue.eventLists_[i]);
  11032. eventQueue.eventLists_[i] = null;
  11033. }
  11034. else {
  11035. sentAll = false;
  11036. }
  11037. }
  11038. }
  11039. if (sentAll) {
  11040. eventQueue.eventLists_ = [];
  11041. }
  11042. eventQueue.recursionDepth_--;
  11043. }
  11044. /**
  11045. * Iterates through the list and raises each event
  11046. */
  11047. function eventListRaise(eventList) {
  11048. for (var i = 0; i < eventList.events.length; i++) {
  11049. var eventData = eventList.events[i];
  11050. if (eventData !== null) {
  11051. eventList.events[i] = null;
  11052. var eventFn = eventData.getEventRunner();
  11053. if (logger) {
  11054. log('event: ' + eventData.toString());
  11055. }
  11056. exceptionGuard(eventFn);
  11057. }
  11058. }
  11059. }
  11060. /**
  11061. * @license
  11062. * Copyright 2017 Google LLC
  11063. *
  11064. * Licensed under the Apache License, Version 2.0 (the "License");
  11065. * you may not use this file except in compliance with the License.
  11066. * You may obtain a copy of the License at
  11067. *
  11068. * http://www.apache.org/licenses/LICENSE-2.0
  11069. *
  11070. * Unless required by applicable law or agreed to in writing, software
  11071. * distributed under the License is distributed on an "AS IS" BASIS,
  11072. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11073. * See the License for the specific language governing permissions and
  11074. * limitations under the License.
  11075. */
  11076. var INTERRUPT_REASON = 'repo_interrupt';
  11077. /**
  11078. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11079. * things this ensure that if there's ever a bug causing a mismatch between
  11080. * client / server hashes for some data, we won't retry indefinitely.
  11081. */
  11082. var MAX_TRANSACTION_RETRIES = 25;
  11083. /**
  11084. * A connection to a single data repository.
  11085. */
  11086. var Repo = /** @class */ (function () {
  11087. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11088. this.repoInfo_ = repoInfo_;
  11089. this.forceRestClient_ = forceRestClient_;
  11090. this.authTokenProvider_ = authTokenProvider_;
  11091. this.appCheckProvider_ = appCheckProvider_;
  11092. this.dataUpdateCount = 0;
  11093. this.statsListener_ = null;
  11094. this.eventQueue_ = new EventQueue();
  11095. this.nextWriteId_ = 1;
  11096. this.interceptServerDataCallback_ = null;
  11097. /** A list of data pieces and paths to be set when this client disconnects. */
  11098. this.onDisconnect_ = newSparseSnapshotTree();
  11099. /** Stores queues of outstanding transactions for Firebase locations. */
  11100. this.transactionQueueTree_ = new Tree();
  11101. // TODO: This should be @private but it's used by test_access.js and internal.js
  11102. this.persistentConnection_ = null;
  11103. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11104. this.key = this.repoInfo_.toURLString();
  11105. }
  11106. /**
  11107. * @returns The URL corresponding to the root of this Firebase.
  11108. */
  11109. Repo.prototype.toString = function () {
  11110. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11111. };
  11112. return Repo;
  11113. }());
  11114. function repoStart(repo, appId, authOverride) {
  11115. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11116. if (repo.forceRestClient_ || beingCrawled()) {
  11117. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11118. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11119. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11120. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11121. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11122. }
  11123. else {
  11124. // Validate authOverride
  11125. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11126. if (typeof authOverride !== 'object') {
  11127. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11128. }
  11129. try {
  11130. stringify(authOverride);
  11131. }
  11132. catch (e) {
  11133. throw new Error('Invalid authOverride provided: ' + e);
  11134. }
  11135. }
  11136. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11137. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11138. }, function (connectStatus) {
  11139. repoOnConnectStatus(repo, connectStatus);
  11140. }, function (updates) {
  11141. repoOnServerInfoUpdate(repo, updates);
  11142. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11143. repo.server_ = repo.persistentConnection_;
  11144. }
  11145. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11146. repo.server_.refreshAuthToken(token);
  11147. });
  11148. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11149. repo.server_.refreshAppCheckToken(result.token);
  11150. });
  11151. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11152. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11153. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11154. // Used for .info.
  11155. repo.infoData_ = new SnapshotHolder();
  11156. repo.infoSyncTree_ = new SyncTree({
  11157. startListening: function (query, tag, currentHashFn, onComplete) {
  11158. var infoEvents = [];
  11159. var node = repo.infoData_.getNode(query._path);
  11160. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11161. // on initial data...
  11162. if (!node.isEmpty()) {
  11163. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11164. setTimeout(function () {
  11165. onComplete('ok');
  11166. }, 0);
  11167. }
  11168. return infoEvents;
  11169. },
  11170. stopListening: function () { }
  11171. });
  11172. repoUpdateInfo(repo, 'connected', false);
  11173. repo.serverSyncTree_ = new SyncTree({
  11174. startListening: function (query, tag, currentHashFn, onComplete) {
  11175. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11176. var events = onComplete(status, data);
  11177. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11178. });
  11179. // No synchronous events for network-backed sync trees
  11180. return [];
  11181. },
  11182. stopListening: function (query, tag) {
  11183. repo.server_.unlisten(query, tag);
  11184. }
  11185. });
  11186. }
  11187. /**
  11188. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11189. */
  11190. function repoServerTime(repo) {
  11191. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11192. var offset = offsetNode.val() || 0;
  11193. return new Date().getTime() + offset;
  11194. }
  11195. /**
  11196. * Generate ServerValues using some variables from the repo object.
  11197. */
  11198. function repoGenerateServerValues(repo) {
  11199. return generateWithValues({
  11200. timestamp: repoServerTime(repo)
  11201. });
  11202. }
  11203. /**
  11204. * Called by realtime when we get new messages from the server.
  11205. */
  11206. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11207. // For testing.
  11208. repo.dataUpdateCount++;
  11209. var path = new Path(pathString);
  11210. data = repo.interceptServerDataCallback_
  11211. ? repo.interceptServerDataCallback_(pathString, data)
  11212. : data;
  11213. var events = [];
  11214. if (tag) {
  11215. if (isMerge) {
  11216. var taggedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
  11217. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11218. }
  11219. else {
  11220. var taggedSnap = nodeFromJSON(data);
  11221. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11222. }
  11223. }
  11224. else if (isMerge) {
  11225. var changedChildren = map(data, function (raw) { return nodeFromJSON(raw); });
  11226. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11227. }
  11228. else {
  11229. var snap = nodeFromJSON(data);
  11230. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11231. }
  11232. var affectedPath = path;
  11233. if (events.length > 0) {
  11234. // Since we have a listener outstanding for each transaction, receiving any events
  11235. // is a proxy for some change having occurred.
  11236. affectedPath = repoRerunTransactions(repo, path);
  11237. }
  11238. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11239. }
  11240. function repoOnConnectStatus(repo, connectStatus) {
  11241. repoUpdateInfo(repo, 'connected', connectStatus);
  11242. if (connectStatus === false) {
  11243. repoRunOnDisconnectEvents(repo);
  11244. }
  11245. }
  11246. function repoOnServerInfoUpdate(repo, updates) {
  11247. each(updates, function (key, value) {
  11248. repoUpdateInfo(repo, key, value);
  11249. });
  11250. }
  11251. function repoUpdateInfo(repo, pathString, value) {
  11252. var path = new Path('/.info/' + pathString);
  11253. var newNode = nodeFromJSON(value);
  11254. repo.infoData_.updateSnapshot(path, newNode);
  11255. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11256. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11257. }
  11258. function repoGetNextWriteId(repo) {
  11259. return repo.nextWriteId_++;
  11260. }
  11261. /**
  11262. * The purpose of `getValue` is to return the latest known value
  11263. * satisfying `query`.
  11264. *
  11265. * This method will first check for in-memory cached values
  11266. * belonging to active listeners. If they are found, such values
  11267. * are considered to be the most up-to-date.
  11268. *
  11269. * If the client is not connected, this method will wait until the
  11270. * repo has established a connection and then request the value for `query`.
  11271. * If the client is not able to retrieve the query result for another reason,
  11272. * it reports an error.
  11273. *
  11274. * @param query - The query to surface a value for.
  11275. */
  11276. function repoGetValue(repo, query, eventRegistration) {
  11277. // Only active queries are cached. There is no persisted cache.
  11278. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11279. if (cached != null) {
  11280. return Promise.resolve(cached);
  11281. }
  11282. return repo.server_.get(query).then(function (payload) {
  11283. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11284. /**
  11285. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11286. * Add an event registration,
  11287. * Update data at the path,
  11288. * Raise any events,
  11289. * Cleanup the SyncTree
  11290. */
  11291. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11292. var events;
  11293. if (query._queryParams.loadsAllData()) {
  11294. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11295. }
  11296. else {
  11297. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11298. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11299. }
  11300. /*
  11301. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11302. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11303. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11304. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11305. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11306. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11307. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11308. * ensure the corresponding child events will get fired.
  11309. */
  11310. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11311. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11312. return node;
  11313. }, function (err) {
  11314. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  11315. return Promise.reject(new Error(err));
  11316. });
  11317. }
  11318. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11319. repoLog(repo, 'set', {
  11320. path: path.toString(),
  11321. value: newVal,
  11322. priority: newPriority
  11323. });
  11324. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11325. // (b) store unresolved paths on JSON parse
  11326. var serverValues = repoGenerateServerValues(repo);
  11327. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11328. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11329. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11330. var writeId = repoGetNextWriteId(repo);
  11331. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11332. eventQueueQueueEvents(repo.eventQueue_, events);
  11333. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11334. var success = status === 'ok';
  11335. if (!success) {
  11336. warn('set at ' + path + ' failed: ' + status);
  11337. }
  11338. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11339. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11340. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11341. });
  11342. var affectedPath = repoAbortTransactions(repo, path);
  11343. repoRerunTransactions(repo, affectedPath);
  11344. // We queued the events above, so just flush the queue here
  11345. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11346. }
  11347. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11348. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11349. // Start with our existing data and merge each child into it.
  11350. var empty = true;
  11351. var serverValues = repoGenerateServerValues(repo);
  11352. var changedChildren = {};
  11353. each(childrenToMerge, function (changedKey, changedValue) {
  11354. empty = false;
  11355. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11356. });
  11357. if (!empty) {
  11358. var writeId_1 = repoGetNextWriteId(repo);
  11359. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11360. eventQueueQueueEvents(repo.eventQueue_, events);
  11361. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11362. var success = status === 'ok';
  11363. if (!success) {
  11364. warn('update at ' + path + ' failed: ' + status);
  11365. }
  11366. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11367. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11368. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11369. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11370. });
  11371. each(childrenToMerge, function (changedPath) {
  11372. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11373. repoRerunTransactions(repo, affectedPath);
  11374. });
  11375. // We queued the events above, so just flush the queue here
  11376. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11377. }
  11378. else {
  11379. log("update() called with empty data. Don't do anything.");
  11380. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11381. }
  11382. }
  11383. /**
  11384. * Applies all of the changes stored up in the onDisconnect_ tree.
  11385. */
  11386. function repoRunOnDisconnectEvents(repo) {
  11387. repoLog(repo, 'onDisconnectEvents');
  11388. var serverValues = repoGenerateServerValues(repo);
  11389. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11390. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11391. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11392. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11393. });
  11394. var events = [];
  11395. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11396. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11397. var affectedPath = repoAbortTransactions(repo, path);
  11398. repoRerunTransactions(repo, affectedPath);
  11399. });
  11400. repo.onDisconnect_ = newSparseSnapshotTree();
  11401. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11402. }
  11403. function repoOnDisconnectCancel(repo, path, onComplete) {
  11404. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11405. if (status === 'ok') {
  11406. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11407. }
  11408. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11409. });
  11410. }
  11411. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11412. var newNode = nodeFromJSON(value);
  11413. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11414. if (status === 'ok') {
  11415. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11416. }
  11417. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11418. });
  11419. }
  11420. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11421. var newNode = nodeFromJSON(value, priority);
  11422. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11423. if (status === 'ok') {
  11424. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11425. }
  11426. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11427. });
  11428. }
  11429. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11430. if (isEmpty(childrenToMerge)) {
  11431. log("onDisconnect().update() called with empty data. Don't do anything.");
  11432. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11433. return;
  11434. }
  11435. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11436. if (status === 'ok') {
  11437. each(childrenToMerge, function (childName, childNode) {
  11438. var newChildNode = nodeFromJSON(childNode);
  11439. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11440. });
  11441. }
  11442. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11443. });
  11444. }
  11445. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11446. var events;
  11447. if (pathGetFront(query._path) === '.info') {
  11448. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11449. }
  11450. else {
  11451. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11452. }
  11453. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11454. }
  11455. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11456. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11457. // a little bit by handling the return values anyways.
  11458. var events;
  11459. if (pathGetFront(query._path) === '.info') {
  11460. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11461. }
  11462. else {
  11463. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11464. }
  11465. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11466. }
  11467. function repoInterrupt(repo) {
  11468. if (repo.persistentConnection_) {
  11469. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11470. }
  11471. }
  11472. function repoResume(repo) {
  11473. if (repo.persistentConnection_) {
  11474. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11475. }
  11476. }
  11477. function repoLog(repo) {
  11478. var varArgs = [];
  11479. for (var _i = 1; _i < arguments.length; _i++) {
  11480. varArgs[_i - 1] = arguments[_i];
  11481. }
  11482. var prefix = '';
  11483. if (repo.persistentConnection_) {
  11484. prefix = repo.persistentConnection_.id + ':';
  11485. }
  11486. log.apply(void 0, __spreadArray([prefix], __read(varArgs), false));
  11487. }
  11488. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11489. if (callback) {
  11490. exceptionGuard(function () {
  11491. if (status === 'ok') {
  11492. callback(null);
  11493. }
  11494. else {
  11495. var code = (status || 'error').toUpperCase();
  11496. var message = code;
  11497. if (errorReason) {
  11498. message += ': ' + errorReason;
  11499. }
  11500. var error = new Error(message);
  11501. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11502. error.code = code;
  11503. callback(error);
  11504. }
  11505. });
  11506. }
  11507. }
  11508. /**
  11509. * Creates a new transaction, adds it to the transactions we're tracking, and
  11510. * sends it to the server if possible.
  11511. *
  11512. * @param path - Path at which to do transaction.
  11513. * @param transactionUpdate - Update callback.
  11514. * @param onComplete - Completion callback.
  11515. * @param unwatcher - Function that will be called when the transaction no longer
  11516. * need data updates for `path`.
  11517. * @param applyLocally - Whether or not to make intermediate results visible
  11518. */
  11519. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11520. repoLog(repo, 'transaction on ' + path);
  11521. // Initialize transaction.
  11522. var transaction = {
  11523. path: path,
  11524. update: transactionUpdate,
  11525. onComplete: onComplete,
  11526. // One of TransactionStatus enums.
  11527. status: null,
  11528. // Used when combining transactions at different locations to figure out
  11529. // which one goes first.
  11530. order: LUIDGenerator(),
  11531. // Whether to raise local events for this transaction.
  11532. applyLocally: applyLocally,
  11533. // Count of how many times we've retried the transaction.
  11534. retryCount: 0,
  11535. // Function to call to clean up our .on() listener.
  11536. unwatcher: unwatcher,
  11537. // Stores why a transaction was aborted.
  11538. abortReason: null,
  11539. currentWriteId: null,
  11540. currentInputSnapshot: null,
  11541. currentOutputSnapshotRaw: null,
  11542. currentOutputSnapshotResolved: null
  11543. };
  11544. // Run transaction initially.
  11545. var currentState = repoGetLatestState(repo, path, undefined);
  11546. transaction.currentInputSnapshot = currentState;
  11547. var newVal = transaction.update(currentState.val());
  11548. if (newVal === undefined) {
  11549. // Abort transaction.
  11550. transaction.unwatcher();
  11551. transaction.currentOutputSnapshotRaw = null;
  11552. transaction.currentOutputSnapshotResolved = null;
  11553. if (transaction.onComplete) {
  11554. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11555. }
  11556. }
  11557. else {
  11558. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11559. // Mark as run and add to our queue.
  11560. transaction.status = 0 /* TransactionStatus.RUN */;
  11561. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11562. var nodeQueue = treeGetValue(queueNode) || [];
  11563. nodeQueue.push(transaction);
  11564. treeSetValue(queueNode, nodeQueue);
  11565. // Update visibleData and raise events
  11566. // Note: We intentionally raise events after updating all of our
  11567. // transaction state, since the user could start new transactions from the
  11568. // event callbacks.
  11569. var priorityForNode = void 0;
  11570. if (typeof newVal === 'object' &&
  11571. newVal !== null &&
  11572. contains(newVal, '.priority')) {
  11573. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11574. priorityForNode = safeGet(newVal, '.priority');
  11575. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11576. 'Priority must be a valid string, finite number, server value, or null.');
  11577. }
  11578. else {
  11579. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11580. ChildrenNode.EMPTY_NODE;
  11581. priorityForNode = currentNode.getPriority().val();
  11582. }
  11583. var serverValues = repoGenerateServerValues(repo);
  11584. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11585. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11586. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11587. transaction.currentOutputSnapshotResolved = newNode;
  11588. transaction.currentWriteId = repoGetNextWriteId(repo);
  11589. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11590. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11591. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11592. }
  11593. }
  11594. /**
  11595. * @param excludeSets - A specific set to exclude
  11596. */
  11597. function repoGetLatestState(repo, path, excludeSets) {
  11598. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11599. ChildrenNode.EMPTY_NODE);
  11600. }
  11601. /**
  11602. * Sends any already-run transactions that aren't waiting for outstanding
  11603. * transactions to complete.
  11604. *
  11605. * Externally it's called with no arguments, but it calls itself recursively
  11606. * with a particular transactionQueueTree node to recurse through the tree.
  11607. *
  11608. * @param node - transactionQueueTree node to start at.
  11609. */
  11610. function repoSendReadyTransactions(repo, node) {
  11611. if (node === void 0) { node = repo.transactionQueueTree_; }
  11612. // Before recursing, make sure any completed transactions are removed.
  11613. if (!node) {
  11614. repoPruneCompletedTransactionsBelowNode(repo, node);
  11615. }
  11616. if (treeGetValue(node)) {
  11617. var queue = repoBuildTransactionQueue(repo, node);
  11618. assert(queue.length > 0, 'Sending zero length transaction queue');
  11619. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11620. // If they're all run (and not sent), we can send them. Else, we must wait.
  11621. if (allRun) {
  11622. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11623. }
  11624. }
  11625. else if (treeHasChildren(node)) {
  11626. treeForEachChild(node, function (childNode) {
  11627. repoSendReadyTransactions(repo, childNode);
  11628. });
  11629. }
  11630. }
  11631. /**
  11632. * Given a list of run transactions, send them to the server and then handle
  11633. * the result (success or failure).
  11634. *
  11635. * @param path - The location of the queue.
  11636. * @param queue - Queue of transactions under the specified location.
  11637. */
  11638. function repoSendTransactionQueue(repo, path, queue) {
  11639. // Mark transactions as sent and increment retry count!
  11640. var setsToIgnore = queue.map(function (txn) {
  11641. return txn.currentWriteId;
  11642. });
  11643. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11644. var snapToSend = latestState;
  11645. var latestHash = latestState.hash();
  11646. for (var i = 0; i < queue.length; i++) {
  11647. var txn = queue[i];
  11648. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11649. txn.status = 1 /* TransactionStatus.SENT */;
  11650. txn.retryCount++;
  11651. var relativePath = newRelativePath(path, txn.path);
  11652. // If we've gotten to this point, the output snapshot must be defined.
  11653. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11654. }
  11655. var dataToSend = snapToSend.val(true);
  11656. var pathToSend = path;
  11657. // Send the put.
  11658. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11659. repoLog(repo, 'transaction put response', {
  11660. path: pathToSend.toString(),
  11661. status: status
  11662. });
  11663. var events = [];
  11664. if (status === 'ok') {
  11665. // Queue up the callbacks and fire them after cleaning up all of our
  11666. // transaction state, since the callback could trigger more
  11667. // transactions or sets.
  11668. var callbacks = [];
  11669. var _loop_1 = function (i) {
  11670. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11671. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11672. if (queue[i].onComplete) {
  11673. // We never unset the output snapshot, and given that this
  11674. // transaction is complete, it should be set
  11675. callbacks.push(function () {
  11676. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11677. });
  11678. }
  11679. queue[i].unwatcher();
  11680. };
  11681. for (var i = 0; i < queue.length; i++) {
  11682. _loop_1(i);
  11683. }
  11684. // Now remove the completed transactions.
  11685. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11686. // There may be pending transactions that we can now send.
  11687. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11688. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11689. // Finally, trigger onComplete callbacks.
  11690. for (var i = 0; i < callbacks.length; i++) {
  11691. exceptionGuard(callbacks[i]);
  11692. }
  11693. }
  11694. else {
  11695. // transactions are no longer sent. Update their status appropriately.
  11696. if (status === 'datastale') {
  11697. for (var i = 0; i < queue.length; i++) {
  11698. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11699. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11700. }
  11701. else {
  11702. queue[i].status = 0 /* TransactionStatus.RUN */;
  11703. }
  11704. }
  11705. }
  11706. else {
  11707. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11708. for (var i = 0; i < queue.length; i++) {
  11709. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11710. queue[i].abortReason = status;
  11711. }
  11712. }
  11713. repoRerunTransactions(repo, path);
  11714. }
  11715. }, latestHash);
  11716. }
  11717. /**
  11718. * Finds all transactions dependent on the data at changedPath and reruns them.
  11719. *
  11720. * Should be called any time cached data changes.
  11721. *
  11722. * Return the highest path that was affected by rerunning transactions. This
  11723. * is the path at which events need to be raised for.
  11724. *
  11725. * @param changedPath - The path in mergedData that changed.
  11726. * @returns The rootmost path that was affected by rerunning transactions.
  11727. */
  11728. function repoRerunTransactions(repo, changedPath) {
  11729. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11730. var path = treeGetPath(rootMostTransactionNode);
  11731. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11732. repoRerunTransactionQueue(repo, queue, path);
  11733. return path;
  11734. }
  11735. /**
  11736. * Does all the work of rerunning transactions (as well as cleans up aborted
  11737. * transactions and whatnot).
  11738. *
  11739. * @param queue - The queue of transactions to run.
  11740. * @param path - The path the queue is for.
  11741. */
  11742. function repoRerunTransactionQueue(repo, queue, path) {
  11743. if (queue.length === 0) {
  11744. return; // Nothing to do!
  11745. }
  11746. // Queue up the callbacks and fire them after cleaning up all of our
  11747. // transaction state, since the callback could trigger more transactions or
  11748. // sets.
  11749. var callbacks = [];
  11750. var events = [];
  11751. // Ignore all of the sets we're going to re-run.
  11752. var txnsToRerun = queue.filter(function (q) {
  11753. return q.status === 0 /* TransactionStatus.RUN */;
  11754. });
  11755. var setsToIgnore = txnsToRerun.map(function (q) {
  11756. return q.currentWriteId;
  11757. });
  11758. var _loop_2 = function (i) {
  11759. var transaction = queue[i];
  11760. var relativePath = newRelativePath(path, transaction.path);
  11761. var abortTransaction = false, abortReason;
  11762. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11763. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11764. abortTransaction = true;
  11765. abortReason = transaction.abortReason;
  11766. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11767. }
  11768. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11769. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11770. abortTransaction = true;
  11771. abortReason = 'maxretry';
  11772. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11773. }
  11774. else {
  11775. // This code reruns a transaction
  11776. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11777. transaction.currentInputSnapshot = currentNode;
  11778. var newData = queue[i].update(currentNode.val());
  11779. if (newData !== undefined) {
  11780. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11781. var newDataNode = nodeFromJSON(newData);
  11782. var hasExplicitPriority = typeof newData === 'object' &&
  11783. newData != null &&
  11784. contains(newData, '.priority');
  11785. if (!hasExplicitPriority) {
  11786. // Keep the old priority if there wasn't a priority explicitly specified.
  11787. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11788. }
  11789. var oldWriteId = transaction.currentWriteId;
  11790. var serverValues = repoGenerateServerValues(repo);
  11791. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11792. transaction.currentOutputSnapshotRaw = newDataNode;
  11793. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11794. transaction.currentWriteId = repoGetNextWriteId(repo);
  11795. // Mutates setsToIgnore in place
  11796. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11797. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11798. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11799. }
  11800. else {
  11801. abortTransaction = true;
  11802. abortReason = 'nodata';
  11803. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11804. }
  11805. }
  11806. }
  11807. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11808. events = [];
  11809. if (abortTransaction) {
  11810. // Abort.
  11811. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11812. // Removing a listener can trigger pruning which can muck with
  11813. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11814. // until we're done.
  11815. (function (unwatcher) {
  11816. setTimeout(unwatcher, Math.floor(0));
  11817. })(queue[i].unwatcher);
  11818. if (queue[i].onComplete) {
  11819. if (abortReason === 'nodata') {
  11820. callbacks.push(function () {
  11821. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11822. });
  11823. }
  11824. else {
  11825. callbacks.push(function () {
  11826. return queue[i].onComplete(new Error(abortReason), false, null);
  11827. });
  11828. }
  11829. }
  11830. }
  11831. };
  11832. for (var i = 0; i < queue.length; i++) {
  11833. _loop_2(i);
  11834. }
  11835. // Clean up completed transactions.
  11836. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11837. // Now fire callbacks, now that we're in a good, known state.
  11838. for (var i = 0; i < callbacks.length; i++) {
  11839. exceptionGuard(callbacks[i]);
  11840. }
  11841. // Try to send the transaction result to the server.
  11842. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11843. }
  11844. /**
  11845. * Returns the rootmost ancestor node of the specified path that has a pending
  11846. * transaction on it, or just returns the node for the given path if there are
  11847. * no pending transactions on any ancestor.
  11848. *
  11849. * @param path - The location to start at.
  11850. * @returns The rootmost node with a transaction.
  11851. */
  11852. function repoGetAncestorTransactionNode(repo, path) {
  11853. var front;
  11854. // Start at the root and walk deeper into the tree towards path until we
  11855. // find a node with pending transactions.
  11856. var transactionNode = repo.transactionQueueTree_;
  11857. front = pathGetFront(path);
  11858. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11859. transactionNode = treeSubTree(transactionNode, front);
  11860. path = pathPopFront(path);
  11861. front = pathGetFront(path);
  11862. }
  11863. return transactionNode;
  11864. }
  11865. /**
  11866. * Builds the queue of all transactions at or below the specified
  11867. * transactionNode.
  11868. *
  11869. * @param transactionNode
  11870. * @returns The generated queue.
  11871. */
  11872. function repoBuildTransactionQueue(repo, transactionNode) {
  11873. // Walk any child transaction queues and aggregate them into a single queue.
  11874. var transactionQueue = [];
  11875. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11876. // Sort them by the order the transactions were created.
  11877. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11878. return transactionQueue;
  11879. }
  11880. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11881. var nodeQueue = treeGetValue(node);
  11882. if (nodeQueue) {
  11883. for (var i = 0; i < nodeQueue.length; i++) {
  11884. queue.push(nodeQueue[i]);
  11885. }
  11886. }
  11887. treeForEachChild(node, function (child) {
  11888. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11889. });
  11890. }
  11891. /**
  11892. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11893. */
  11894. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11895. var queue = treeGetValue(node);
  11896. if (queue) {
  11897. var to = 0;
  11898. for (var from = 0; from < queue.length; from++) {
  11899. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11900. queue[to] = queue[from];
  11901. to++;
  11902. }
  11903. }
  11904. queue.length = to;
  11905. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11906. }
  11907. treeForEachChild(node, function (childNode) {
  11908. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11909. });
  11910. }
  11911. /**
  11912. * Aborts all transactions on ancestors or descendants of the specified path.
  11913. * Called when doing a set() or update() since we consider them incompatible
  11914. * with transactions.
  11915. *
  11916. * @param path - Path for which we want to abort related transactions.
  11917. */
  11918. function repoAbortTransactions(repo, path) {
  11919. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11920. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11921. treeForEachAncestor(transactionNode, function (node) {
  11922. repoAbortTransactionsOnNode(repo, node);
  11923. });
  11924. repoAbortTransactionsOnNode(repo, transactionNode);
  11925. treeForEachDescendant(transactionNode, function (node) {
  11926. repoAbortTransactionsOnNode(repo, node);
  11927. });
  11928. return affectedPath;
  11929. }
  11930. /**
  11931. * Abort transactions stored in this transaction queue node.
  11932. *
  11933. * @param node - Node to abort transactions for.
  11934. */
  11935. function repoAbortTransactionsOnNode(repo, node) {
  11936. var queue = treeGetValue(node);
  11937. if (queue) {
  11938. // Queue up the callbacks and fire them after cleaning up all of our
  11939. // transaction state, since the callback could trigger more transactions
  11940. // or sets.
  11941. var callbacks = [];
  11942. // Go through queue. Any already-sent transactions must be marked for
  11943. // abort, while the unsent ones can be immediately aborted and removed.
  11944. var events = [];
  11945. var lastSent = -1;
  11946. for (var i = 0; i < queue.length; i++) {
  11947. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11948. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11949. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11950. lastSent = i;
  11951. // Mark transaction for abort when it comes back.
  11952. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11953. queue[i].abortReason = 'set';
  11954. }
  11955. else {
  11956. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11957. // We can abort it immediately.
  11958. queue[i].unwatcher();
  11959. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11960. if (queue[i].onComplete) {
  11961. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11962. }
  11963. }
  11964. }
  11965. if (lastSent === -1) {
  11966. // We're not waiting for any sent transactions. We can clear the queue.
  11967. treeSetValue(node, undefined);
  11968. }
  11969. else {
  11970. // Remove the transactions we aborted.
  11971. queue.length = lastSent + 1;
  11972. }
  11973. // Now fire the callbacks.
  11974. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11975. for (var i = 0; i < callbacks.length; i++) {
  11976. exceptionGuard(callbacks[i]);
  11977. }
  11978. }
  11979. }
  11980. /**
  11981. * @license
  11982. * Copyright 2017 Google LLC
  11983. *
  11984. * Licensed under the Apache License, Version 2.0 (the "License");
  11985. * you may not use this file except in compliance with the License.
  11986. * You may obtain a copy of the License at
  11987. *
  11988. * http://www.apache.org/licenses/LICENSE-2.0
  11989. *
  11990. * Unless required by applicable law or agreed to in writing, software
  11991. * distributed under the License is distributed on an "AS IS" BASIS,
  11992. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11993. * See the License for the specific language governing permissions and
  11994. * limitations under the License.
  11995. */
  11996. function decodePath(pathString) {
  11997. var pathStringDecoded = '';
  11998. var pieces = pathString.split('/');
  11999. for (var i = 0; i < pieces.length; i++) {
  12000. if (pieces[i].length > 0) {
  12001. var piece = pieces[i];
  12002. try {
  12003. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12004. }
  12005. catch (e) { }
  12006. pathStringDecoded += '/' + piece;
  12007. }
  12008. }
  12009. return pathStringDecoded;
  12010. }
  12011. /**
  12012. * @returns key value hash
  12013. */
  12014. function decodeQuery(queryString) {
  12015. var e_1, _a;
  12016. var results = {};
  12017. if (queryString.charAt(0) === '?') {
  12018. queryString = queryString.substring(1);
  12019. }
  12020. try {
  12021. for (var _b = __values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12022. var segment = _c.value;
  12023. if (segment.length === 0) {
  12024. continue;
  12025. }
  12026. var kv = segment.split('=');
  12027. if (kv.length === 2) {
  12028. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12029. }
  12030. else {
  12031. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12032. }
  12033. }
  12034. }
  12035. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12036. finally {
  12037. try {
  12038. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12039. }
  12040. finally { if (e_1) throw e_1.error; }
  12041. }
  12042. return results;
  12043. }
  12044. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12045. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12046. if (parsedUrl.domain === 'firebase.com') {
  12047. fatal(parsedUrl.host +
  12048. ' is no longer supported. ' +
  12049. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12050. }
  12051. // Catch common error of uninitialized namespace value.
  12052. if ((!namespace || namespace === 'undefined') &&
  12053. parsedUrl.domain !== 'localhost') {
  12054. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12055. }
  12056. if (!parsedUrl.secure) {
  12057. warnIfPageIsSecure();
  12058. }
  12059. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12060. return {
  12061. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12062. /*persistenceKey=*/ '',
  12063. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12064. path: new Path(parsedUrl.pathString)
  12065. };
  12066. };
  12067. var parseDatabaseURL = function (dataURL) {
  12068. // Default to empty strings in the event of a malformed string.
  12069. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12070. // Always default to SSL, unless otherwise specified.
  12071. var secure = true, scheme = 'https', port = 443;
  12072. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12073. if (typeof dataURL === 'string') {
  12074. // Parse scheme.
  12075. var colonInd = dataURL.indexOf('//');
  12076. if (colonInd >= 0) {
  12077. scheme = dataURL.substring(0, colonInd - 1);
  12078. dataURL = dataURL.substring(colonInd + 2);
  12079. }
  12080. // Parse host, path, and query string.
  12081. var slashInd = dataURL.indexOf('/');
  12082. if (slashInd === -1) {
  12083. slashInd = dataURL.length;
  12084. }
  12085. var questionMarkInd = dataURL.indexOf('?');
  12086. if (questionMarkInd === -1) {
  12087. questionMarkInd = dataURL.length;
  12088. }
  12089. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12090. if (slashInd < questionMarkInd) {
  12091. // For pathString, questionMarkInd will always come after slashInd
  12092. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12093. }
  12094. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12095. // If we have a port, use scheme for determining if it's secure.
  12096. colonInd = host.indexOf(':');
  12097. if (colonInd >= 0) {
  12098. secure = scheme === 'https' || scheme === 'wss';
  12099. port = parseInt(host.substring(colonInd + 1), 10);
  12100. }
  12101. else {
  12102. colonInd = host.length;
  12103. }
  12104. var hostWithoutPort = host.slice(0, colonInd);
  12105. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12106. domain = 'localhost';
  12107. }
  12108. else if (hostWithoutPort.split('.').length <= 2) {
  12109. domain = hostWithoutPort;
  12110. }
  12111. else {
  12112. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12113. var dotInd = host.indexOf('.');
  12114. subdomain = host.substring(0, dotInd).toLowerCase();
  12115. domain = host.substring(dotInd + 1);
  12116. // Normalize namespaces to lowercase to share storage / connection.
  12117. namespace = subdomain;
  12118. }
  12119. // Always treat the value of the `ns` as the namespace name if it is present.
  12120. if ('ns' in queryParams) {
  12121. namespace = queryParams['ns'];
  12122. }
  12123. }
  12124. return {
  12125. host: host,
  12126. port: port,
  12127. domain: domain,
  12128. subdomain: subdomain,
  12129. secure: secure,
  12130. scheme: scheme,
  12131. pathString: pathString,
  12132. namespace: namespace
  12133. };
  12134. };
  12135. /**
  12136. * @license
  12137. * Copyright 2017 Google LLC
  12138. *
  12139. * Licensed under the Apache License, Version 2.0 (the "License");
  12140. * you may not use this file except in compliance with the License.
  12141. * You may obtain a copy of the License at
  12142. *
  12143. * http://www.apache.org/licenses/LICENSE-2.0
  12144. *
  12145. * Unless required by applicable law or agreed to in writing, software
  12146. * distributed under the License is distributed on an "AS IS" BASIS,
  12147. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12148. * See the License for the specific language governing permissions and
  12149. * limitations under the License.
  12150. */
  12151. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12152. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12153. /**
  12154. * Fancy ID generator that creates 20-character string identifiers with the
  12155. * following properties:
  12156. *
  12157. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12158. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12159. * collide with other clients' IDs.
  12160. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12161. * that will sort properly).
  12162. * 4. They're monotonically increasing. Even if you generate more than one in
  12163. * the same timestamp, the latter ones will sort after the former ones. We do
  12164. * this by using the previous random bits but "incrementing" them by 1 (only
  12165. * in the case of a timestamp collision).
  12166. */
  12167. var nextPushId = (function () {
  12168. // Timestamp of last push, used to prevent local collisions if you push twice
  12169. // in one ms.
  12170. var lastPushTime = 0;
  12171. // We generate 72-bits of randomness which get turned into 12 characters and
  12172. // appended to the timestamp to prevent collisions with other clients. We
  12173. // store the last characters we generated because in the event of a collision,
  12174. // we'll use those same characters except "incremented" by one.
  12175. var lastRandChars = [];
  12176. return function (now) {
  12177. var duplicateTime = now === lastPushTime;
  12178. lastPushTime = now;
  12179. var i;
  12180. var timeStampChars = new Array(8);
  12181. for (i = 7; i >= 0; i--) {
  12182. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12183. // NOTE: Can't use << here because javascript will convert to int and lose
  12184. // the upper bits.
  12185. now = Math.floor(now / 64);
  12186. }
  12187. assert(now === 0, 'Cannot push at time == 0');
  12188. var id = timeStampChars.join('');
  12189. if (!duplicateTime) {
  12190. for (i = 0; i < 12; i++) {
  12191. lastRandChars[i] = Math.floor(Math.random() * 64);
  12192. }
  12193. }
  12194. else {
  12195. // If the timestamp hasn't changed since last push, use the same random
  12196. // number, except incremented by 1.
  12197. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12198. lastRandChars[i] = 0;
  12199. }
  12200. lastRandChars[i]++;
  12201. }
  12202. for (i = 0; i < 12; i++) {
  12203. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12204. }
  12205. assert(id.length === 20, 'nextPushId: Length should be 20.');
  12206. return id;
  12207. };
  12208. })();
  12209. /**
  12210. * @license
  12211. * Copyright 2017 Google LLC
  12212. *
  12213. * Licensed under the Apache License, Version 2.0 (the "License");
  12214. * you may not use this file except in compliance with the License.
  12215. * You may obtain a copy of the License at
  12216. *
  12217. * http://www.apache.org/licenses/LICENSE-2.0
  12218. *
  12219. * Unless required by applicable law or agreed to in writing, software
  12220. * distributed under the License is distributed on an "AS IS" BASIS,
  12221. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12222. * See the License for the specific language governing permissions and
  12223. * limitations under the License.
  12224. */
  12225. /**
  12226. * Encapsulates the data needed to raise an event
  12227. */
  12228. var DataEvent = /** @class */ (function () {
  12229. /**
  12230. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12231. * @param eventRegistration - The function to call to with the event data. User provided
  12232. * @param snapshot - The data backing the event
  12233. * @param prevName - Optional, the name of the previous child for child_* events.
  12234. */
  12235. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12236. this.eventType = eventType;
  12237. this.eventRegistration = eventRegistration;
  12238. this.snapshot = snapshot;
  12239. this.prevName = prevName;
  12240. }
  12241. DataEvent.prototype.getPath = function () {
  12242. var ref = this.snapshot.ref;
  12243. if (this.eventType === 'value') {
  12244. return ref._path;
  12245. }
  12246. else {
  12247. return ref.parent._path;
  12248. }
  12249. };
  12250. DataEvent.prototype.getEventType = function () {
  12251. return this.eventType;
  12252. };
  12253. DataEvent.prototype.getEventRunner = function () {
  12254. return this.eventRegistration.getEventRunner(this);
  12255. };
  12256. DataEvent.prototype.toString = function () {
  12257. return (this.getPath().toString() +
  12258. ':' +
  12259. this.eventType +
  12260. ':' +
  12261. stringify(this.snapshot.exportVal()));
  12262. };
  12263. return DataEvent;
  12264. }());
  12265. var CancelEvent = /** @class */ (function () {
  12266. function CancelEvent(eventRegistration, error, path) {
  12267. this.eventRegistration = eventRegistration;
  12268. this.error = error;
  12269. this.path = path;
  12270. }
  12271. CancelEvent.prototype.getPath = function () {
  12272. return this.path;
  12273. };
  12274. CancelEvent.prototype.getEventType = function () {
  12275. return 'cancel';
  12276. };
  12277. CancelEvent.prototype.getEventRunner = function () {
  12278. return this.eventRegistration.getEventRunner(this);
  12279. };
  12280. CancelEvent.prototype.toString = function () {
  12281. return this.path.toString() + ':cancel';
  12282. };
  12283. return CancelEvent;
  12284. }());
  12285. /**
  12286. * @license
  12287. * Copyright 2017 Google LLC
  12288. *
  12289. * Licensed under the Apache License, Version 2.0 (the "License");
  12290. * you may not use this file except in compliance with the License.
  12291. * You may obtain a copy of the License at
  12292. *
  12293. * http://www.apache.org/licenses/LICENSE-2.0
  12294. *
  12295. * Unless required by applicable law or agreed to in writing, software
  12296. * distributed under the License is distributed on an "AS IS" BASIS,
  12297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12298. * See the License for the specific language governing permissions and
  12299. * limitations under the License.
  12300. */
  12301. /**
  12302. * A wrapper class that converts events from the database@exp SDK to the legacy
  12303. * Database SDK. Events are not converted directly as event registration relies
  12304. * on reference comparison of the original user callback (see `matches()`) and
  12305. * relies on equality of the legacy SDK's `context` object.
  12306. */
  12307. var CallbackContext = /** @class */ (function () {
  12308. function CallbackContext(snapshotCallback, cancelCallback) {
  12309. this.snapshotCallback = snapshotCallback;
  12310. this.cancelCallback = cancelCallback;
  12311. }
  12312. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12313. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12314. };
  12315. CallbackContext.prototype.onCancel = function (error) {
  12316. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12317. return this.cancelCallback.call(null, error);
  12318. };
  12319. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12320. get: function () {
  12321. return !!this.cancelCallback;
  12322. },
  12323. enumerable: false,
  12324. configurable: true
  12325. });
  12326. CallbackContext.prototype.matches = function (other) {
  12327. return (this.snapshotCallback === other.snapshotCallback ||
  12328. (this.snapshotCallback.userCallback !== undefined &&
  12329. this.snapshotCallback.userCallback ===
  12330. other.snapshotCallback.userCallback &&
  12331. this.snapshotCallback.context === other.snapshotCallback.context));
  12332. };
  12333. return CallbackContext;
  12334. }());
  12335. /**
  12336. * @license
  12337. * Copyright 2021 Google LLC
  12338. *
  12339. * Licensed under the Apache License, Version 2.0 (the "License");
  12340. * you may not use this file except in compliance with the License.
  12341. * You may obtain a copy of the License at
  12342. *
  12343. * http://www.apache.org/licenses/LICENSE-2.0
  12344. *
  12345. * Unless required by applicable law or agreed to in writing, software
  12346. * distributed under the License is distributed on an "AS IS" BASIS,
  12347. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12348. * See the License for the specific language governing permissions and
  12349. * limitations under the License.
  12350. */
  12351. /**
  12352. * The `onDisconnect` class allows you to write or clear data when your client
  12353. * disconnects from the Database server. These updates occur whether your
  12354. * client disconnects cleanly or not, so you can rely on them to clean up data
  12355. * even if a connection is dropped or a client crashes.
  12356. *
  12357. * The `onDisconnect` class is most commonly used to manage presence in
  12358. * applications where it is useful to detect how many clients are connected and
  12359. * when other clients disconnect. See
  12360. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12361. * for more information.
  12362. *
  12363. * To avoid problems when a connection is dropped before the requests can be
  12364. * transferred to the Database server, these functions should be called before
  12365. * writing any data.
  12366. *
  12367. * Note that `onDisconnect` operations are only triggered once. If you want an
  12368. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12369. * the `onDisconnect` operations each time you reconnect.
  12370. */
  12371. var OnDisconnect = /** @class */ (function () {
  12372. /** @hideconstructor */
  12373. function OnDisconnect(_repo, _path) {
  12374. this._repo = _repo;
  12375. this._path = _path;
  12376. }
  12377. /**
  12378. * Cancels all previously queued `onDisconnect()` set or update events for this
  12379. * location and all children.
  12380. *
  12381. * If a write has been queued for this location via a `set()` or `update()` at a
  12382. * parent location, the write at this location will be canceled, though writes
  12383. * to sibling locations will still occur.
  12384. *
  12385. * @returns Resolves when synchronization to the server is complete.
  12386. */
  12387. OnDisconnect.prototype.cancel = function () {
  12388. var deferred = new Deferred();
  12389. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12390. return deferred.promise;
  12391. };
  12392. /**
  12393. * Ensures the data at this location is deleted when the client is disconnected
  12394. * (due to closing the browser, navigating to a new page, or network issues).
  12395. *
  12396. * @returns Resolves when synchronization to the server is complete.
  12397. */
  12398. OnDisconnect.prototype.remove = function () {
  12399. validateWritablePath('OnDisconnect.remove', this._path);
  12400. var deferred = new Deferred();
  12401. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12402. return deferred.promise;
  12403. };
  12404. /**
  12405. * Ensures the data at this location is set to the specified value when the
  12406. * client is disconnected (due to closing the browser, navigating to a new page,
  12407. * or network issues).
  12408. *
  12409. * `set()` is especially useful for implementing "presence" systems, where a
  12410. * value should be changed or cleared when a user disconnects so that they
  12411. * appear "offline" to other users. See
  12412. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12413. * for more information.
  12414. *
  12415. * Note that `onDisconnect` operations are only triggered once. If you want an
  12416. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12417. * the `onDisconnect` operations each time.
  12418. *
  12419. * @param value - The value to be written to this location on disconnect (can
  12420. * be an object, array, string, number, boolean, or null).
  12421. * @returns Resolves when synchronization to the Database is complete.
  12422. */
  12423. OnDisconnect.prototype.set = function (value) {
  12424. validateWritablePath('OnDisconnect.set', this._path);
  12425. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12426. var deferred = new Deferred();
  12427. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12428. return deferred.promise;
  12429. };
  12430. /**
  12431. * Ensures the data at this location is set to the specified value and priority
  12432. * when the client is disconnected (due to closing the browser, navigating to a
  12433. * new page, or network issues).
  12434. *
  12435. * @param value - The value to be written to this location on disconnect (can
  12436. * be an object, array, string, number, boolean, or null).
  12437. * @param priority - The priority to be written (string, number, or null).
  12438. * @returns Resolves when synchronization to the Database is complete.
  12439. */
  12440. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12441. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12442. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12443. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12444. var deferred = new Deferred();
  12445. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12446. return deferred.promise;
  12447. };
  12448. /**
  12449. * Writes multiple values at this location when the client is disconnected (due
  12450. * to closing the browser, navigating to a new page, or network issues).
  12451. *
  12452. * The `values` argument contains multiple property-value pairs that will be
  12453. * written to the Database together. Each child property can either be a simple
  12454. * property (for example, "name") or a relative path (for example, "name/first")
  12455. * from the current location to the data to update.
  12456. *
  12457. * As opposed to the `set()` method, `update()` can be use to selectively update
  12458. * only the referenced properties at the current location (instead of replacing
  12459. * all the child properties at the current location).
  12460. *
  12461. * @param values - Object containing multiple values.
  12462. * @returns Resolves when synchronization to the Database is complete.
  12463. */
  12464. OnDisconnect.prototype.update = function (values) {
  12465. validateWritablePath('OnDisconnect.update', this._path);
  12466. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12467. var deferred = new Deferred();
  12468. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12469. return deferred.promise;
  12470. };
  12471. return OnDisconnect;
  12472. }());
  12473. /**
  12474. * @license
  12475. * Copyright 2020 Google LLC
  12476. *
  12477. * Licensed under the Apache License, Version 2.0 (the "License");
  12478. * you may not use this file except in compliance with the License.
  12479. * You may obtain a copy of the License at
  12480. *
  12481. * http://www.apache.org/licenses/LICENSE-2.0
  12482. *
  12483. * Unless required by applicable law or agreed to in writing, software
  12484. * distributed under the License is distributed on an "AS IS" BASIS,
  12485. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12486. * See the License for the specific language governing permissions and
  12487. * limitations under the License.
  12488. */
  12489. /**
  12490. * @internal
  12491. */
  12492. var QueryImpl = /** @class */ (function () {
  12493. /**
  12494. * @hideconstructor
  12495. */
  12496. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12497. this._repo = _repo;
  12498. this._path = _path;
  12499. this._queryParams = _queryParams;
  12500. this._orderByCalled = _orderByCalled;
  12501. }
  12502. Object.defineProperty(QueryImpl.prototype, "key", {
  12503. get: function () {
  12504. if (pathIsEmpty(this._path)) {
  12505. return null;
  12506. }
  12507. else {
  12508. return pathGetBack(this._path);
  12509. }
  12510. },
  12511. enumerable: false,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(QueryImpl.prototype, "ref", {
  12515. get: function () {
  12516. return new ReferenceImpl(this._repo, this._path);
  12517. },
  12518. enumerable: false,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12522. get: function () {
  12523. var obj = queryParamsGetQueryObject(this._queryParams);
  12524. var id = ObjectToUniqueKey(obj);
  12525. return id === '{}' ? 'default' : id;
  12526. },
  12527. enumerable: false,
  12528. configurable: true
  12529. });
  12530. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12531. /**
  12532. * An object representation of the query parameters used by this Query.
  12533. */
  12534. get: function () {
  12535. return queryParamsGetQueryObject(this._queryParams);
  12536. },
  12537. enumerable: false,
  12538. configurable: true
  12539. });
  12540. QueryImpl.prototype.isEqual = function (other) {
  12541. other = getModularInstance(other);
  12542. if (!(other instanceof QueryImpl)) {
  12543. return false;
  12544. }
  12545. var sameRepo = this._repo === other._repo;
  12546. var samePath = pathEquals(this._path, other._path);
  12547. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12548. return sameRepo && samePath && sameQueryIdentifier;
  12549. };
  12550. QueryImpl.prototype.toJSON = function () {
  12551. return this.toString();
  12552. };
  12553. QueryImpl.prototype.toString = function () {
  12554. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12555. };
  12556. return QueryImpl;
  12557. }());
  12558. /**
  12559. * Validates that no other order by call has been made
  12560. */
  12561. function validateNoPreviousOrderByCall(query, fnName) {
  12562. if (query._orderByCalled === true) {
  12563. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12564. }
  12565. }
  12566. /**
  12567. * Validates start/end values for queries.
  12568. */
  12569. function validateQueryEndpoints(params) {
  12570. var startNode = null;
  12571. var endNode = null;
  12572. if (params.hasStart()) {
  12573. startNode = params.getIndexStartValue();
  12574. }
  12575. if (params.hasEnd()) {
  12576. endNode = params.getIndexEndValue();
  12577. }
  12578. if (params.getIndex() === KEY_INDEX) {
  12579. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12580. 'startAt(), endAt(), or equalTo().';
  12581. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12582. 'endAt(), endBefore(), or equalTo() must be a string.';
  12583. if (params.hasStart()) {
  12584. var startName = params.getIndexStartName();
  12585. if (startName !== MIN_NAME) {
  12586. throw new Error(tooManyArgsError);
  12587. }
  12588. else if (typeof startNode !== 'string') {
  12589. throw new Error(wrongArgTypeError);
  12590. }
  12591. }
  12592. if (params.hasEnd()) {
  12593. var endName = params.getIndexEndName();
  12594. if (endName !== MAX_NAME) {
  12595. throw new Error(tooManyArgsError);
  12596. }
  12597. else if (typeof endNode !== 'string') {
  12598. throw new Error(wrongArgTypeError);
  12599. }
  12600. }
  12601. }
  12602. else if (params.getIndex() === PRIORITY_INDEX) {
  12603. if ((startNode != null && !isValidPriority(startNode)) ||
  12604. (endNode != null && !isValidPriority(endNode))) {
  12605. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12606. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12607. '(null, a number, or a string).');
  12608. }
  12609. }
  12610. else {
  12611. assert(params.getIndex() instanceof PathIndex ||
  12612. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12613. if ((startNode != null && typeof startNode === 'object') ||
  12614. (endNode != null && typeof endNode === 'object')) {
  12615. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12616. 'equalTo() cannot be an object.');
  12617. }
  12618. }
  12619. }
  12620. /**
  12621. * Validates that limit* has been called with the correct combination of parameters
  12622. */
  12623. function validateLimit(params) {
  12624. if (params.hasStart() &&
  12625. params.hasEnd() &&
  12626. params.hasLimit() &&
  12627. !params.hasAnchoredLimit()) {
  12628. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12629. 'limitToFirst() or limitToLast() instead.');
  12630. }
  12631. }
  12632. /**
  12633. * @internal
  12634. */
  12635. var ReferenceImpl = /** @class */ (function (_super) {
  12636. __extends(ReferenceImpl, _super);
  12637. /** @hideconstructor */
  12638. function ReferenceImpl(repo, path) {
  12639. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12640. }
  12641. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12642. get: function () {
  12643. var parentPath = pathParent(this._path);
  12644. return parentPath === null
  12645. ? null
  12646. : new ReferenceImpl(this._repo, parentPath);
  12647. },
  12648. enumerable: false,
  12649. configurable: true
  12650. });
  12651. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12652. get: function () {
  12653. var ref = this;
  12654. while (ref.parent !== null) {
  12655. ref = ref.parent;
  12656. }
  12657. return ref;
  12658. },
  12659. enumerable: false,
  12660. configurable: true
  12661. });
  12662. return ReferenceImpl;
  12663. }(QueryImpl));
  12664. /**
  12665. * A `DataSnapshot` contains data from a Database location.
  12666. *
  12667. * Any time you read data from the Database, you receive the data as a
  12668. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12669. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12670. * JavaScript object by calling the `val()` method. Alternatively, you can
  12671. * traverse into the snapshot by calling `child()` to return child snapshots
  12672. * (which you could then call `val()` on).
  12673. *
  12674. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12675. * a Database location. It cannot be modified and will never change (to modify
  12676. * data, you always call the `set()` method on a `Reference` directly).
  12677. */
  12678. var DataSnapshot = /** @class */ (function () {
  12679. /**
  12680. * @param _node - A SnapshotNode to wrap.
  12681. * @param ref - The location this snapshot came from.
  12682. * @param _index - The iteration order for this snapshot
  12683. * @hideconstructor
  12684. */
  12685. function DataSnapshot(_node,
  12686. /**
  12687. * The location of this DataSnapshot.
  12688. */
  12689. ref, _index) {
  12690. this._node = _node;
  12691. this.ref = ref;
  12692. this._index = _index;
  12693. }
  12694. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12695. /**
  12696. * Gets the priority value of the data in this `DataSnapshot`.
  12697. *
  12698. * Applications need not use priority but can order collections by
  12699. * ordinary properties (see
  12700. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12701. * ).
  12702. */
  12703. get: function () {
  12704. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12705. return this._node.getPriority().val();
  12706. },
  12707. enumerable: false,
  12708. configurable: true
  12709. });
  12710. Object.defineProperty(DataSnapshot.prototype, "key", {
  12711. /**
  12712. * The key (last part of the path) of the location of this `DataSnapshot`.
  12713. *
  12714. * The last token in a Database location is considered its key. For example,
  12715. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12716. * `DataSnapshot` will return the key for the location that generated it.
  12717. * However, accessing the key on the root URL of a Database will return
  12718. * `null`.
  12719. */
  12720. get: function () {
  12721. return this.ref.key;
  12722. },
  12723. enumerable: false,
  12724. configurable: true
  12725. });
  12726. Object.defineProperty(DataSnapshot.prototype, "size", {
  12727. /** Returns the number of child properties of this `DataSnapshot`. */
  12728. get: function () {
  12729. return this._node.numChildren();
  12730. },
  12731. enumerable: false,
  12732. configurable: true
  12733. });
  12734. /**
  12735. * Gets another `DataSnapshot` for the location at the specified relative path.
  12736. *
  12737. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12738. * another `DataSnapshot` for the location at the specified relative path. The
  12739. * relative path can either be a simple child name (for example, "ada") or a
  12740. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12741. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12742. * whose value is `null`) is returned.
  12743. *
  12744. * @param path - A relative path to the location of child data.
  12745. */
  12746. DataSnapshot.prototype.child = function (path) {
  12747. var childPath = new Path(path);
  12748. var childRef = child(this.ref, path);
  12749. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12750. };
  12751. /**
  12752. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12753. * efficient than using `snapshot.val() !== null`.
  12754. */
  12755. DataSnapshot.prototype.exists = function () {
  12756. return !this._node.isEmpty();
  12757. };
  12758. /**
  12759. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12760. *
  12761. * The `exportVal()` method is similar to `val()`, except priority information
  12762. * is included (if available), making it suitable for backing up your data.
  12763. *
  12764. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12765. * Array, string, number, boolean, or `null`).
  12766. */
  12767. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12768. DataSnapshot.prototype.exportVal = function () {
  12769. return this._node.val(true);
  12770. };
  12771. /**
  12772. * Enumerates the top-level children in the `DataSnapshot`.
  12773. *
  12774. * Because of the way JavaScript objects work, the ordering of data in the
  12775. * JavaScript object returned by `val()` is not guaranteed to match the
  12776. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12777. * where `forEach()` comes in handy. It guarantees the children of a
  12778. * `DataSnapshot` will be iterated in their query order.
  12779. *
  12780. * If no explicit `orderBy*()` method is used, results are returned
  12781. * ordered by key (unless priorities are used, in which case, results are
  12782. * returned by priority).
  12783. *
  12784. * @param action - A function that will be called for each child DataSnapshot.
  12785. * The callback can return true to cancel further enumeration.
  12786. * @returns true if enumeration was canceled due to your callback returning
  12787. * true.
  12788. */
  12789. DataSnapshot.prototype.forEach = function (action) {
  12790. var _this = this;
  12791. if (this._node.isLeafNode()) {
  12792. return false;
  12793. }
  12794. var childrenNode = this._node;
  12795. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12796. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12797. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12798. });
  12799. };
  12800. /**
  12801. * Returns true if the specified child path has (non-null) data.
  12802. *
  12803. * @param path - A relative path to the location of a potential child.
  12804. * @returns `true` if data exists at the specified child path; else
  12805. * `false`.
  12806. */
  12807. DataSnapshot.prototype.hasChild = function (path) {
  12808. var childPath = new Path(path);
  12809. return !this._node.getChild(childPath).isEmpty();
  12810. };
  12811. /**
  12812. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12813. * properties.
  12814. *
  12815. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12816. * children. If it does, you can enumerate them using `forEach()`. If it
  12817. * doesn't, then either this snapshot contains a primitive value (which can be
  12818. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12819. * `null`).
  12820. *
  12821. * @returns true if this snapshot has any children; else false.
  12822. */
  12823. DataSnapshot.prototype.hasChildren = function () {
  12824. if (this._node.isLeafNode()) {
  12825. return false;
  12826. }
  12827. else {
  12828. return !this._node.isEmpty();
  12829. }
  12830. };
  12831. /**
  12832. * Returns a JSON-serializable representation of this object.
  12833. */
  12834. DataSnapshot.prototype.toJSON = function () {
  12835. return this.exportVal();
  12836. };
  12837. /**
  12838. * Extracts a JavaScript value from a `DataSnapshot`.
  12839. *
  12840. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12841. * scalar type (string, number, or boolean), an array, or an object. It may
  12842. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12843. * data).
  12844. *
  12845. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12846. * Array, string, number, boolean, or `null`).
  12847. */
  12848. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12849. DataSnapshot.prototype.val = function () {
  12850. return this._node.val();
  12851. };
  12852. return DataSnapshot;
  12853. }());
  12854. /**
  12855. *
  12856. * Returns a `Reference` representing the location in the Database
  12857. * corresponding to the provided path. If no path is provided, the `Reference`
  12858. * will point to the root of the Database.
  12859. *
  12860. * @param db - The database instance to obtain a reference for.
  12861. * @param path - Optional path representing the location the returned
  12862. * `Reference` will point. If not provided, the returned `Reference` will
  12863. * point to the root of the Database.
  12864. * @returns If a path is provided, a `Reference`
  12865. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12866. * root of the Database.
  12867. */
  12868. function ref(db, path) {
  12869. db = getModularInstance(db);
  12870. db._checkNotDeleted('ref');
  12871. return path !== undefined ? child(db._root, path) : db._root;
  12872. }
  12873. /**
  12874. * Returns a `Reference` representing the location in the Database
  12875. * corresponding to the provided Firebase URL.
  12876. *
  12877. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12878. * has a different domain than the current `Database` instance.
  12879. *
  12880. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12881. * and are not applied to the returned `Reference`.
  12882. *
  12883. * @param db - The database instance to obtain a reference for.
  12884. * @param url - The Firebase URL at which the returned `Reference` will
  12885. * point.
  12886. * @returns A `Reference` pointing to the provided
  12887. * Firebase URL.
  12888. */
  12889. function refFromURL(db, url) {
  12890. db = getModularInstance(db);
  12891. db._checkNotDeleted('refFromURL');
  12892. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12893. validateUrl('refFromURL', parsedURL);
  12894. var repoInfo = parsedURL.repoInfo;
  12895. if (!db._repo.repoInfo_.isCustomHost() &&
  12896. repoInfo.host !== db._repo.repoInfo_.host) {
  12897. fatal('refFromURL' +
  12898. ': Host name does not match the current database: ' +
  12899. '(found ' +
  12900. repoInfo.host +
  12901. ' but expected ' +
  12902. db._repo.repoInfo_.host +
  12903. ')');
  12904. }
  12905. return ref(db, parsedURL.path.toString());
  12906. }
  12907. /**
  12908. * Gets a `Reference` for the location at the specified relative path.
  12909. *
  12910. * The relative path can either be a simple child name (for example, "ada") or
  12911. * a deeper slash-separated path (for example, "ada/name/first").
  12912. *
  12913. * @param parent - The parent location.
  12914. * @param path - A relative path from this location to the desired child
  12915. * location.
  12916. * @returns The specified child location.
  12917. */
  12918. function child(parent, path) {
  12919. parent = getModularInstance(parent);
  12920. if (pathGetFront(parent._path) === null) {
  12921. validateRootPathString('child', 'path', path, false);
  12922. }
  12923. else {
  12924. validatePathString('child', 'path', path, false);
  12925. }
  12926. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12927. }
  12928. /**
  12929. * Returns an `OnDisconnect` object - see
  12930. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12931. * for more information on how to use it.
  12932. *
  12933. * @param ref - The reference to add OnDisconnect triggers for.
  12934. */
  12935. function onDisconnect(ref) {
  12936. ref = getModularInstance(ref);
  12937. return new OnDisconnect(ref._repo, ref._path);
  12938. }
  12939. /**
  12940. * Generates a new child location using a unique key and returns its
  12941. * `Reference`.
  12942. *
  12943. * This is the most common pattern for adding data to a collection of items.
  12944. *
  12945. * If you provide a value to `push()`, the value is written to the
  12946. * generated location. If you don't pass a value, nothing is written to the
  12947. * database and the child remains empty (but you can use the `Reference`
  12948. * elsewhere).
  12949. *
  12950. * The unique keys generated by `push()` are ordered by the current time, so the
  12951. * resulting list of items is chronologically sorted. The keys are also
  12952. * designed to be unguessable (they contain 72 random bits of entropy).
  12953. *
  12954. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12955. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12956. *
  12957. * @param parent - The parent location.
  12958. * @param value - Optional value to be written at the generated location.
  12959. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12960. * but can be used immediately as the `Reference` to the child location.
  12961. */
  12962. function push(parent, value) {
  12963. parent = getModularInstance(parent);
  12964. validateWritablePath('push', parent._path);
  12965. validateFirebaseDataArg('push', value, parent._path, true);
  12966. var now = repoServerTime(parent._repo);
  12967. var name = nextPushId(now);
  12968. // push() returns a ThennableReference whose promise is fulfilled with a
  12969. // regular Reference. We use child() to create handles to two different
  12970. // references. The first is turned into a ThennableReference below by adding
  12971. // then() and catch() methods and is used as the return value of push(). The
  12972. // second remains a regular Reference and is used as the fulfilled value of
  12973. // the first ThennableReference.
  12974. var thennablePushRef = child(parent, name);
  12975. var pushRef = child(parent, name);
  12976. var promise;
  12977. if (value != null) {
  12978. promise = set(pushRef, value).then(function () { return pushRef; });
  12979. }
  12980. else {
  12981. promise = Promise.resolve(pushRef);
  12982. }
  12983. thennablePushRef.then = promise.then.bind(promise);
  12984. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12985. return thennablePushRef;
  12986. }
  12987. /**
  12988. * Removes the data at this Database location.
  12989. *
  12990. * Any data at child locations will also be deleted.
  12991. *
  12992. * The effect of the remove will be visible immediately and the corresponding
  12993. * event 'value' will be triggered. Synchronization of the remove to the
  12994. * Firebase servers will also be started, and the returned Promise will resolve
  12995. * when complete. If provided, the onComplete callback will be called
  12996. * asynchronously after synchronization has finished.
  12997. *
  12998. * @param ref - The location to remove.
  12999. * @returns Resolves when remove on server is complete.
  13000. */
  13001. function remove(ref) {
  13002. validateWritablePath('remove', ref._path);
  13003. return set(ref, null);
  13004. }
  13005. /**
  13006. * Writes data to this Database location.
  13007. *
  13008. * This will overwrite any data at this location and all child locations.
  13009. *
  13010. * The effect of the write will be visible immediately, and the corresponding
  13011. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13012. * the data to the Firebase servers will also be started, and the returned
  13013. * Promise will resolve when complete. If provided, the `onComplete` callback
  13014. * will be called asynchronously after synchronization has finished.
  13015. *
  13016. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13017. * all data at this location and all child locations will be deleted.
  13018. *
  13019. * `set()` will remove any priority stored at this location, so if priority is
  13020. * meant to be preserved, you need to use `setWithPriority()` instead.
  13021. *
  13022. * Note that modifying data with `set()` will cancel any pending transactions
  13023. * at that location, so extreme care should be taken if mixing `set()` and
  13024. * `transaction()` to modify the same data.
  13025. *
  13026. * A single `set()` will generate a single "value" event at the location where
  13027. * the `set()` was performed.
  13028. *
  13029. * @param ref - The location to write to.
  13030. * @param value - The value to be written (string, number, boolean, object,
  13031. * array, or null).
  13032. * @returns Resolves when write to server is complete.
  13033. */
  13034. function set(ref, value) {
  13035. ref = getModularInstance(ref);
  13036. validateWritablePath('set', ref._path);
  13037. validateFirebaseDataArg('set', value, ref._path, false);
  13038. var deferred = new Deferred();
  13039. repoSetWithPriority(ref._repo, ref._path, value,
  13040. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13041. return deferred.promise;
  13042. }
  13043. /**
  13044. * Sets a priority for the data at this Database location.
  13045. *
  13046. * Applications need not use priority but can order collections by
  13047. * ordinary properties (see
  13048. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13049. * ).
  13050. *
  13051. * @param ref - The location to write to.
  13052. * @param priority - The priority to be written (string, number, or null).
  13053. * @returns Resolves when write to server is complete.
  13054. */
  13055. function setPriority(ref, priority) {
  13056. ref = getModularInstance(ref);
  13057. validateWritablePath('setPriority', ref._path);
  13058. validatePriority('setPriority', priority, false);
  13059. var deferred = new Deferred();
  13060. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13061. return deferred.promise;
  13062. }
  13063. /**
  13064. * Writes data the Database location. Like `set()` but also specifies the
  13065. * priority for that data.
  13066. *
  13067. * Applications need not use priority but can order collections by
  13068. * ordinary properties (see
  13069. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13070. * ).
  13071. *
  13072. * @param ref - The location to write to.
  13073. * @param value - The value to be written (string, number, boolean, object,
  13074. * array, or null).
  13075. * @param priority - The priority to be written (string, number, or null).
  13076. * @returns Resolves when write to server is complete.
  13077. */
  13078. function setWithPriority(ref, value, priority) {
  13079. validateWritablePath('setWithPriority', ref._path);
  13080. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13081. validatePriority('setWithPriority', priority, false);
  13082. if (ref.key === '.length' || ref.key === '.keys') {
  13083. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13084. }
  13085. var deferred = new Deferred();
  13086. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13087. return deferred.promise;
  13088. }
  13089. /**
  13090. * Writes multiple values to the Database at once.
  13091. *
  13092. * The `values` argument contains multiple property-value pairs that will be
  13093. * written to the Database together. Each child property can either be a simple
  13094. * property (for example, "name") or a relative path (for example,
  13095. * "name/first") from the current location to the data to update.
  13096. *
  13097. * As opposed to the `set()` method, `update()` can be use to selectively update
  13098. * only the referenced properties at the current location (instead of replacing
  13099. * all the child properties at the current location).
  13100. *
  13101. * The effect of the write will be visible immediately, and the corresponding
  13102. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13103. * the data to the Firebase servers will also be started, and the returned
  13104. * Promise will resolve when complete. If provided, the `onComplete` callback
  13105. * will be called asynchronously after synchronization has finished.
  13106. *
  13107. * A single `update()` will generate a single "value" event at the location
  13108. * where the `update()` was performed, regardless of how many children were
  13109. * modified.
  13110. *
  13111. * Note that modifying data with `update()` will cancel any pending
  13112. * transactions at that location, so extreme care should be taken if mixing
  13113. * `update()` and `transaction()` to modify the same data.
  13114. *
  13115. * Passing `null` to `update()` will remove the data at this location.
  13116. *
  13117. * See
  13118. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13119. *
  13120. * @param ref - The location to write to.
  13121. * @param values - Object containing multiple values.
  13122. * @returns Resolves when update on server is complete.
  13123. */
  13124. function update(ref, values) {
  13125. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13126. var deferred = new Deferred();
  13127. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13128. return deferred.promise;
  13129. }
  13130. /**
  13131. * Gets the most up-to-date result for this query.
  13132. *
  13133. * @param query - The query to run.
  13134. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13135. * available, or rejects if the client is unable to return a value (e.g., if the
  13136. * server is unreachable and there is nothing cached).
  13137. */
  13138. function get(query) {
  13139. query = getModularInstance(query);
  13140. var callbackContext = new CallbackContext(function () { });
  13141. var container = new ValueEventRegistration(callbackContext);
  13142. return repoGetValue(query._repo, query, container).then(function (node) {
  13143. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13144. });
  13145. }
  13146. /**
  13147. * Represents registration for 'value' events.
  13148. */
  13149. var ValueEventRegistration = /** @class */ (function () {
  13150. function ValueEventRegistration(callbackContext) {
  13151. this.callbackContext = callbackContext;
  13152. }
  13153. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13154. return eventType === 'value';
  13155. };
  13156. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13157. var index = query._queryParams.getIndex();
  13158. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13159. };
  13160. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13161. var _this = this;
  13162. if (eventData.getEventType() === 'cancel') {
  13163. return function () {
  13164. return _this.callbackContext.onCancel(eventData.error);
  13165. };
  13166. }
  13167. else {
  13168. return function () {
  13169. return _this.callbackContext.onValue(eventData.snapshot, null);
  13170. };
  13171. }
  13172. };
  13173. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13174. if (this.callbackContext.hasCancelCallback) {
  13175. return new CancelEvent(this, error, path);
  13176. }
  13177. else {
  13178. return null;
  13179. }
  13180. };
  13181. ValueEventRegistration.prototype.matches = function (other) {
  13182. if (!(other instanceof ValueEventRegistration)) {
  13183. return false;
  13184. }
  13185. else if (!other.callbackContext || !this.callbackContext) {
  13186. // If no callback specified, we consider it to match any callback.
  13187. return true;
  13188. }
  13189. else {
  13190. return other.callbackContext.matches(this.callbackContext);
  13191. }
  13192. };
  13193. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13194. return this.callbackContext !== null;
  13195. };
  13196. return ValueEventRegistration;
  13197. }());
  13198. /**
  13199. * Represents the registration of a child_x event.
  13200. */
  13201. var ChildEventRegistration = /** @class */ (function () {
  13202. function ChildEventRegistration(eventType, callbackContext) {
  13203. this.eventType = eventType;
  13204. this.callbackContext = callbackContext;
  13205. }
  13206. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13207. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13208. eventToCheck =
  13209. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13210. return this.eventType === eventToCheck;
  13211. };
  13212. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13213. if (this.callbackContext.hasCancelCallback) {
  13214. return new CancelEvent(this, error, path);
  13215. }
  13216. else {
  13217. return null;
  13218. }
  13219. };
  13220. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13221. assert(change.childName != null, 'Child events should have a childName.');
  13222. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13223. var index = query._queryParams.getIndex();
  13224. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13225. };
  13226. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13227. var _this = this;
  13228. if (eventData.getEventType() === 'cancel') {
  13229. return function () {
  13230. return _this.callbackContext.onCancel(eventData.error);
  13231. };
  13232. }
  13233. else {
  13234. return function () {
  13235. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13236. };
  13237. }
  13238. };
  13239. ChildEventRegistration.prototype.matches = function (other) {
  13240. if (other instanceof ChildEventRegistration) {
  13241. return (this.eventType === other.eventType &&
  13242. (!this.callbackContext ||
  13243. !other.callbackContext ||
  13244. this.callbackContext.matches(other.callbackContext)));
  13245. }
  13246. return false;
  13247. };
  13248. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13249. return !!this.callbackContext;
  13250. };
  13251. return ChildEventRegistration;
  13252. }());
  13253. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13254. var cancelCallback;
  13255. if (typeof cancelCallbackOrListenOptions === 'object') {
  13256. cancelCallback = undefined;
  13257. options = cancelCallbackOrListenOptions;
  13258. }
  13259. if (typeof cancelCallbackOrListenOptions === 'function') {
  13260. cancelCallback = cancelCallbackOrListenOptions;
  13261. }
  13262. if (options && options.onlyOnce) {
  13263. var userCallback_1 = callback;
  13264. var onceCallback = function (dataSnapshot, previousChildName) {
  13265. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13266. userCallback_1(dataSnapshot, previousChildName);
  13267. };
  13268. onceCallback.userCallback = callback.userCallback;
  13269. onceCallback.context = callback.context;
  13270. callback = onceCallback;
  13271. }
  13272. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13273. var container = eventType === 'value'
  13274. ? new ValueEventRegistration(callbackContext)
  13275. : new ChildEventRegistration(eventType, callbackContext);
  13276. repoAddEventCallbackForQuery(query._repo, query, container);
  13277. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13278. }
  13279. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13280. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13281. }
  13282. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13283. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13284. }
  13285. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13286. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13287. }
  13288. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13289. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13290. }
  13291. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13292. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13293. }
  13294. /**
  13295. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13296. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13297. * the respective `on*` callbacks.
  13298. *
  13299. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13300. * will not automatically remove listeners registered on child nodes, `off()`
  13301. * must also be called on any child listeners to remove the callback.
  13302. *
  13303. * If a callback is not specified, all callbacks for the specified eventType
  13304. * will be removed. Similarly, if no eventType is specified, all callbacks
  13305. * for the `Reference` will be removed.
  13306. *
  13307. * Individual listeners can also be removed by invoking their unsubscribe
  13308. * callbacks.
  13309. *
  13310. * @param query - The query that the listener was registered with.
  13311. * @param eventType - One of the following strings: "value", "child_added",
  13312. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13313. * for the `Reference` will be removed.
  13314. * @param callback - The callback function that was passed to `on()` or
  13315. * `undefined` to remove all callbacks.
  13316. */
  13317. function off(query, eventType, callback) {
  13318. var container = null;
  13319. var expCallback = callback ? new CallbackContext(callback) : null;
  13320. if (eventType === 'value') {
  13321. container = new ValueEventRegistration(expCallback);
  13322. }
  13323. else if (eventType) {
  13324. container = new ChildEventRegistration(eventType, expCallback);
  13325. }
  13326. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13327. }
  13328. /**
  13329. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13330. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13331. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13332. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13333. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13334. * {@link orderByValue} or {@link equalTo} and
  13335. * can then be passed to {@link query} to create a new query instance that
  13336. * also contains this `QueryConstraint`.
  13337. */
  13338. var QueryConstraint = /** @class */ (function () {
  13339. function QueryConstraint() {
  13340. }
  13341. return QueryConstraint;
  13342. }());
  13343. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13344. __extends(QueryEndAtConstraint, _super);
  13345. function QueryEndAtConstraint(_value, _key) {
  13346. var _this = _super.call(this) || this;
  13347. _this._value = _value;
  13348. _this._key = _key;
  13349. return _this;
  13350. }
  13351. QueryEndAtConstraint.prototype._apply = function (query) {
  13352. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13353. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13354. validateLimit(newParams);
  13355. validateQueryEndpoints(newParams);
  13356. if (query._queryParams.hasEnd()) {
  13357. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13358. 'endBefore or equalTo).');
  13359. }
  13360. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13361. };
  13362. return QueryEndAtConstraint;
  13363. }(QueryConstraint));
  13364. /**
  13365. * Creates a `QueryConstraint` with the specified ending point.
  13366. *
  13367. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13368. * allows you to choose arbitrary starting and ending points for your queries.
  13369. *
  13370. * The ending point is inclusive, so children with exactly the specified value
  13371. * will be included in the query. The optional key argument can be used to
  13372. * further limit the range of the query. If it is specified, then children that
  13373. * have exactly the specified value must also have a key name less than or equal
  13374. * to the specified key.
  13375. *
  13376. * You can read more about `endAt()` in
  13377. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13378. *
  13379. * @param value - The value to end at. The argument type depends on which
  13380. * `orderBy*()` function was used in this query. Specify a value that matches
  13381. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13382. * value must be a string.
  13383. * @param key - The child key to end at, among the children with the previously
  13384. * specified priority. This argument is only allowed if ordering by child,
  13385. * value, or priority.
  13386. */
  13387. function endAt(value, key) {
  13388. validateKey('endAt', 'key', key, true);
  13389. return new QueryEndAtConstraint(value, key);
  13390. }
  13391. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13392. __extends(QueryEndBeforeConstraint, _super);
  13393. function QueryEndBeforeConstraint(_value, _key) {
  13394. var _this = _super.call(this) || this;
  13395. _this._value = _value;
  13396. _this._key = _key;
  13397. return _this;
  13398. }
  13399. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13400. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13401. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13402. validateLimit(newParams);
  13403. validateQueryEndpoints(newParams);
  13404. if (query._queryParams.hasEnd()) {
  13405. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13406. 'endBefore or equalTo).');
  13407. }
  13408. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13409. };
  13410. return QueryEndBeforeConstraint;
  13411. }(QueryConstraint));
  13412. /**
  13413. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13414. *
  13415. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13416. * allows you to choose arbitrary starting and ending points for your queries.
  13417. *
  13418. * The ending point is exclusive. If only a value is provided, children
  13419. * with a value less than the specified value will be included in the query.
  13420. * If a key is specified, then children must have a value less than or equal
  13421. * to the specified value and a key name less than the specified key.
  13422. *
  13423. * @param value - The value to end before. The argument type depends on which
  13424. * `orderBy*()` function was used in this query. Specify a value that matches
  13425. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13426. * value must be a string.
  13427. * @param key - The child key to end before, among the children with the
  13428. * previously specified priority. This argument is only allowed if ordering by
  13429. * child, value, or priority.
  13430. */
  13431. function endBefore(value, key) {
  13432. validateKey('endBefore', 'key', key, true);
  13433. return new QueryEndBeforeConstraint(value, key);
  13434. }
  13435. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13436. __extends(QueryStartAtConstraint, _super);
  13437. function QueryStartAtConstraint(_value, _key) {
  13438. var _this = _super.call(this) || this;
  13439. _this._value = _value;
  13440. _this._key = _key;
  13441. return _this;
  13442. }
  13443. QueryStartAtConstraint.prototype._apply = function (query) {
  13444. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13445. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13446. validateLimit(newParams);
  13447. validateQueryEndpoints(newParams);
  13448. if (query._queryParams.hasStart()) {
  13449. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13450. 'startBefore or equalTo).');
  13451. }
  13452. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13453. };
  13454. return QueryStartAtConstraint;
  13455. }(QueryConstraint));
  13456. /**
  13457. * Creates a `QueryConstraint` with the specified starting point.
  13458. *
  13459. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13460. * allows you to choose arbitrary starting and ending points for your queries.
  13461. *
  13462. * The starting point is inclusive, so children with exactly the specified value
  13463. * will be included in the query. The optional key argument can be used to
  13464. * further limit the range of the query. If it is specified, then children that
  13465. * have exactly the specified value must also have a key name greater than or
  13466. * equal to the specified key.
  13467. *
  13468. * You can read more about `startAt()` in
  13469. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13470. *
  13471. * @param value - The value to start at. The argument type depends on which
  13472. * `orderBy*()` function was used in this query. Specify a value that matches
  13473. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13474. * value must be a string.
  13475. * @param key - The child key to start at. This argument is only allowed if
  13476. * ordering by child, value, or priority.
  13477. */
  13478. function startAt(value, key) {
  13479. if (value === void 0) { value = null; }
  13480. validateKey('startAt', 'key', key, true);
  13481. return new QueryStartAtConstraint(value, key);
  13482. }
  13483. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13484. __extends(QueryStartAfterConstraint, _super);
  13485. function QueryStartAfterConstraint(_value, _key) {
  13486. var _this = _super.call(this) || this;
  13487. _this._value = _value;
  13488. _this._key = _key;
  13489. return _this;
  13490. }
  13491. QueryStartAfterConstraint.prototype._apply = function (query) {
  13492. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13493. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13494. validateLimit(newParams);
  13495. validateQueryEndpoints(newParams);
  13496. if (query._queryParams.hasStart()) {
  13497. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13498. 'startAfter, or equalTo).');
  13499. }
  13500. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13501. };
  13502. return QueryStartAfterConstraint;
  13503. }(QueryConstraint));
  13504. /**
  13505. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13506. *
  13507. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13508. * allows you to choose arbitrary starting and ending points for your queries.
  13509. *
  13510. * The starting point is exclusive. If only a value is provided, children
  13511. * with a value greater than the specified value will be included in the query.
  13512. * If a key is specified, then children must have a value greater than or equal
  13513. * to the specified value and a a key name greater than the specified key.
  13514. *
  13515. * @param value - The value to start after. The argument type depends on which
  13516. * `orderBy*()` function was used in this query. Specify a value that matches
  13517. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13518. * value must be a string.
  13519. * @param key - The child key to start after. This argument is only allowed if
  13520. * ordering by child, value, or priority.
  13521. */
  13522. function startAfter(value, key) {
  13523. validateKey('startAfter', 'key', key, true);
  13524. return new QueryStartAfterConstraint(value, key);
  13525. }
  13526. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13527. __extends(QueryLimitToFirstConstraint, _super);
  13528. function QueryLimitToFirstConstraint(_limit) {
  13529. var _this = _super.call(this) || this;
  13530. _this._limit = _limit;
  13531. return _this;
  13532. }
  13533. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13534. if (query._queryParams.hasLimit()) {
  13535. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13536. 'or limitToLast).');
  13537. }
  13538. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13539. };
  13540. return QueryLimitToFirstConstraint;
  13541. }(QueryConstraint));
  13542. /**
  13543. * Creates a new `QueryConstraint` that if limited to the first specific number
  13544. * of children.
  13545. *
  13546. * The `limitToFirst()` method is used to set a maximum number of children to be
  13547. * synced for a given callback. If we set a limit of 100, we will initially only
  13548. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13549. * stored in our Database, a `child_added` event will fire for each message.
  13550. * However, if we have over 100 messages, we will only receive a `child_added`
  13551. * event for the first 100 ordered messages. As items change, we will receive
  13552. * `child_removed` events for each item that drops out of the active list so
  13553. * that the total number stays at 100.
  13554. *
  13555. * You can read more about `limitToFirst()` in
  13556. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13557. *
  13558. * @param limit - The maximum number of nodes to include in this query.
  13559. */
  13560. function limitToFirst(limit) {
  13561. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13562. throw new Error('limitToFirst: First argument must be a positive integer.');
  13563. }
  13564. return new QueryLimitToFirstConstraint(limit);
  13565. }
  13566. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13567. __extends(QueryLimitToLastConstraint, _super);
  13568. function QueryLimitToLastConstraint(_limit) {
  13569. var _this = _super.call(this) || this;
  13570. _this._limit = _limit;
  13571. return _this;
  13572. }
  13573. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13574. if (query._queryParams.hasLimit()) {
  13575. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13576. 'or limitToLast).');
  13577. }
  13578. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13579. };
  13580. return QueryLimitToLastConstraint;
  13581. }(QueryConstraint));
  13582. /**
  13583. * Creates a new `QueryConstraint` that is limited to return only the last
  13584. * specified number of children.
  13585. *
  13586. * The `limitToLast()` method is used to set a maximum number of children to be
  13587. * synced for a given callback. If we set a limit of 100, we will initially only
  13588. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13589. * stored in our Database, a `child_added` event will fire for each message.
  13590. * However, if we have over 100 messages, we will only receive a `child_added`
  13591. * event for the last 100 ordered messages. As items change, we will receive
  13592. * `child_removed` events for each item that drops out of the active list so
  13593. * that the total number stays at 100.
  13594. *
  13595. * You can read more about `limitToLast()` in
  13596. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13597. *
  13598. * @param limit - The maximum number of nodes to include in this query.
  13599. */
  13600. function limitToLast(limit) {
  13601. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13602. throw new Error('limitToLast: First argument must be a positive integer.');
  13603. }
  13604. return new QueryLimitToLastConstraint(limit);
  13605. }
  13606. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13607. __extends(QueryOrderByChildConstraint, _super);
  13608. function QueryOrderByChildConstraint(_path) {
  13609. var _this = _super.call(this) || this;
  13610. _this._path = _path;
  13611. return _this;
  13612. }
  13613. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13614. validateNoPreviousOrderByCall(query, 'orderByChild');
  13615. var parsedPath = new Path(this._path);
  13616. if (pathIsEmpty(parsedPath)) {
  13617. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13618. }
  13619. var index = new PathIndex(parsedPath);
  13620. var newParams = queryParamsOrderBy(query._queryParams, index);
  13621. validateQueryEndpoints(newParams);
  13622. return new QueryImpl(query._repo, query._path, newParams,
  13623. /*orderByCalled=*/ true);
  13624. };
  13625. return QueryOrderByChildConstraint;
  13626. }(QueryConstraint));
  13627. /**
  13628. * Creates a new `QueryConstraint` that orders by the specified child key.
  13629. *
  13630. * Queries can only order by one key at a time. Calling `orderByChild()`
  13631. * multiple times on the same query is an error.
  13632. *
  13633. * Firebase queries allow you to order your data by any child key on the fly.
  13634. * However, if you know in advance what your indexes will be, you can define
  13635. * them via the .indexOn rule in your Security Rules for better performance. See
  13636. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13637. * rule for more information.
  13638. *
  13639. * You can read more about `orderByChild()` in
  13640. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13641. *
  13642. * @param path - The path to order by.
  13643. */
  13644. function orderByChild(path) {
  13645. if (path === '$key') {
  13646. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13647. }
  13648. else if (path === '$priority') {
  13649. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13650. }
  13651. else if (path === '$value') {
  13652. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13653. }
  13654. validatePathString('orderByChild', 'path', path, false);
  13655. return new QueryOrderByChildConstraint(path);
  13656. }
  13657. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13658. __extends(QueryOrderByKeyConstraint, _super);
  13659. function QueryOrderByKeyConstraint() {
  13660. return _super !== null && _super.apply(this, arguments) || this;
  13661. }
  13662. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13663. validateNoPreviousOrderByCall(query, 'orderByKey');
  13664. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13665. validateQueryEndpoints(newParams);
  13666. return new QueryImpl(query._repo, query._path, newParams,
  13667. /*orderByCalled=*/ true);
  13668. };
  13669. return QueryOrderByKeyConstraint;
  13670. }(QueryConstraint));
  13671. /**
  13672. * Creates a new `QueryConstraint` that orders by the key.
  13673. *
  13674. * Sorts the results of a query by their (ascending) key values.
  13675. *
  13676. * You can read more about `orderByKey()` in
  13677. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13678. */
  13679. function orderByKey() {
  13680. return new QueryOrderByKeyConstraint();
  13681. }
  13682. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13683. __extends(QueryOrderByPriorityConstraint, _super);
  13684. function QueryOrderByPriorityConstraint() {
  13685. return _super !== null && _super.apply(this, arguments) || this;
  13686. }
  13687. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13688. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13689. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13690. validateQueryEndpoints(newParams);
  13691. return new QueryImpl(query._repo, query._path, newParams,
  13692. /*orderByCalled=*/ true);
  13693. };
  13694. return QueryOrderByPriorityConstraint;
  13695. }(QueryConstraint));
  13696. /**
  13697. * Creates a new `QueryConstraint` that orders by priority.
  13698. *
  13699. * Applications need not use priority but can order collections by
  13700. * ordinary properties (see
  13701. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13702. * for alternatives to priority.
  13703. */
  13704. function orderByPriority() {
  13705. return new QueryOrderByPriorityConstraint();
  13706. }
  13707. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13708. __extends(QueryOrderByValueConstraint, _super);
  13709. function QueryOrderByValueConstraint() {
  13710. return _super !== null && _super.apply(this, arguments) || this;
  13711. }
  13712. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13713. validateNoPreviousOrderByCall(query, 'orderByValue');
  13714. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13715. validateQueryEndpoints(newParams);
  13716. return new QueryImpl(query._repo, query._path, newParams,
  13717. /*orderByCalled=*/ true);
  13718. };
  13719. return QueryOrderByValueConstraint;
  13720. }(QueryConstraint));
  13721. /**
  13722. * Creates a new `QueryConstraint` that orders by value.
  13723. *
  13724. * If the children of a query are all scalar values (string, number, or
  13725. * boolean), you can order the results by their (ascending) values.
  13726. *
  13727. * You can read more about `orderByValue()` in
  13728. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13729. */
  13730. function orderByValue() {
  13731. return new QueryOrderByValueConstraint();
  13732. }
  13733. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13734. __extends(QueryEqualToValueConstraint, _super);
  13735. function QueryEqualToValueConstraint(_value, _key) {
  13736. var _this = _super.call(this) || this;
  13737. _this._value = _value;
  13738. _this._key = _key;
  13739. return _this;
  13740. }
  13741. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13742. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13743. if (query._queryParams.hasStart()) {
  13744. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13745. 'equalTo).');
  13746. }
  13747. if (query._queryParams.hasEnd()) {
  13748. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13749. 'equalTo).');
  13750. }
  13751. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13752. };
  13753. return QueryEqualToValueConstraint;
  13754. }(QueryConstraint));
  13755. /**
  13756. * Creates a `QueryConstraint` that includes children that match the specified
  13757. * value.
  13758. *
  13759. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13760. * allows you to choose arbitrary starting and ending points for your queries.
  13761. *
  13762. * The optional key argument can be used to further limit the range of the
  13763. * query. If it is specified, then children that have exactly the specified
  13764. * value must also have exactly the specified key as their key name. This can be
  13765. * used to filter result sets with many matches for the same value.
  13766. *
  13767. * You can read more about `equalTo()` in
  13768. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13769. *
  13770. * @param value - The value to match for. The argument type depends on which
  13771. * `orderBy*()` function was used in this query. Specify a value that matches
  13772. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13773. * value must be a string.
  13774. * @param key - The child key to start at, among the children with the
  13775. * previously specified priority. This argument is only allowed if ordering by
  13776. * child, value, or priority.
  13777. */
  13778. function equalTo(value, key) {
  13779. validateKey('equalTo', 'key', key, true);
  13780. return new QueryEqualToValueConstraint(value, key);
  13781. }
  13782. /**
  13783. * Creates a new immutable instance of `Query` that is extended to also include
  13784. * additional query constraints.
  13785. *
  13786. * @param query - The Query instance to use as a base for the new constraints.
  13787. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13788. * @throws if any of the provided query constraints cannot be combined with the
  13789. * existing or new constraints.
  13790. */
  13791. function query(query) {
  13792. var e_1, _a;
  13793. var queryConstraints = [];
  13794. for (var _i = 1; _i < arguments.length; _i++) {
  13795. queryConstraints[_i - 1] = arguments[_i];
  13796. }
  13797. var queryImpl = getModularInstance(query);
  13798. try {
  13799. for (var queryConstraints_1 = __values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13800. var constraint = queryConstraints_1_1.value;
  13801. queryImpl = constraint._apply(queryImpl);
  13802. }
  13803. }
  13804. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13805. finally {
  13806. try {
  13807. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13808. }
  13809. finally { if (e_1) throw e_1.error; }
  13810. }
  13811. return queryImpl;
  13812. }
  13813. /**
  13814. * Define reference constructor in various modules
  13815. *
  13816. * We are doing this here to avoid several circular
  13817. * dependency issues
  13818. */
  13819. syncPointSetReferenceConstructor(ReferenceImpl);
  13820. syncTreeSetReferenceConstructor(ReferenceImpl);
  13821. /**
  13822. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13823. * modifying this definition, consult the definition in:
  13824. *
  13825. * https://github.com/firebase/firebase-admin-node
  13826. *
  13827. * and make sure the two are consistent.
  13828. */
  13829. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13830. /**
  13831. * Creates and caches `Repo` instances.
  13832. */
  13833. var repos = {};
  13834. /**
  13835. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13836. */
  13837. var useRestClient = false;
  13838. /**
  13839. * Update an existing `Repo` in place to point to a new host/port.
  13840. */
  13841. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13842. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13843. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  13844. if (tokenProvider) {
  13845. repo.authTokenProvider_ = tokenProvider;
  13846. }
  13847. }
  13848. /**
  13849. * This function should only ever be called to CREATE a new database instance.
  13850. * @internal
  13851. */
  13852. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13853. var dbUrl = url || app.options.databaseURL;
  13854. if (dbUrl === undefined) {
  13855. if (!app.options.projectId) {
  13856. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13857. ' a Project ID when calling firebase.initializeApp().');
  13858. }
  13859. log('Using default host for project ', app.options.projectId);
  13860. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13861. }
  13862. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13863. var repoInfo = parsedUrl.repoInfo;
  13864. var isEmulator;
  13865. var dbEmulatorHost = undefined;
  13866. if (typeof process !== 'undefined' && process.env) {
  13867. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13868. }
  13869. if (dbEmulatorHost) {
  13870. isEmulator = true;
  13871. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13872. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13873. repoInfo = parsedUrl.repoInfo;
  13874. }
  13875. else {
  13876. isEmulator = !parsedUrl.repoInfo.secure;
  13877. }
  13878. var authTokenProvider = nodeAdmin && isEmulator
  13879. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13880. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13881. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13882. if (!pathIsEmpty(parsedUrl.path)) {
  13883. fatal('Database URL must point to the root of a Firebase Database ' +
  13884. '(not including a child path).');
  13885. }
  13886. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13887. return new Database(repo, app);
  13888. }
  13889. /**
  13890. * Remove the repo and make sure it is disconnected.
  13891. *
  13892. */
  13893. function repoManagerDeleteRepo(repo, appName) {
  13894. var appRepos = repos[appName];
  13895. // This should never happen...
  13896. if (!appRepos || appRepos[repo.key] !== repo) {
  13897. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13898. }
  13899. repoInterrupt(repo);
  13900. delete appRepos[repo.key];
  13901. }
  13902. /**
  13903. * Ensures a repo doesn't already exist and then creates one using the
  13904. * provided app.
  13905. *
  13906. * @param repoInfo - The metadata about the Repo
  13907. * @returns The Repo object for the specified server / repoName.
  13908. */
  13909. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13910. var appRepos = repos[app.name];
  13911. if (!appRepos) {
  13912. appRepos = {};
  13913. repos[app.name] = appRepos;
  13914. }
  13915. var repo = appRepos[repoInfo.toURLString()];
  13916. if (repo) {
  13917. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13918. }
  13919. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13920. appRepos[repoInfo.toURLString()] = repo;
  13921. return repo;
  13922. }
  13923. /**
  13924. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13925. */
  13926. function repoManagerForceRestClient(forceRestClient) {
  13927. useRestClient = forceRestClient;
  13928. }
  13929. /**
  13930. * Class representing a Firebase Realtime Database.
  13931. */
  13932. var Database = /** @class */ (function () {
  13933. /** @hideconstructor */
  13934. function Database(_repoInternal,
  13935. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13936. app) {
  13937. this._repoInternal = _repoInternal;
  13938. this.app = app;
  13939. /** Represents a `Database` instance. */
  13940. this['type'] = 'database';
  13941. /** Track if the instance has been used (root or repo accessed) */
  13942. this._instanceStarted = false;
  13943. }
  13944. Object.defineProperty(Database.prototype, "_repo", {
  13945. get: function () {
  13946. if (!this._instanceStarted) {
  13947. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13948. this._instanceStarted = true;
  13949. }
  13950. return this._repoInternal;
  13951. },
  13952. enumerable: false,
  13953. configurable: true
  13954. });
  13955. Object.defineProperty(Database.prototype, "_root", {
  13956. get: function () {
  13957. if (!this._rootInternal) {
  13958. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13959. }
  13960. return this._rootInternal;
  13961. },
  13962. enumerable: false,
  13963. configurable: true
  13964. });
  13965. Database.prototype._delete = function () {
  13966. if (this._rootInternal !== null) {
  13967. repoManagerDeleteRepo(this._repo, this.app.name);
  13968. this._repoInternal = null;
  13969. this._rootInternal = null;
  13970. }
  13971. return Promise.resolve();
  13972. };
  13973. Database.prototype._checkNotDeleted = function (apiName) {
  13974. if (this._rootInternal === null) {
  13975. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13976. }
  13977. };
  13978. return Database;
  13979. }());
  13980. function checkTransportInit() {
  13981. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13982. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13983. }
  13984. }
  13985. /**
  13986. * Force the use of websockets instead of longPolling.
  13987. */
  13988. function forceWebSockets() {
  13989. checkTransportInit();
  13990. BrowserPollConnection.forceDisallow();
  13991. }
  13992. /**
  13993. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13994. */
  13995. function forceLongPolling() {
  13996. checkTransportInit();
  13997. WebSocketConnection.forceDisallow();
  13998. BrowserPollConnection.forceAllow();
  13999. }
  14000. /**
  14001. * Returns the instance of the Realtime Database SDK that is associated
  14002. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  14003. * with default settings if no instance exists or if the existing instance uses
  14004. * a custom database URL.
  14005. *
  14006. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  14007. * Database instance is associated with.
  14008. * @param url - The URL of the Realtime Database instance to connect to. If not
  14009. * provided, the SDK connects to the default instance of the Firebase App.
  14010. * @returns The `Database` instance of the provided app.
  14011. */
  14012. function getDatabase(app, url) {
  14013. if (app === void 0) { app = getApp(); }
  14014. var db = _getProvider(app, 'database').getImmediate({
  14015. identifier: url
  14016. });
  14017. if (!db._instanceStarted) {
  14018. var emulator = getDefaultEmulatorHostnameAndPort('database');
  14019. if (emulator) {
  14020. connectDatabaseEmulator.apply(void 0, __spreadArray([db], __read(emulator), false));
  14021. }
  14022. }
  14023. return db;
  14024. }
  14025. /**
  14026. * Modify the provided instance to communicate with the Realtime Database
  14027. * emulator.
  14028. *
  14029. * <p>Note: This method must be called before performing any other operation.
  14030. *
  14031. * @param db - The instance to modify.
  14032. * @param host - The emulator host (ex: localhost)
  14033. * @param port - The emulator port (ex: 8080)
  14034. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14035. */
  14036. function connectDatabaseEmulator(db, host, port, options) {
  14037. if (options === void 0) { options = {}; }
  14038. db = getModularInstance(db);
  14039. db._checkNotDeleted('useEmulator');
  14040. if (db._instanceStarted) {
  14041. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14042. }
  14043. var repo = db._repoInternal;
  14044. var tokenProvider = undefined;
  14045. if (repo.repoInfo_.nodeAdmin) {
  14046. if (options.mockUserToken) {
  14047. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14048. }
  14049. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14050. }
  14051. else if (options.mockUserToken) {
  14052. var token = typeof options.mockUserToken === 'string'
  14053. ? options.mockUserToken
  14054. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14055. tokenProvider = new EmulatorTokenProvider(token);
  14056. }
  14057. // Modify the repo to apply emulator settings
  14058. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14059. }
  14060. /**
  14061. * Disconnects from the server (all Database operations will be completed
  14062. * offline).
  14063. *
  14064. * The client automatically maintains a persistent connection to the Database
  14065. * server, which will remain active indefinitely and reconnect when
  14066. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14067. * to control the client connection in cases where a persistent connection is
  14068. * undesirable.
  14069. *
  14070. * While offline, the client will no longer receive data updates from the
  14071. * Database. However, all Database operations performed locally will continue to
  14072. * immediately fire events, allowing your application to continue behaving
  14073. * normally. Additionally, each operation performed locally will automatically
  14074. * be queued and retried upon reconnection to the Database server.
  14075. *
  14076. * To reconnect to the Database and begin receiving remote events, see
  14077. * `goOnline()`.
  14078. *
  14079. * @param db - The instance to disconnect.
  14080. */
  14081. function goOffline(db) {
  14082. db = getModularInstance(db);
  14083. db._checkNotDeleted('goOffline');
  14084. repoInterrupt(db._repo);
  14085. }
  14086. /**
  14087. * Reconnects to the server and synchronizes the offline Database state
  14088. * with the server state.
  14089. *
  14090. * This method should be used after disabling the active connection with
  14091. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14092. * and fire the appropriate events so that your client "catches up"
  14093. * automatically.
  14094. *
  14095. * @param db - The instance to reconnect.
  14096. */
  14097. function goOnline(db) {
  14098. db = getModularInstance(db);
  14099. db._checkNotDeleted('goOnline');
  14100. repoResume(db._repo);
  14101. }
  14102. function enableLogging(logger, persistent) {
  14103. enableLogging$1(logger, persistent);
  14104. }
  14105. /**
  14106. * @license
  14107. * Copyright 2021 Google LLC
  14108. *
  14109. * Licensed under the Apache License, Version 2.0 (the "License");
  14110. * you may not use this file except in compliance with the License.
  14111. * You may obtain a copy of the License at
  14112. *
  14113. * http://www.apache.org/licenses/LICENSE-2.0
  14114. *
  14115. * Unless required by applicable law or agreed to in writing, software
  14116. * distributed under the License is distributed on an "AS IS" BASIS,
  14117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14118. * See the License for the specific language governing permissions and
  14119. * limitations under the License.
  14120. */
  14121. function registerDatabase(variant) {
  14122. setSDKVersion(SDK_VERSION$1);
  14123. _registerComponent(new Component('database', function (container, _a) {
  14124. var url = _a.instanceIdentifier;
  14125. var app = container.getProvider('app').getImmediate();
  14126. var authProvider = container.getProvider('auth-internal');
  14127. var appCheckProvider = container.getProvider('app-check-internal');
  14128. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  14129. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  14130. registerVersion(name, version, variant);
  14131. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  14132. registerVersion(name, version, 'esm5');
  14133. }
  14134. /**
  14135. * @license
  14136. * Copyright 2020 Google LLC
  14137. *
  14138. * Licensed under the Apache License, Version 2.0 (the "License");
  14139. * you may not use this file except in compliance with the License.
  14140. * You may obtain a copy of the License at
  14141. *
  14142. * http://www.apache.org/licenses/LICENSE-2.0
  14143. *
  14144. * Unless required by applicable law or agreed to in writing, software
  14145. * distributed under the License is distributed on an "AS IS" BASIS,
  14146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14147. * See the License for the specific language governing permissions and
  14148. * limitations under the License.
  14149. */
  14150. var SERVER_TIMESTAMP = {
  14151. '.sv': 'timestamp'
  14152. };
  14153. /**
  14154. * Returns a placeholder value for auto-populating the current timestamp (time
  14155. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14156. * servers.
  14157. */
  14158. function serverTimestamp() {
  14159. return SERVER_TIMESTAMP;
  14160. }
  14161. /**
  14162. * Returns a placeholder value that can be used to atomically increment the
  14163. * current database value by the provided delta.
  14164. *
  14165. * @param delta - the amount to modify the current value atomically.
  14166. * @returns A placeholder value for modifying data atomically server-side.
  14167. */
  14168. function increment(delta) {
  14169. return {
  14170. '.sv': {
  14171. 'increment': delta
  14172. }
  14173. };
  14174. }
  14175. /**
  14176. * @license
  14177. * Copyright 2020 Google LLC
  14178. *
  14179. * Licensed under the Apache License, Version 2.0 (the "License");
  14180. * you may not use this file except in compliance with the License.
  14181. * You may obtain a copy of the License at
  14182. *
  14183. * http://www.apache.org/licenses/LICENSE-2.0
  14184. *
  14185. * Unless required by applicable law or agreed to in writing, software
  14186. * distributed under the License is distributed on an "AS IS" BASIS,
  14187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14188. * See the License for the specific language governing permissions and
  14189. * limitations under the License.
  14190. */
  14191. /**
  14192. * A type for the resolve value of {@link runTransaction}.
  14193. */
  14194. var TransactionResult = /** @class */ (function () {
  14195. /** @hideconstructor */
  14196. function TransactionResult(
  14197. /** Whether the transaction was successfully committed. */
  14198. committed,
  14199. /** The resulting data snapshot. */
  14200. snapshot) {
  14201. this.committed = committed;
  14202. this.snapshot = snapshot;
  14203. }
  14204. /** Returns a JSON-serializable representation of this object. */
  14205. TransactionResult.prototype.toJSON = function () {
  14206. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14207. };
  14208. return TransactionResult;
  14209. }());
  14210. /**
  14211. * Atomically modifies the data at this location.
  14212. *
  14213. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14214. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14215. * used to modify the existing value to a new value, ensuring there are no
  14216. * conflicts with other clients writing to the same location at the same time.
  14217. *
  14218. * To accomplish this, you pass `runTransaction()` an update function which is
  14219. * used to transform the current value into a new value. If another client
  14220. * writes to the location before your new value is successfully written, your
  14221. * update function will be called again with the new current value, and the
  14222. * write will be retried. This will happen repeatedly until your write succeeds
  14223. * without conflict or you abort the transaction by not returning a value from
  14224. * your update function.
  14225. *
  14226. * Note: Modifying data with `set()` will cancel any pending transactions at
  14227. * that location, so extreme care should be taken if mixing `set()` and
  14228. * `runTransaction()` to update the same data.
  14229. *
  14230. * Note: When using transactions with Security and Firebase Rules in place, be
  14231. * aware that a client needs `.read` access in addition to `.write` access in
  14232. * order to perform a transaction. This is because the client-side nature of
  14233. * transactions requires the client to read the data in order to transactionally
  14234. * update it.
  14235. *
  14236. * @param ref - The location to atomically modify.
  14237. * @param transactionUpdate - A developer-supplied function which will be passed
  14238. * the current data stored at this location (as a JavaScript object). The
  14239. * function should return the new value it would like written (as a JavaScript
  14240. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14241. * transaction will be aborted and the data at this location will not be
  14242. * modified.
  14243. * @param options - An options object to configure transactions.
  14244. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14245. * callback to handle success and failure.
  14246. */
  14247. function runTransaction(ref,
  14248. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14249. transactionUpdate, options) {
  14250. var _a;
  14251. ref = getModularInstance(ref);
  14252. validateWritablePath('Reference.transaction', ref._path);
  14253. if (ref.key === '.length' || ref.key === '.keys') {
  14254. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14255. }
  14256. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14257. var deferred = new Deferred();
  14258. var promiseComplete = function (error, committed, node) {
  14259. var dataSnapshot = null;
  14260. if (error) {
  14261. deferred.reject(error);
  14262. }
  14263. else {
  14264. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14265. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14266. }
  14267. };
  14268. // Add a watch to make sure we get server updates.
  14269. var unwatcher = onValue(ref, function () { });
  14270. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14271. return deferred.promise;
  14272. }
  14273. /**
  14274. * @license
  14275. * Copyright 2017 Google LLC
  14276. *
  14277. * Licensed under the Apache License, Version 2.0 (the "License");
  14278. * you may not use this file except in compliance with the License.
  14279. * You may obtain a copy of the License at
  14280. *
  14281. * http://www.apache.org/licenses/LICENSE-2.0
  14282. *
  14283. * Unless required by applicable law or agreed to in writing, software
  14284. * distributed under the License is distributed on an "AS IS" BASIS,
  14285. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14286. * See the License for the specific language governing permissions and
  14287. * limitations under the License.
  14288. */
  14289. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14290. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14291. this.sendRequest('q', { p: pathString }, onComplete);
  14292. };
  14293. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14294. PersistentConnection.prototype.echo = function (data, onEcho) {
  14295. this.sendRequest('echo', { d: data }, onEcho);
  14296. };
  14297. /**
  14298. * @internal
  14299. */
  14300. var hijackHash = function (newHash) {
  14301. var oldPut = PersistentConnection.prototype.put;
  14302. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14303. if (hash !== undefined) {
  14304. hash = newHash();
  14305. }
  14306. oldPut.call(this, pathString, data, onComplete, hash);
  14307. };
  14308. return function () {
  14309. PersistentConnection.prototype.put = oldPut;
  14310. };
  14311. };
  14312. /**
  14313. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14314. * @internal
  14315. */
  14316. var forceRestClient = function (forceRestClient) {
  14317. repoManagerForceRestClient(forceRestClient);
  14318. };
  14319. /**
  14320. * Firebase Realtime Database
  14321. *
  14322. * @packageDocumentation
  14323. */
  14324. registerDatabase();
  14325. export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
  14326. //# sourceMappingURL=index.esm5.js.map